package com.sifang.modules.supply.order.controller;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.CustomException;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.supply.order.entity.CrmSupplyMaterialReturnOrderMsg;
import com.sifang.modules.supply.order.request.AddReturnOrderReq;
import com.sifang.modules.supply.order.service.DeliverOrderService;
import com.sifang.modules.supply.order.service.MaterialReturnOrderService;
import com.sifang.modules.supply.stock.utils.MaterialUtils;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.web.BaseExceptionController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("${adminPath}/material/return")
public class MaterialReturnOrderController extends BaseExceptionController {

    Logger logger = LoggerFactory.getLogger(MaterialReturnOrderController.class);

    @Autowired
    private MaterialReturnOrderService returnOrderService;
    @Autowired
    private DeliverOrderService deliverOrderService;


    @RequestMapping("returnOrder")
    public String returnOrder(Model model) {
        model.addAttribute("traderList", CrmUtils.findAllTrader());
        return "modules/supply/return/returnOrderList";
    }

    @ResponseBody
    @RequestMapping("ajaxForRetenOrderList")
    public Object ajaxForRetenOrderList(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        LayuiPage<Record> page = new LayuiPage<>(request);
        returnOrderService.returnOrderPageList(page, map);
        return page.renderJson();
    }

    /**
     * 订单退货
     */
    @RequestMapping(value = "addReturnOrder")
    public String addReturnOrder(Model model, HttpServletRequest request) {
        List<Record> deliveryMethodList = MaterialUtils.getDeliveryMethod();
        List<Record> warehouseList = MaterialUtils.findMaterialWarehouse("1","");
        model.addAttribute("deliveryMethodList", deliveryMethodList);
        model.addAttribute("warehouseList", warehouseList);

        return "modules/supply/return/addReturnOrder";
    }

    @RequestMapping(value = "addReturnOrderFromCompleteOrder")
    public String addReturnOrderFromCompleteOrder(Model model, HttpServletRequest request) {
        List<Record> deliveryMethodList = MaterialUtils.getDeliveryMethod();
        List<Record> warehouseList = MaterialUtils.findMaterialWarehouse("1","");
        model.addAttribute("deliveryMethodList", deliveryMethodList);
        model.addAttribute("warehouseList", warehouseList);

        String id = request.getParameter("id");
        Record order = deliverOrderService.findOrderById(id);
        List<Record> details = returnOrderService.findDeliverOrderById(id);
        model.addAttribute("order", order);
        model.addAttribute("details", details);
        return "modules/supply/return/addReturnOrderFromCompleteOrder";
    }

    /**
     * 根据订单编号查询订单
     */
    @ResponseBody
    @RequestMapping("findDeliverOrderByNumber")
    public Object findDeliverOrderByNumber(HttpServletRequest request) {
        String code = request.getParameter("code");
        String belongType = request.getParameter("belongType");
        if (StringUtil.isBlank(code)) {
            return Result.fail("2003", "参数为空");
        }
        return returnOrderService.findDeliverOrderByNumber(code,belongType);
    }

