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

import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.Service.CustomerEntryService;
import com.sifang.modules.customer.pdf.OrderPdf;
import com.sifang.modules.flowable.service.ProcessFlowableService;
import com.sifang.modules.flowable.utils.FormUtils;
import com.sifang.modules.flowpath.entity.ExamineInfo;
import com.sifang.modules.flowpath.service.ExamineInfoService;
import com.sifang.modules.flowpath.vo.UserApplyVo;
import com.sifang.modules.q7link.utils.Q7DataUtil;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmTrader;
import com.sifang.modules.sunshine.SystemSetting.service.TraderService;
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.dao.MaterialDeliverDao;
import com.sifang.modules.supply.order.entity.CrmSupplyMaterialDeliverOrder;
import com.sifang.modules.supply.order.request.OrderApproveReq;
import com.sifang.modules.supply.order.request.UpdateSupplyOrderDetailReq;
import com.sifang.modules.supply.order.service.CrmSupplyMaterialDeliverOrderService;
import com.sifang.modules.supply.order.service.DeliverOrderService;
import com.sifang.modules.supply.order.service.MaterialApplyService;
import com.sifang.modules.supply.order.service.SupplyOrderAuditService;
import com.sifang.modules.supply.stock.dao.SupplyMaterialDao;
import com.sifang.modules.supply.stock.entity.SupplyMaterial;
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.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.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;


//待审批订单
@Controller
@RequestMapping(value = "${adminPath}/material/order")
public class SupplyDeliverMaterialAuditController extends BaseExceptionController {

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

    @Autowired
    SupplyOrderAuditService supplyOrderService;

    @Autowired
    ExamineInfoService examineInfoService;

    @Autowired
    DeliverOrderService deliverOrderService;

    @Autowired
    private ProcessFlowableService flowableService;

    @Autowired
    CustomerEntryService customerService;

    @Autowired
    private TraderService traderService;

    @Resource
    private CrmSupplyMaterialDeliverOrderService crmSupplyMaterialDeliverOrderService;
    @Autowired
    private MaterialApplyService materialApplyService;
    @Autowired
    private MaterialDeliverDao materialDeliverDao;

    @Autowired
    private SupplyMaterialDao supplyMaterialDao;

    /**
     * 现金下单 列表
     */
    @RequestMapping("/findZjApplyOrder")
    public String findZjApplyOrder(Model model){
       /* //判断平台员工角色 5.业务人员 6.运管部 7.物资专员 2.项目工程师（工程部）
        User user = UserUtils.getUser();
        String userType = user.getUserType();
        if (UserConstants.TYPE_PLAT_EMP.equals(userType)) {
            model.addAttribute("roleType", traderOrderService.findRoleType(user.getId()));
        }
        model.addAttribute("userType", userType);*/
        User user = UserUtils.getUser();
        model.addAttribute("userId",user.getId());
        model.addAttribute("userType",user.getUserType());
        //代理商列表
        List<Record> traderList = traderService.getAllTopTrader();
        model.addAttribute("traderList", traderList);
        List<Record> qqProjectList= Q7DataUtil.getAllQQProjectCode();
        model.addAttribute("qqProjectList",qqProjectList);
        return "modules/supply/order/ZjApplyOrderList";
    }


    /**
     * 订单管理--列表数据_h
     */
    @ResponseBody
    @RequestMapping("/auditOderList")
    public Object auditOderList(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        LayuiPage<Record> page = new LayuiPage<>(request);

        User user = UserUtils.getUser();
        if (User.USER_TYPE_KJ.equals(user.getUserType()) || User.USER_TYPE_ADVISOR.equals(user.getUserType())) {  //代理商
            String traderId = CrmUtils.getUserRelId(user);
            map.put("traderId",traderId);
        }/*else{
            if(StringUtil.isBlank(map.get("status"))){
                map.put("status","1,2,3,9");
            }
        }*/
        supplyOrderService.listPageDate(page,map,FormUtils.SUPPLY_ORDER_APPLICATION);
        return page.renderJson();
    }

