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

import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.supply.order.entity.CrmSupplyMaterialApplyMsg;
import com.sifang.modules.supply.order.entity.CrmSupplyMaterialDeliverOrderMsg;
import com.sifang.modules.supply.order.request.InStockReq;
import com.sifang.modules.supply.order.service.DeliverOrderService;
import com.sifang.modules.supply.order.service.InStockOrderService;
import com.sifang.modules.supply.order.service.MaterialApplyService;
import com.sifang.modules.supply.setting.service.CrmSupplyDeliveryMethodService;
import com.sifang.modules.supply.setting.service.CrmSupplyWarehouseSettingService;
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.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.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * 入库单管理
 */
@Controller
@RequestMapping("${adminPath}/material/order")
public class InStockOrderController extends BaseExceptionController {

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

    @Autowired
    MaterialApplyService applyService;

    @Autowired
    CrmSupplyDeliveryMethodService deliveryMethodService;

    @Autowired
    DeliverOrderService deliverOrderService;

    @Autowired
    InStockOrderService inStockOrderService;

    @Autowired
    CrmSupplyWarehouseSettingService warehouseSettingService;

    /**
     * 供应链端的收货单管理
     */
    @RequestMapping("/inStockOrderList")
    public String deliverOrderList(Model model) {
        List<Record> methods = deliveryMethodService.listDeliverMethods();
        model.addAttribute("deliverMethods", methods);
        //供应链入库
        Ascription ascription = CrmUtils.getAscription();
        model.addAttribute("inAscriptionId", ascription.getAscriptionId());
        //仓库列表
        List<Record> warehouses = warehouseSettingService.findWarehouseByAscriptionId(ascription.getAscriptionId());
        model.addAttribute("warehouses", warehouses);
        return "modules/supply/order/inStockOrderList";
    }

    /**
     * 仓库打回
     */
    @ResponseBody
    @RequestMapping("/giveBack")
    public Result giveBack(String id, String reason){
        GuardUtils.notBlank(reason, "打回原因不能为空");
        inStockOrderService.giveBack(id, reason, Operator.of(UserUtils.getUser()));
        return Result.ok();
    }

