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


import com.google.common.collect.Maps;
import com.jfinal.plugin.activerecord.Record;
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.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.entity.CrmSupplyMaterialDeliverOrderMsg;
import com.sifang.modules.supply.order.service.DeliverOrderService;
import com.sifang.modules.supply.setting.service.CrmSupplyWarehouseSettingService;
import com.sifang.modules.supply.warehouse.service.SupplyPurchaseOrderAuditService;
import com.sifang.modules.supply.warehouse.vo.AddPurchaseOrderVo;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.web.BaseExceptionController;
import net.sf.json.JSONObject;
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 org.springframework.web.multipart.MultipartFile;

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

@Controller
@RequestMapping(value = "${adminPath}/supplyOrder/purchaseAudit")
public class SupplyPurchaseOrderAuditController extends BaseExceptionController {

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

    @Autowired
    TraderService traderService;

    @Autowired
    CrmSupplyWarehouseSettingService warehouseSettingService;

    @Autowired
    private SupplyPurchaseOrderAuditService auditService;

    @Autowired
    private DeliverOrderService  deliverOrderService;

    @Autowired
    private ExamineInfoService examineInfoService;

    @Autowired
    private ProcessFlowableService flowableService;

    //采购审批页面
    @RequestMapping(value = "purchaseAuditPage")
    public String purchaseAuditPage(Model model) {
        //供应商列表
        List<Record> supplyList = warehouseSettingService.getSupplyList();
        model.addAttribute("supplyList", supplyList);
        //代理商列表
        List<Record> traderList = traderService.getAllTrader();
        model.addAttribute("traderList", traderList);
        model.addAttribute("formId", FormUtils.PURCHASE_ORDER_APPLICATION);
        User user = UserUtils.getUser();
        model.addAttribute("userId",user.getId());
        return "modules/supply/warehouse/purchaseAuditListPage";
    }

    //列表数据
    @ResponseBody
    @RequestMapping(value = "purchaseAuditList")
    public Object purchaseAuditList(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        LayuiPage<Record> page = new LayuiPage<>(request);
        auditService.purchaseOrderAuditDate(page, map);
        return page.renderJson();
    }

     /**
     *  新增采购单
      *  2023-08-09调整
      *  采购部分调整的服务类采购流程。
      * 1、首先要对物料进行调整，对物料进行外购与服务类型的区分。物料接口中使用 FErpClsID字段区别：外购（1），服务（6）；
      * 2、物料创建完成之后，新增采购单的时候只能选外购的物料 ；
     */
    @RequestMapping(value = "addPurchasePage")
    public String addPurchasePage(Model model) {
        //供应商列表
        List<Record> supplyList = warehouseSettingService.getSupplyList();
        model.addAttribute("supplyList", supplyList);
        model.addAttribute("from","add");
        model.addAttribute("total",0);
        //平台所属仓库
        List<Record> warehouseList=warehouseSettingService.findWarehouseByAscriptionId("a");
        model.addAttribute("warehouseList",warehouseList);
        return "modules/supply/warehouse/addPurchaseOrder";
    }

    //编辑采购单
    @RequestMapping(value = "editPurchasePage")
    public String editPurchasePage(HttpServletRequest request,Model model) {
        String id=request.getParameter("id");
        // 订单详情
        Record record= auditService.purchaseOrderDetail(id);
        model.addAttribute("order",record);
        //物料信息
        List<Record> mates=auditService.getOrderMaterials(id);
        BigDecimal total=BigDecimal.ZERO;
        for(Record r:mates){
            total.add(r.getBigDecimal("apply_amount").multiply(r.getBigDecimal("purchase_price")));
        }
        model.addAttribute("details",mates);
        model.addAttribute("total",total);
        //供应商列表
        List<Record> supplyList = warehouseSettingService.getSupplyList();
        model.addAttribute("supplyList", supplyList);
        //平台所属仓库
        List<Record> warehouseList=warehouseSettingService.findWarehouseByAscriptionId("a");
        model.addAttribute("warehouseList",warehouseList);
        model.addAttribute("from","edit");
        return "modules/supply/warehouse/addPurchaseOrder";
    }