    /**
     * 订单管理--列表数据_h
     */
    @ResponseBody
    @RequestMapping("/ZjauditOderList")
    public Object ZjauditOderList(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        LayuiPage<Record> page = new LayuiPage<>(request);
    /*    if(StringUtil.isBlank(map.get("status"))){
            map.put("status","1,2,9,a,3,10");
        }*/
        User user = UserUtils.getUser();
        String traderId="";
        if (User.USER_TYPE_KJ.equals(user.getUserType()) || User.USER_TYPE_ADVISOR.equals(user.getUserType())) {  //代理商
            traderId = CrmUtils.getUserRelId(user);
            map.put("traderId",traderId);
        }
        supplyOrderService.listPageDate(page,map,FormUtils.BRACKET_ORDER_APPLY);
        return page.renderJson();
    }

    // 详情 页面
    @RequestMapping(value = "/auditOderDetailPage")
    public String auditOderDetailPage(HttpServletRequest request, Model model){
        Ascription ascription = CrmUtils.getAscription();
        //CrmTrader trader = traderService.getById(ascription.getAscriptionId());
        String id=request.getParameter("id");
        // 订单详情
        Record order=supplyOrderService.orderDetail(id);
        model.addAttribute("order",order);
        //物料信息
        List<Record> mates=supplyOrderService.getOrderMaterials(id);
        model.addAttribute("details",mates);
        String formKey = FormUtils.SUPPLY_ORDER_APPLICATION;
        if("5".equals(order.getStr("type"))){
            formKey = FormUtils.BRACKET_ORDER_APPLY;
        }

        List<ExamineInfo> infos=examineInfoService.getByApplyId(id, formKey);
        model.addAttribute("infos",infos);
        User user = UserUtils.getUser();
        model.addAttribute("userType",user.getUserType());
        flowableService.readApplication(order.getStr("process_instance_id"),formKey,id,user);
        if("1".equals(order.getStr("type"))){
            String entryid= order.getStr("apply_order_id");
            List<Record> listens = customerService.getEntryListByEntryIds("",entryid);
            model.addAttribute("entrys",listens);

        }
        List<Record> qqProjectList= Q7DataUtil.getAllQQProjectCode();
        model.addAttribute("qqProjectList",qqProjectList);
        return "modules/supply/order/supplyMaterialOrderDetail";
    }

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