    /**
     * 签收页面
     */
    @RequestMapping("/toInStock")
    public String toInStock(String id, Model model,String status){
        Record order = deliverOrderService.findOrderById(id);
        if("11".equals(order.get("status")) && !"2".equals(status)){
            status="1";
        }
        List<Record> details = deliverOrderService.findDetailsByOrderId(id);
        String img=details.get(0).get("receive_invoice");
        if(StringUtils.isNotBlank(img)){
            img=img.substring(00,img.length()-1);

        }
        //供应链入库或代理商入库
        Ascription ascription = CrmUtils.getAscription();
        model.addAttribute("inAscriptionId", ascription.getAscriptionId());
        // 发货方式
        model.addAttribute("methodType",deliveryMethodService.getTypeDetai(order.getStr("deliver_method_id")).getType());
        model.addAttribute("id", id);
        model.addAttribute("order", order);
        model.addAttribute("status", status);
        model.addAttribute("details", details);
        model.addAttribute("img",img);

        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);
        User user=UserUtils.getUser();
        model.addAttribute("user",user);
       return "modules/supply/order/inStock";
    }
    /**
     * 导入条码
    */
    @RequestMapping(value = "toBarcode")
    public String toBarcode( Model model,String id ,String amount) {
        model.addAttribute("id",id);
        model.addAttribute("amount",amount);
        return "modules/supply/barcode/toBarcode";
    }




    /**
     * 待签收详情页面
     */
    @RequestMapping("/waitReciveDetail")
    public String waitReciveDetail(String id, Model model){
        Record order = deliverOrderService.findOrderById(id);
        List<Record> details = deliverOrderService.findDetailsByOrderId(id);
        //供应链入库或代理商入库
        Ascription ascription = CrmUtils.getAscription();
        model.addAttribute("inAscriptionId", ascription.getAscriptionId());
        //过程记录
        List<CrmSupplyMaterialDeliverOrderMsg> msgList = deliverOrderService.listMsgByOrderId(id);
        model.addAttribute("msgList", msgList);
        // 发货方式
        model.addAttribute("methodType",deliveryMethodService.getTypeDetai(order.getStr("deliver_method_id")).getType());
        model.addAttribute("id", id);
        model.addAttribute("order", order);
        model.addAttribute("details", details);
        if (StringUtils.isNotBlank(order.getStr("receive_invoice"))) {
            String[] imgArr = order.getStr("receive_invoice").split(",");
            List<String> imglist = new ArrayList<>();
            for (String img:imgArr) {
                imglist.add(img);
            }
            model.addAttribute("imglist", imglist);
        }
        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("user", UserUtils.getUser());
       return "modules/supply/order/waitReciveDetail";
    }

    /**
     * 入库
     */
    @ResponseBody
    @RequestMapping("/inStock")
    public Result inStock(@Valid @RequestBody InStockReq req){
        try {
            logger.info("into allocation, req={}", JSONObject.toJSONString(req));
            inStockOrderService.inStock(req, Operator.of(UserUtils.getUser()));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
        return Result.ok();
    }

    /**
     * 代理商确认
     */
    @ResponseBody
    @RequestMapping("/agentOk ")
    public Result agentOk(@Valid @RequestBody InStockReq req){

        if(StringUtil.isBlank(req.getOrderId())){
            return Result.fail("203","参数为空");
        }
        try {
            logger.info("into allocation, req={}", JSONObject.toJSONString(req));
            inStockOrderService.agentOk(req, Operator.of(UserUtils.getUser()));
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
        return Result.ok();
    }

    /**
     * 代理商确认
     */
    @ResponseBody
    @RequestMapping("/agentFalse")
    public Result agentFalse(@Valid @RequestBody InStockReq req){

        if(StringUtil.isBlank(req.getOrderId())){
            return Result.fail("203","参数为空");
        }
        try {
            logger.info("into allocation, req={}", JSONObject.toJSONString(req));

            inStockOrderService.agentFalse(req, Operator.of(UserUtils.getUser()));
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
        return Result.ok();
    }




    /**
     * 入库单详情
     */
    @RequestMapping("inStockOrderDetail")
    public String inStockOrderDetail(String id, Model model) {
        Record order = deliverOrderService.findOrderById(id);
        model.addAttribute("order", order);
        List<Record> details = deliverOrderService.findDetailsByOrderId(id);
        model.addAttribute("details", details);
        //过程记录
        List<CrmSupplyMaterialDeliverOrderMsg> msgList = deliverOrderService.listMsgByOrderId(id);
        model.addAttribute("msgList", msgList);
        return "modules/supply/order/inStockOrderDetail";
    }

    /**
     * 入库单详情
     * type 1.申请单 2.发货单
     */
    @RequestMapping("mergeOrderDetail")
    public String mergeOrderDetail(String id, String type, Model model) {
        String applyOrderId;
        if("1".equals(type)){
            applyOrderId = id;
        }else {
            Record order = deliverOrderService.findOrderById(id);
            model.addAttribute("deliverOrder", order);
            applyOrderId = order.getStr("apply_order_id");
            //过程记录
            List<CrmSupplyMaterialDeliverOrderMsg> msgList = deliverOrderService.listMsgByOrderId(id);
            model.addAttribute("deliverMsgList", msgList);
            List<Record> details = deliverOrderService.findDetailsByOrderId(id);
            model.addAttribute("deliverOrderDetails", details);
        }
        Record applyOrder = applyService.getRecordById(applyOrderId, Operator.of(UserUtils.getUser()));
        model.addAttribute("applyOrder", applyOrder);
        List<Record> gatherDetails = applyService.listGatherByApplyId(applyOrderId);
        model.addAttribute("gatherDetails", gatherDetails);
        List<Record> applyDetails = applyService.listDetailsByApplyId(applyOrderId);
        model.addAttribute("applyDetails", applyDetails);
        List<CrmSupplyMaterialApplyMsg> msgList = applyService.listMsgByApplyId(applyOrderId);
        model.addAttribute("applyOrderMsgList", msgList);
        model.addAttribute("user", UserUtils.getUser());
        return "modules/supply/order/mergeOrderDetail";
    }
}