    /**
     * 导入物料页面
     */
    @RequestMapping(value = "toImportMaterialForm")
    public String toImportMaterialForm(Model model, HttpServletRequest request) {
        String warehouseId = request.getParameter("warehouseId");
        model.addAttribute("warehouseId", warehouseId);
        return "modules/supply/warehouse/importPurchaseOrderMaterial";
    }

    /**
     * 校验 excel
     */
    @ResponseBody
    @RequestMapping(value = "checkImportPurchaseOrderMaterial")
    public Object checkImportExcel(MultipartFile file) throws IOException {
        Map<String, String> params = Maps.newHashMap();
        params.put("extName", StringUtil.getFileExtName(file.getOriginalFilename()));
        Map<String, Object> retMap = auditService.checkImportExcel(params, file.getInputStream());
        return JSONObject.fromObject(retMap);
    }

    /**
     * 导入 excel数据
     */
    @ResponseBody
    @RequestMapping(value = "importPurchaseOrderMaterialData")
    public JSONObject importInventoryData(MultipartFile file) throws IOException {
        Map<String, String> params = Maps.newHashMap();
        params.put("fileName", file.getOriginalFilename());
        Map<String, Object> retMap = auditService.importInventoryData(params, file.getInputStream());
        return JSONObject.fromObject(retMap);
    }

    // 保存新增/编辑 采购单
    @ResponseBody
    @RequestMapping(value = "savePurchaseOrder")
    public Result savePurchaseOrder(@Validated @RequestBody AddPurchaseOrderVo orderVo){
        auditService.savePurchaseOrder(orderVo);
        return Result.ok();
    }

    //审批页面
    @RequestMapping(value = "auditPurchaseOrderPage")
    public String auditPurchaseOrderPage(HttpServletRequest request,Model model){
        String id=request.getParameter("id");
        // 订单详情
        Record record= auditService.purchaseOrderDetail(id);
        model.addAttribute("order",record);
        //物料信息
        List<Record> mates=auditService.getOrderMaterials(id);
        model.addAttribute("details",mates);

        List<ExamineInfo> infos=examineInfoService.getByApplyId(id,FormUtils.PURCHASE_ORDER_APPLICATION);
        model.addAttribute("infos",infos);
        BigDecimal total=BigDecimal.ZERO;
        for(Record r:mates){
          total= total.add(r.getBigDecimal("out_amount").multiply(r.getBigDecimal("purchase_price")));
        }
        model.addAttribute("total",total.setScale(2, RoundingMode.HALF_UP));
        //过程信息
        List<CrmSupplyMaterialDeliverOrderMsg> msg= deliverOrderService.listMsgByOrderId(id);
        model.addAttribute("msg",msg);
        String from=request.getParameter("from"); //from=audit 那么就是审核  否则详情
        model.addAttribute("from",from);
        User user = UserUtils.getUser();
        if(!"audit".equals(from)){
            flowableService.readApplication(record.getStr("purchase_process_instance_id"),FormUtils.PURCHASE_ORDER_APPLICATION,id,user);
        }
        return "modules/supply/warehouse/auditPurchaseOrderPage";
    }


    //审核通过
    @ResponseBody
    @RequestMapping(value = "examinePurchaseOrderApprove")
    public Result examinePurchaseOrderApprove(UserApplyVo userApplyVo){
        try{
            auditService.examinePurchaseOrderApprove(userApplyVo);
            return Result.ok();
        }catch (RuntimeException c){
            logger.info(">>>>>>>>>>>>>>examinePurchaseOrderApprove c:{}",c);
            return Result.fail(c.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            logger.error(">>>>>>>>>>>>>>examinePurchaseOrderApprove e:{}",e);
            return Result.fail("审核失败！");
        }
    }

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

    //审核撤销
    @ResponseBody
    @RequestMapping(value = "deletePurchaseOrder")
    public Result deletePurchaseOrder(String id){
        try{
            auditService.deletePurchaseOrder(id);
            return Result.ok();
        }catch (RuntimeException r){
            r.printStackTrace();
            return Result.fail(r.getMessage());
        }catch (Exception e){
            logger.error(">>>>>>>>>>>>>>deletePurchaseOrder e:{}",e);
            e.printStackTrace();
            return Result.fail("删除失败！");
        }
    }

}