        User user = UserUtils.getUser();
        List<Record> mates=supplyOrderService.getOrderMaterials(id);
        model.addAttribute("details",mates);
        BigDecimal total=BigDecimal.ZERO;
        if("purchase".equals(from)){
            for(Record r:mates){
                total.add(r.getBigDecimal("apply_amount").multiply(r.getBigDecimal("purchase_price")));
            }
        }
        model.addAttribute("order", order);
        model.addAttribute("user",user);
        model.addAttribute("from","from");
        model.addAttribute("total",total);
        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";
    }


    //审批页面
    @RequestMapping(value = "/supplyMaterialOrderAudit")
    public String supplyMaterialOrderAudit(HttpServletRequest request, Model model){
        String formKey = request.getParameter("formKey");
        String id=request.getParameter("id");
        // 订单详情
        Record order=supplyOrderService.orderDetail(id);
        model.addAttribute("order",order);
        //物料信息
        List<Record> mates=supplyOrderService.getOrderMaterials(id);
        model.addAttribute("details",mates);
        String from=request.getParameter("from"); //from=audit 那么就是审核  否则编辑
        if(StringUtil.isBlank(from)){
            from="";
        }
        model.addAttribute("from",from);
        //判断目前是几级审批
        Integer sort=FormUtils.getSortByDefIdName(order.getStr("process_def_id"),order.getStr("task_name"));
        if(sort==null){
            sort=0;
        }
        //判断是否是最后一级审批
        Integer maxSort = FormUtils.getMaxSortByProDefId(order.getStr("process_def_id"));
        if (maxSort == sort ){
            model.addAttribute("processSort",2);
        }else {
            model.addAttribute("processSort",1);
        }

        List<Record> qqProjectList= Q7DataUtil.getAllQQProjectCode();
        model.addAttribute("qqProjectList",qqProjectList);
        if(FormUtils.BRACKET_ORDER_APPLY.equals(formKey)){
            return "modules/supply/order/zj/supplyZjOrderAudit";
        }else{
            if("1".equals(order.getStr("type"))){
                String entryid= order.getStr("apply_order_id");
                List<Record> listens = customerService.getEntryListByEntryIds("",entryid);
                model.addAttribute("entrys",listens);
            }
            return "modules/supply/order/supplyMaterialOrderAudit";
        }
    }

    //匹配页面  from=bh 那么是备货申请里面的匹配  from=xd 那么是待审批订单里面的匹配
    @RequestMapping(value = "mateMaterialPage")
    public String mateMaterialPage(String type,String spec,String amount,String traderId,Model model,String id,String from, String qqProjectCode){
        if("bh".equals(from)){
            List<Record> stocks=supplyOrderService.getBySpecVsType(type,spec);
            model.addAttribute("platStock",stocks);
        }else {
            //平台库存信息
            List<Record> platStock=supplyOrderService.getPlateMaterialsStock2(type,spec,traderId,id,qqProjectCode);
            model.addAttribute("platStock",platStock);
            //代理商库存信息
            List<Record> tradeStock=supplyOrderService.getPlateMaterialsStock(type,spec,"3",traderId,qqProjectCode);
            model.addAttribute("tradeStock",tradeStock);
        }
        model.addAttribute("amount",amount);
        model.addAttribute("from",from);
        return "modules/supply/order/mateMaterialPage";
    }

    //审批通过
    @ResponseBody
    @RequestMapping(value = "supplyOrderApprove")
    public Result supplyOrderApprove(@Validated @RequestBody OrderApproveReq approveReq){
        try{
            supplyOrderService.supplyOrderApprove(approveReq);
            return Result.ok();
        }catch (RuntimeException c){
            logger.info(">>>>>>>>>>>>>>supplyOrderApprove c:{}",c);
            return Result.fail(c.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            logger.error(">>>>>>>>>>>>>>supplyOrderApprove e:{}",e);
            return Result.fail("审核失败！");
        }
    }


    //审核驳回
    @ResponseBody
    @RequestMapping(value = "backSupplyOrder")
    public Result backSupplyOrder(@Valid UserApplyVo userApplyVo){
        try{
            supplyOrderService.backSupplyOrder(userApplyVo);
            return Result.ok();
        }catch (Exception e){
            logger.error(">>>>>>>>>>>>>>backSupplyOrder e:{}",e);
            return Result.fail("审核失败！");
        }
    }


    @RequestMapping("/supplyOrderEdit")
    public String supplyOrderEdit(HttpServletRequest request,Model model) {
        String orderId=request.getParameter("orderId");
        // 订单详情
        Record order=supplyOrderService.orderDetail(orderId);
        model.addAttribute("rd",order);
        int insuranceFilesCount = 0;
        if(StringUtil.isNotBlank(order.getStr("insurance_files"))){
            String[] arr=order.getStr("insurance_files").split(",");
            insuranceFilesCount = arr.length;
        }
        model.addAttribute("insuranceFilesCount",insuranceFilesCount);
        int safetyFilesCount = 0;
        if(StringUtil.isNotBlank(order.getStr("safety_files"))){
            String[] arr=order.getStr("safety_files").split(",");
            safetyFilesCount = arr.length;
        }
        model.addAttribute("safetyFilesCount",safetyFilesCount);
        int filesCount = 0;
        if(StringUtil.isNotBlank(order.getStr("file_url"))){
            String[] arr=order.getStr("file_url").split(",");
            filesCount = arr.length;
        }
        model.addAttribute("filesCount",filesCount);
        //物料信息  标准物料
        List<Record> mates1=supplyOrderService.getOrderDetail(orderId,"0");
        model.addAttribute("details",mates1);
        BigDecimal totalPrice = BigDecimal.ZERO;
        for (Record detail : mates1) {
            BigDecimal applyAmount = detail.getBigDecimal("apply_amount");
            BigDecimal salesPrice = detail.getBigDecimal("sales_price");
            totalPrice = totalPrice.add(applyAmount.multiply(salesPrice));
        }
        model.addAttribute("totalPrice",totalPrice.stripTrailingZeros().toPlainString());
        //物料信息  非标准物料
  /*      List<Record> mates2=supplyOrderService.getOrderDetail(orderId,"1");
        model.addAttribute("details2",mates2);*/
        User user = UserUtils.getUser();
        Ascription ascription = CrmUtils.getAscription();
        CrmTrader trader = traderService.getById(ascription.getAscriptionId());
        Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
        List<Record> list = MaterialUtils.findMaterialWarehouseByAscriptionId(ascription.getAscriptionId());
        model.addAttribute("wares", list);
        model.addAttribute("userId", user.getId());
        //自选产品物料类型
        List<Record> typeList = MaterialUtils.findMaterialTypeForSXXD("0");
        model.addAttribute("typeList",typeList);
        model.addAttribute("orderId",orderId);
        if("1".equals(order.getStr("type"))){
            String entryid= order.getStr("apply_order_id");
            List<Record> listens = customerService.getEntryListByEntryIds("",entryid);
            model.addAttribute("entrys",listens);

        }
        List<Record> qqProjectList= Q7DataUtil.getQQProjectByCode(trader.getQqProjectCode());
        model.addAttribute("qqProjectList",qqProjectList);
        return "modules/supply/order/supplyOrderEdit";
    }



    @ResponseBody
    @RequestMapping(value = "deleteAuditOrder")
    public Result deleteAuditOrder(HttpServletRequest request){
        String orderId=request.getParameter("orderId");
        String formKey = request.getParameter("formKey");
        supplyOrderService.deleteOrder(orderId,formKey);
        return Result.ok();
    }

    //导出pdf文件
    @RequestMapping(value = "exportOrderPdfDocument")
    public void exportOrderPdfDocument(String id, HttpServletResponse response){
        GuardUtils.notBlank(id, "id不能为空");
        logger.info(">...exportOrderPdfDocument id:{}",id);
        long s1 = System.currentTimeMillis();
        Record order = deliverOrderService.findOrderById(id);
        List<Record> details = deliverOrderService.findDetails(id);
        for (Record detail : details) {
            String materialId = detail.getStr("material_id");
            SupplyMaterial supplyMaterial = supplyMaterialDao.get(materialId);
            detail.set("qq_code",supplyMaterial.getQqCode());
        }
//        List<ExamineInfo> infos=examineInfoService.getByApplyId(id, FormUtils.SUPPLY_ORDER_APPLICATION);
        OutputStream outputStream = null;
        try {
            String name = "物资需求单_"+order.getStr("number")+".pdf";
            // 防止中文乱码
            String fileName  = URLEncoder.encode(name, "UTF-8");
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            response.setContentType("application/octet-stream;charset=UTF-8");
            outputStream = new BufferedOutputStream(response.getOutputStream());
            OrderPdf.createOrderPdf(outputStream,order,details);
            outputStream.flush();
            long s2 = System.currentTimeMillis();
            logger.info(" >>导出订单pdf文件 时间统计  end exportOrderPdfDocument use {}ms ",  (s2 - s1));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            logger.error("UnsupportedEncodingException --------------:{}",e);
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("IOException ---->>>>>>>>>>----------:{}",e);
        }finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @ResponseBody
    @RequestMapping("/findPurchasePrice")
    public Object findPurchasePrice(String materialId){
        Record record = materialDeliverDao.findPurchasePrice(materialId);
        if (record!=null){
            return record.getBigDecimal("purchasePrice");
        }else {
            return  "0";
        }

    }


    //匹配后直接保存匹配物料信息
    @ResponseBody
    @RequestMapping(value = "updateSupplyOrderDetail")
    public Result updateSupplyOrderDetail(@Validated @RequestBody UpdateSupplyOrderDetailReq req){
        return supplyOrderService.updateSupplyOrderDetail(req);
    }
}