    /**
     * 退货单保存
     */
    @ResponseBody
    @RequestMapping(value = "saveReturnOrder")
    public Result saveReturnOrder(@Valid @RequestBody AddReturnOrderReq orderVo, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return errRet(bindingResult);
        }
        logger.info(" into addReturnOrder orderVo={}", JSONObject.toJSONString(orderVo));
        returnOrderService.addReturnOrder(orderVo);
        return Result.ok();
    }

    /**
     * 电站退货单保存
     */
    @ResponseBody
    @RequestMapping(value = "saveReturnPSOrder")
    public Result saveReturnPSOrder(@Valid @RequestBody AddReturnOrderReq orderVo, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return errRet(bindingResult);
        }
        logger.info(" into addReturnOrder orderVo={}", JSONObject.toJSONString(orderVo));
        returnOrderService.addReturnOrderPS(orderVo);
        return Result.ok();
    }

    /**
     * 获取发货方式详情
     */
    @ResponseBody
    @RequestMapping("getReturnMethodDetail")
    public Object getReturnMethodDetail(HttpServletRequest request) {
        String returnMethodId = request.getParameter("returnMethodId");
        return returnOrderService.getReturnMethodDetail(returnMethodId);
    }


    /**
     * 代理商退货页面
     * */
    @RequestMapping("traderReturnOrder")
    public String traderReturnOrder(Model model) {
        List<Record> deliveryMethodList = MaterialUtils.getDeliveryMethod();
        model.addAttribute("deliveryMethodList", deliveryMethodList);
        return "modules/supply/return/traderReturnOrder";
    }

    @ResponseBody
    @RequestMapping("ajaxForTraderRetenOrderList")
    public Object ajaxForTraderRetenOrderList(HttpServletRequest request) {
        String traderId = CrmUtils.getAscription().getAscriptionId();
        Map<String, String> map = getParams(request);
        LayuiPage<Record> page = new LayuiPage<>(request);
        returnOrderService.getTraderReturnList(page, map, traderId);
        return page.renderJson();
    }

    /**
     * 供应商退货页面
     * */
    @RequestMapping("supplyReturnOrder")
    public String supplyReturnOrder(Model model) {
        return "modules/supply/return/supplyOrderList";
    }

    @ResponseBody
    @RequestMapping("/ajaxForSupplyRetenOrderList")
    public Object ajaxForSupplyRetenOrderList(HttpServletRequest request) {
        String supplyId = CrmUtils.getAscription().getAscriptionId();
        Map<String, String> map = getParams(request);
        LayuiPage<Record> page = new LayuiPage<>(request);
        returnOrderService.getSupplyReturnList(page, map, supplyId);
        return page.renderJson();
    }

    /**
     * 新增代理商订单退货
     */
    @RequestMapping(value = "addTraderReturnOrder")
    public String addTraderReturnOrder(Model model) {
        List<Record> deliveryMethodList = MaterialUtils.getDeliveryMethod();
        List<Record> warehouseList = MaterialUtils.getWarehouseList();
        model.addAttribute("deliveryMethodList", deliveryMethodList);
        model.addAttribute("warehouseList", warehouseList);
        return "modules/supply/return/addTraderReturnOrder";
    }

    /**
     * 新增代理商电站退货
     */
    @RequestMapping(value = "addPSReturnOrder")
    public String addPSReturnOrder(Model model) {
        List<Record> warehouseList = MaterialUtils.getWarehouseList();
        model.addAttribute("warehouseList", warehouseList);
        return "modules/supply/return/addPSReturnOrder";
    }

    /**
     * 根据电站编号查询订单
     */
    @ResponseBody
    @RequestMapping("findPSOrderByNumber")
    public Object findPSOrderByNumber(HttpServletRequest request) {
        String code = request.getParameter("code");
        if (StringUtil.isBlank(code)) {
            return Result.fail("2003", "参数为空");
        }
        String traderId = CrmUtils.getAscription().getAscriptionId();
        return returnOrderService.findPSOrderByNumber(code,traderId);
    }

    /**
     * 平台退货单入库页
     */
    @RequestMapping("confirmOrder")
    public String confirmOrder(String id, String source, Model model){
        Record order = returnOrderService.findOrderById(id);
        model.addAttribute("order", order);
        List<Record> details = returnOrderService.getAllDetail(id);
        model.addAttribute("details", details);
        if ("3".equals(order.getStr("type"))) {
            model.addAttribute("source", source);
            return "modules/supply/return/confirmOrder";
        } else {
            List<Record> warehouseList = MaterialUtils.findMaterialWarehouseByAscriptionId("a");
            model.addAttribute("warehouseList", warehouseList);
            return "modules/supply/return/confirmTraderOrder";
        }
    }

    /**
     * 平台退货-确认收货
     */
    @ResponseBody
    @RequestMapping(value = "confirmReturnOrder")
    public Result confirmReturnOrder(String id, String voucherImgs) {
        logger.info(">>>>>>>>>>>>> into outAllocationOrder returnOrderId={},voucherImgs={}", id, voucherImgs);
        try {
            returnOrderService.confirmReturnOrder(id, voucherImgs);
        } catch (BusinessException e) {
            return Result.fail(e.getErrorCode(),e.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage());
            return Result.fail("502","操作失败");
        }

        return Result.ok();
    }


    /**
     * 代理商订单退货-确认收货
     */
    @ResponseBody
    @RequestMapping(value = "confirmTraderReturnOrder")
    public Result confirmTraderReturnOrder(String id, String warehouseId, String voucherImgs) {
        logger.info(">>>>>>>>>>>>> into outAllocationOrder returnOrderId={},warehouseId={},voucherImgs={}", id, warehouseId,voucherImgs);
        try {
            returnOrderService.confirmTraderReturnOrder(id, warehouseId, voucherImgs);
        } catch (BusinessException e) {
            return Result.fail(e.getErrorCode(),e.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage());
            return Result.fail("502","操作失败");
        }
        return Result.ok();
    }

    /**
     * 退货单详情
     */
    @RequestMapping("showDetail")
    public String showDetail(String id, Model model){
        Record order = returnOrderService.findOrderById(id);
        model.addAttribute("order", order);
        List<Record> details = returnOrderService.getAllDetail(id);
        model.addAttribute("details", details);
        //过程记录
        List<CrmSupplyMaterialReturnOrderMsg> msgList = returnOrderService.listMsgByOrderId(id);
        model.addAttribute("msgList", msgList);
        if (StringUtil.isNotBlank(order.getStr("voucher_img"))) {
            model.addAttribute("voucherImgList", order.getStr("voucher_img").split(","));
        }
        model.addAttribute("user", UserUtils.getUser());
        return "modules/supply/return/showDetail";
    }

    /**
     * 关联订单详情页
     */
    @RequestMapping("toDeliverPage")
    public String toDeliverPage(String id, Model model){
        Record order = deliverOrderService.findOrderById(id);
        model.addAttribute("order", order);
        List<Record> details = deliverOrderService.findDetailsByOrderId(id);
        model.addAttribute("details", details);
        return "modules/supply/return/doDeliver";
    }

    /**
     * 关联电站详情页
     */
    @RequestMapping("toPSPage")
    public String toPSPage(String id, Model model){
        Record order = returnOrderService.getCustomerEntryById(id);
        model.addAttribute("order", order);
        model.addAttribute("warehouseName", returnOrderService.getWarehouseName(id));
        List<Record> details = returnOrderService.findPSOrderById(id);
        model.addAttribute("details", details);
        return "modules/supply/return/psPage";
    }

    /**
     * 物料清单
     */
    @RequestMapping("materialList")
    public String materialList(String id, Model model){
        List<Record> details = returnOrderService.getAllDetail(id);
        model.addAttribute("details", details);
        return "modules/supply/return/materialList";
    }

    /**
     * 删除退货单
     */
    @ResponseBody
    @RequestMapping("deleteOrder")
    public Object deleteOrder(String orderId) throws CustomException {
        if(StringUtil.isNotBlank(orderId)){
            returnOrderService.deleteOrder(orderId);
            return  Result.ok();
        }
        return Result.fail("参数为空");
    }

    /**
     * 退货单驳回
     */
    @ResponseBody
    @RequestMapping("returnReject")
    public Object returnReject(String id, String reason) throws CustomException {
        if(StringUtil.isNotBlank(id)){
            returnOrderService.returnReject(id,reason);
            return  Result.ok();
        }
        return Result.fail("参数为空");
    }

    /**
     * 供应商退货单编辑页面
     */
    @RequestMapping("editPage")
    public String editPage(String id, Model model) {
        Record order = returnOrderService.findOrderById(id);
        model.addAttribute("order", order);
        List<Record> details = returnOrderService.getAllDetail(id);
        model.addAttribute("details", details);
        for (Record r : details) {
            BigDecimal num = returnOrderService.findAllReturnedNum(order.getStr("relation_id"),r.getStr("material_id"),order.getStr("id"));
            r.set("returnedNum",num);
        }
        List<Record> warehouseList = MaterialUtils.getWarehouseList();
        model.addAttribute("warehouseList", warehouseList);
        List<Record> deliveryMethodList = MaterialUtils.getDeliveryMethod();
        model.addAttribute("deliveryMethodList", deliveryMethodList);
        return "modules/supply/return/editTraderReturnOrder";

    }

}
