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

import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.constant.UserConstants;
import com.sifang.modules.sunshine.SystemSetting.service.TraderService;
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.constant.DeliverOrderConstants;
import com.sifang.modules.supply.order.entity.CrmSupplyMaterialDeliverOrder;
import com.sifang.modules.supply.order.entity.CrmSupplyMaterialDeliverOrderMsg;
import com.sifang.modules.supply.order.request.*;
import com.sifang.modules.supply.order.service.CrmSupplyMaterialDeliverOrderService;
import com.sifang.modules.supply.order.service.DeliverOrderService;
import com.sifang.modules.supply.setting.entity.CrmSupplySupplier;
import com.sifang.modules.supply.setting.service.CrmSupplyDeliveryMethodService;
import com.sifang.modules.supply.setting.service.CrmSupplySupplierService;
import com.sifang.modules.supply.setting.service.CrmSupplyWarehouseSettingService;
import com.sifang.modules.supply.stock.utils.MaterialUtils;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.entity.Ascription;
import com.sifang.modules.sys.entity.Operator;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.GuardUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.web.BaseExceptionController;
import org.apache.commons.lang3.StringUtils;
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.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 发货单管理
 */
@Controller
@RequestMapping("${adminPath}/material/order")
public class DeliverOrderController extends BaseExceptionController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    CrmSupplyDeliveryMethodService deliveryMethodService;

    @Autowired
    DeliverOrderService deliverOrderService;

    @Autowired
    CrmSupplySupplierService supplierService;

    @Autowired
    private TraderService traderService;

    @Autowired
    private CrmSupplyWarehouseSettingService warehouseSettingService;
    /**
     * 采购分配 列表页面
     */
    @RequestMapping("/deliverOrderList")
    public String deliverOrderList(HttpServletRequest request, Model model) {
        List<Record> methods = deliveryMethodService.listDeliverMethods();
        model.addAttribute("deliverMethods", methods);
        //供应链的发货单或供应商的发货单
        Ascription ascription = CrmUtils.getAscription();
        model.addAttribute("deliverId", ascription.getAscriptionId());
        List<Record> traders = traderService.getAllTrader();
        model.addAttribute("traders", traders);
        Map<String, String> map = getParams(request);
        model.addAttribute("map", map);
        return "modules/supply/order/deliverOrderList";
    }

    /**
     * 采购分配 列表数据
     */
    @ResponseBody
    @RequestMapping(value = "ajaxForDeliverOrderData")
    public Object ajaxForDeliverOrderData(HttpServletRequest request) {
        LayuiPage<Record> page = new LayuiPage<>(request);
        Map<String, String> params = getParams(request);
        params.put("fixedStatus", "2,9,a");// 采购分配 查询状态2，9的数据
        params.put("types","1,2,3,4");
        deliverOrderService.deliverOrderListPage(page, params);
        return page.renderJson();
    }

    /**
     * 分配页面
     */
    @RequestMapping(value = "toAllocationPage")
    public String toAllocationPage(String id, Model model) {
        Record order = deliverOrderService.findOrderById(id);
        model.addAttribute("order", order);
        List<Record> details = deliverOrderService.findDetailsByOrderId(id);
        model.addAttribute("details", details);
        BigDecimal total = BigDecimal.ZERO;
        String brand ="";
        boolean difBrand = true;
        for (Record r : details) {
            total = total.add(r.getBigDecimal("purchase_price").multiply(r.getBigDecimal("apply_amount")).setScale(2, RoundingMode.HALF_UP));
            if(StringUtil.isNotBlank(brand)&& !brand.equals(r.getStr("material_brand"))){
                difBrand = false;
               break;
            }else{
                brand = r.getStr("material_brand");
            }
        }
        model.addAttribute("total", total);// 采购总额
        if (difBrand) {
            model.addAttribute("supplies", warehouseSettingService.getSupplyListByBrand(brand));
        }

      //  CrmTrader trader = traderService.getById(order.getStr("traderId"));
        // 供应链仓库
       // List<Record> warehouses = warehouseSettingService.supplyChainWarehouses2(trader.getProvince(),trader.getCity());
        List<Record> warehouses = warehouseSettingService.supplyChainWarehouses2("","");
        model.addAttribute("warehouses", warehouses);
        return "modules/supply/order/allocationPage";
    }


    /**
     * 分配
     */
    @ResponseBody
    @RequestMapping(value = "allocation")
    public Result<Void> allocation(@Validated @RequestBody AllocationReq req) {
        logger.info("into allocation, req={}", req);
        deliverOrderService.allocation(req);
        return Result.ok();
    }

    /**
     * 驳回
     */
    @ResponseBody
    @RequestMapping(value = "reject")
    public Result<Void> reject(String id) {
        logger.info("into allocation, req={}", id);
        Operator operator = Operator.of(UserUtils.getUser());
        int result= deliverOrderService.reject(id,operator);
        if(result>0){
            return Result.ok();
        }
        return Result.fail("驳回失败");
    }

    /**
     * 分配驳回
     */
    @ResponseBody
    @RequestMapping(value = "allocationReject")
    public Result<Void> allocationReject(@Validated @RequestBody CommonRejectReq req) {
        logger.info("into allocationReject, req={}", req);
        deliverOrderService.allocationReject(req);
        return Result.ok();
    }

    /**
     * 合并订单
     */
    @ResponseBody
    @RequestMapping(value = "mergeDeliverOrder")
    public Result<Void> mergeDeliverOrder(String ids) {
        GuardUtils.notBlank(ids, "请选择订单");
        logger.info("into mergeOrder, ids={}", ids);
        deliverOrderService.mergeDeliverOrder(ids, Operator.of(UserUtils.getUser()));
        return Result.ok();
    }

    /**
     * 订单详情页
     */
    @RequestMapping("/toDeliverPage")
    public String toDeliverPage(String id, String opt, Model model){
        Record order = deliverOrderService.findOrderById(id);
        model.addAttribute("order", order);
        List<Record> details = deliverOrderService.findDetails(id);
        model.addAttribute("details", details);
        //过程记录
        List<CrmSupplyMaterialDeliverOrderMsg> msgList = deliverOrderService.listMsgByOrderId(id);
        model.addAttribute("msgList", msgList);
        //发货方式
//        List<Record> methods = MaterialUtils.getDeliveryMethod();
        model.addAttribute("opt", opt);
//        model.addAttribute("methods", methods);
        if(StringUtil.isNotBlank(order.getStr("deliver_method_id"))){
            model.addAttribute("methodType",deliveryMethodService.getTypeDetai(order.getStr("deliver_method_id")).getType());
        }
        BigDecimal total = BigDecimal.ZERO;
        for (Record r : details) {
            total = total.add(r.getBigDecimal("purchase_price").multiply(r.getBigDecimal("out_amount")).setScale(2, RoundingMode.HALF_UP));
        }

        Integer quaimgsCount=0;
        if(StringUtil.isNotBlank(order.getStr("delivery_voucher"))){
            String[] arr=order.getStr("delivery_voucher").split(",");
            model.addAttribute("quaimgs",arr);
            quaimgsCount=arr.length;
        }
        model.addAttribute("quaimgsCount",quaimgsCount);
        model.addAttribute("total", total);
        User user = UserUtils.getUser();
        model.addAttribute("user",user);
        model.addAttribute("relationReturnOrder",deliverOrderService.relationReturnOrder(id));
        if (StringUtils.isNotBlank(order.getStr("receive_invoice"))) {
            String[] imgArr = order.getStr("receive_invoice").split(",");
            List<String> imglist = new ArrayList<>();
            Collections.addAll(imglist, imgArr);
            model.addAttribute("imglist", imglist);
            model.addAttribute("pdfsCount", imglist.size());
            model.addAttribute("id", id);
        }
        return "modules/supply/order/doDeliver";
    }

    /**
     * 订单详情页
     */
    @RequestMapping("/toDeliverPagea")
    public String toDeliverPagea(String id, String opt, Model model){
        Record order = deliverOrderService.findOrderById(id);
        model.addAttribute("order", order);
        List<Record> details = deliverOrderService.findDetails(id);
        model.addAttribute("details", details);
        //过程记录
        List<CrmSupplyMaterialDeliverOrderMsg> msgList = deliverOrderService.listMsgByOrderId(id);
        model.addAttribute("msgList", msgList);
        //发货方式
        List<Record> methods = MaterialUtils.getDeliveryMethod();
        model.addAttribute("opt", opt);
        model.addAttribute("methods", methods);
        BigDecimal total = BigDecimal.ZERO;
        for (Record r : details) {
            total = total.add(r.getBigDecimal("purchase_price").multiply(r.getBigDecimal("out_amount")).setScale(2, RoundingMode.HALF_UP));
        }

        Integer quaimgsCount=0;
        if(StringUtil.isNotBlank(order.getStr("delivery_voucher"))){
            String[] arr=order.getStr("delivery_voucher").split(",");
            model.addAttribute("quaimgs",arr);
            quaimgsCount=arr.length;
        }
        model.addAttribute("quaimgsCount",quaimgsCount);
        model.addAttribute("total", total);
        User user = UserUtils.getUser();
        model.addAttribute("user",user);
        model.addAttribute("relationReturnOrder",deliverOrderService.relationReturnOrder(id));
        if (StringUtils.isNotBlank(order.getStr("receive_invoice"))) {
            String[] imgArr = order.getStr("receive_invoice").split(",");
            List<String> imglist = new ArrayList<>();
            Collections.addAll(imglist, imgArr);
            model.addAttribute("imglist", imglist);
        }
        return "modules/supply/order/doDelivera";
    }

    /**
     * 发货页面
     */
    @RequestMapping("toDeliverForm")
    public String toDeliverForm(String id, Model model) {
        Record order = deliverOrderService.findOrderById(id);
        model.addAttribute("order", order);
        List<Record> details = deliverOrderService.findDetailsByOrderId(id);
        model.addAttribute("details", details);
        //发货方式
        List<Record> methods = MaterialUtils.getDeliveryMethod();
        model.addAttribute("methods", methods);
        BigDecimal total = BigDecimal.ZERO;
        for (Record r : details) {
            total = total.add(r.getBigDecimal("purchase_price").multiply(r.getBigDecimal("apply_amount")).setScale(2, RoundingMode.HALF_UP));
        }
        model.addAttribute("total", total);
        // 供应链仓库
        List<Record> warehouses = warehouseSettingService.supplyChainWarehouses();
        model.addAttribute("warehouses", warehouses);
        model.addAttribute("userType",UserUtils.getUser().getUserType());
        Integer quaimgsCount=0;
        if(StringUtil.isNotBlank(order.getStr("delivery_voucher"))){
            String[] arr=order.getStr("delivery_voucher").split(",");
            model.addAttribute("quaimgs",arr);
            quaimgsCount=arr.length;
        }
        model.addAttribute("quaimgsCount",quaimgsCount);
        return "modules/supply/order/deliverForm";
    }


    /**
     * 发货审核页面
     */
    @RequestMapping("/sendToExamine")
    public String sendToExamine(String id, Model model){
        Record order = deliverOrderService.findOrderById(id);
        List<Record> details = deliverOrderService.findDetailsByOrderId(id);
        //供应链入库或代理商入库
        Ascription ascription = CrmUtils.getAscription();
        model.addAttribute("inAscriptionId", ascription.getAscriptionId());
        // 发货方式
        if(StringUtil.isNotBlank(order.getStr("deliver_method_id"))){
            // 发货方式
            model.addAttribute("methodType",deliveryMethodService.getTypeDetai(order.getStr("deliver_method_id")).getType());
        }
        model.addAttribute("id", id);
        model.addAttribute("order", order);
        model.addAttribute("details", details);

        if(StringUtil.isNotBlank(order.getStr("delivery_voucher"))){
            String[] arr=order.getStr("delivery_voucher").split(",");
            model.addAttribute("quaimgs",arr);
        }
        return "modules/supply/order/sendToExamine";
    }
    /**
     * 发货审核通过
     */
    @ResponseBody
    @RequestMapping(value = "passThrough")
    public Result<Void> passThrough(String id,String type,String examineRemark) {
            GuardUtils.notBlank(id,"id参数不能为空");
        deliverOrderService.passThrough(id,type,examineRemark,Operator.of(UserUtils.getUser()));
        return Result.ok();
    }



    /**
     * 发货打回
     */
    @ResponseBody
    @RequestMapping(value = "deliverReject")
    public Result<Void> deliverReject(@Validated @RequestBody CommonRejectReq req) {
        logger.info("into deliverReject, req={}", req);
        deliverOrderService.deliverReject(req,Operator.of(UserUtils.getUser()));
        return Result.ok();
    }

    /**
     * 拒发货
     */
    @ResponseBody
    @RequestMapping(value = "deliverRejectBatch")
    public Result<Void> deliverRejectBatch(@Validated @RequestBody CommonRejectReq req) {
        logger.info("into deliverReject, req={}", req);
        deliverOrderService.deliverRejectBatch(req);
        return Result.ok();
    }

    /**
     * 打印
     */
    @RequestMapping("/printOrder")
    public String printOrder(String applyId, Model model) {
        Record apply = deliverOrderService.findOrderById(applyId);
        model.addAttribute("apply", apply);
        String deliver_name="";
        if("a".equals(apply.getStr("deliver_id"))){
            //供应链 -- 取仓库名称
            deliver_name=apply.getStr("outWarehouseName");
        }else{
            //取供应商编码
            CrmSupplySupplier supplier = supplierService.getById(apply.getStr("deliver_id"));
          //  deliver_name = supplier.getNumber();
        }

        model.addAttribute("deliver_name", deliver_name);
        List<Record> details = deliverOrderService.findDetailsByOrderId(applyId);
        model.addAttribute("applyDetails", details);
        return "modules/supply/order/printOrder";
    }


    /**
     * 发货单拆单
     */
    @ResponseBody
    @RequestMapping("/splitDeliverOrder")
    public Result splitDeliverOrder(@Valid @RequestBody AllocationReq allocationReq){
        logger.info(" AllocationReq = {}", allocationReq);
        TraderOrderReq traderOrderReq = new TraderOrderReq();
        traderOrderReq.setOrderId(allocationReq.getId());
        traderOrderReq.setDetails(allocationReq.getSplitDetails());
        deliverOrderService.splitDeliverOrder(allocationReq,traderOrderReq, Operator.of(UserUtils.getUser()));
        return Result.ok();
    }

    /**
     * 发货单发货
     */
    @ResponseBody
    @RequestMapping("/doDeliver")
    public Result doDeliver(@Valid @RequestBody DeliverReq req){
        User user = UserUtils.getUser();
        String userName = "";
        if(UserConstants.TYPE_SUPPLIER.equals(user.getUserType())){
            userName = "供应商";
        }else{
            userName=CrmUtils.getUserXM(user);
            GuardUtils.notBlank(req.getOutWarehouseId(), "发货仓库不能为空");
        }
        deliverOrderService.doDeliver(req, Operator.of(user.getId(), userName, user.getUserType()), "1");
        return Result.ok();
    }

    /**
     * 发货单暂存
     */
    @ResponseBody
    @RequestMapping("/doTemporary")
     public Result doTemporary(HttpServletRequest request){

        String orderId = request.getParameter("orderId");
        String deliverMethodId= request.getParameter("deliverMethodId");
        String expressNo= request.getParameter("expressNo");
        String deliverRemark= request.getParameter("deliverRemark");
        String deliverDriver= request.getParameter("deliverDriver");
        String deliverMobile= request.getParameter("deliverMobile");
        String deliverCarNum= request.getParameter("deliverCarNum");
        DeliverReq req = new DeliverReq();
        req.setDeliverCarNum(deliverCarNum);
        req.setDeliverDriver(deliverDriver);
        req.setDeliverMethodId(deliverMethodId);
        req.setDeliverMobile(deliverMobile);
        req.setDeliverRemark(deliverRemark);
        req.setType("2");
        req.setExpressNo(expressNo);
        TraderOrderReq or =   new TraderOrderReq();
        or.setOrderId(orderId);
        req.setMaterialInfo(or);
        User user = UserUtils.getUser();
        String userName = "";
        if(UserConstants.TYPE_SUPPLIER.equals(user.getUserType())){
            userName = "供应商";
        }else{
            userName=CrmUtils.getUserXM(user);
        }
        deliverOrderService.doDeliver(req,  Operator.of(user.getId(),userName,user.getUserType()),"2");
        return Result.ok();
        }


    /**
     * 物料清单
     */
    @RequestMapping("/materialList")
    public String materialList(String id, Model model){
        CrmSupplyMaterialDeliverOrder order = deliverOrderService.findByOrderId(id);

        List<Record> details = deliverOrderService.findDetailsByOrderId(id);
        model.addAttribute("details", details);
        BigDecimal total = BigDecimal.ZERO;
        for (Record r : details) {
            total = total.add(r.getBigDecimal("purchase_price").multiply(r.getBigDecimal("apply_amount")).setScale(2, RoundingMode.HALF_UP));
        }
        model.addAttribute("order", order);
        model.addAttribute("total", total);
        model.addAttribute("user", UserUtils.getUser());
        if (StringUtil.equalsAny(order.getStatus(), DeliverOrderConstants.STATUS_WAIT_DELIVER, DeliverOrderConstants.STATUS_WAIT_SIGN_IN,
                DeliverOrderConstants.STATUS_COMPLETED, DeliverOrderConstants.STATUS_DELIVER_REJECT)) {
            model.addAttribute("tyoeor","2");
        }else{
            model.addAttribute("tyoeor","1");
        }

        return "modules/supply/order/materialList";
    }
    /**
     * 删除订单
    */
    @ResponseBody
    @RequestMapping("deleteOrder")
    public Object deleteOrder(String orderId) throws CustomException {
        if(!StringUtil.isBlank(orderId)){
            deliverOrderService.deleteOrder(orderId);
           return  Result.ok();
        }
        return Result.fail("参数为空");
    }

    /**
     * 订单查询列表数据
     */
    @ResponseBody
    @RequestMapping(value = "ajaxForAllDeliverOrder")
    public Object ajaxForAllDeliverOrder(HttpServletRequest request) {
        Map<String, String> params = getParams(request);
        User user = UserUtils.getUser();
        String ascriptionId = CrmUtils.getAscription().getAscriptionId();
        if (StringUtil.endsWithAny(user.getUserType(), User.USER_TYPE_KJ, User.USER_TYPE_ADVISOR)) {
            params.put("traderId", ascriptionId);
        }
        LayuiPage<Record> page = new LayuiPage<>(request);
        deliverOrderService.deliverOrderListPage(page, params);
        return page.renderJson();
    }

    /**
     * 已完成订单 页面
     */
    @RequestMapping(value = "completedOrder")
    public String completedOrderList(HttpServletRequest request, Model model) {
        List<Record> methods = deliveryMethodService.listDeliverMethods();
        model.addAttribute("deliverMethods", methods);
        User user = UserUtils.getUser();
        String ascriptionId = CrmUtils.getAscription().getAscriptionId();
        if (StringUtil.endsWithAny(user.getUserType(), User.USER_TYPE_KJ, User.USER_TYPE_ADVISOR)) {
            model.addAttribute("applyTraderId", ascriptionId);
        }
        model.addAttribute("supplies", warehouseSettingService.getSupplyList());
        model.addAttribute("warehouses", MaterialUtils.getWarehouseList());
        model.addAttribute("ascriptionId", ascriptionId);
        model.addAttribute("userType", user.getUserType());
        List<Record> traders = traderService.getAllTopTrader();
        model.addAttribute("traders", traders);
        model.addAttribute("map", getParams(request));
        return "modules/supply/order/completedDeliverOrder";
    }

    /**
     * 已完成订单 列表数据
     */
    @ResponseBody
    @RequestMapping(value = "ajaxForCompletedOrderData")
    public Object ajaxForCompletedOrderData(HttpServletRequest request) {
        Map<String, String> params = getParams(request);
        LayuiPage<Record> page = new LayuiPage<>(request);
        params.put("fixedStatus", "7");// 已完成订单状态是7
        deliverOrderService.deliverOrderListPage(page, params);
        return page.renderJson();
    }

    /**
     * 保存物料申请单--自主下单
     *
     */
    @ResponseBody
    @RequestMapping("/saveApplyOrder")
    public Result saveApplyOrder(@Valid @RequestBody ApplyOrderReq req) {
        deliverOrderService.saveApplyOrder(req, Operator.of(UserUtils.getUser()));
        return Result.ok();
    }

    @ResponseBody
    @RequestMapping("/updateReceiveInvoice")
    public Result updateReceiveInvoice(String orderId ,String receiveInvoice){
        return deliverOrderService.updateReceiveInvoice(orderId, receiveInvoice);
    }
}
