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

import com.google.common.collect.Maps;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.Service.CustomerEntryComponentService;
import com.sifang.modules.customer.Service.CustomerEntryService;
import com.sifang.modules.platform.service.AddressService;
import com.sifang.modules.q7link.service.CrmSupplyMaterialProjectPriceService;
import com.sifang.modules.q7link.utils.Q7DataUtil;
import com.sifang.modules.setting.service.MemberService;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmTrader;
import com.sifang.modules.sunshine.SystemSetting.service.TraderEmployeService;
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.CrmSupplyMaterialApplyMsg;
import com.sifang.modules.supply.order.request.ApplyOrderReq;
import com.sifang.modules.supply.order.service.MaterialApplyService;
import com.sifang.modules.supply.setting.entity.CrmSupplyWarehouse;
import com.sifang.modules.supply.setting.service.CrmSupplyWarehouseSettingService;
import com.sifang.modules.supply.stock.entity.SupplyMaterial;
import com.sifang.modules.supply.stock.utils.MaterialUtils;
import com.sifang.modules.supply.warehouse.service.InventoryOrderService;
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.LayuiPage;
import com.sifang.modules.sys.web.BaseExceptionController;
import net.sf.json.JSONObject;
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 org.springframework.web.multipart.MultipartFile;

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

/**
 * @author hongzq
 */
@Controller
@RequestMapping("${adminPath}/material/apply")
public class MaterialApplyOrderController extends BaseExceptionController {

    @Autowired
    MaterialApplyService materialApplyService;

    @Autowired
    MemberService memberService;
    @Autowired
    CrmSupplyWarehouseSettingService warehouseSettingService;

    @Autowired
    AddressService addressService;

    @Autowired
    CustomerEntryService customerService;

    @Autowired
    private InventoryOrderService inventoryOrderService;

    @Autowired
    private CustomerEntryComponentService customerEntryComponentService;

    @Autowired
    private TraderService traderService;

    @Autowired
    private CrmSupplyMaterialProjectPriceService projectPriceService;

    @Autowired
    private TraderEmployeService traderEmployeService;

    /**
     * 代理商端，物料申请单下单
     */
    @RequestMapping("/create")
    public String create(Model model) {
        User user = UserUtils.getUser();
        Ascription ascription = CrmUtils.getAscription();
        CrmTrader trader = traderService.getById(ascription.getAscriptionId());
        List<Record> list = MaterialUtils.findMaterialWarehouseByAscriptionId(ascription.getAscriptionId());
        //获取所有省份
        List<Record> province = addressService.getProvinces();
        model.addAttribute("province", province);
        if(list.size()==1){
            Record rd = list.get(0);
            //获取当前省下的市
            //获取当前市下的区县
            String provin = rd.getStr("province");
            String city = rd.getStr("city");
            //根据省查询下面的
            List<Record> citys = addressService.getCityByProviceName(provin);
            List<Record> areas = addressService.getAreaByCityName(city);
            model.addAttribute("faccitys",citys);
            model.addAttribute("areas",areas);
            model.addAttribute("rd", list.get(0));
        }
        model.addAttribute("wares", list);
        model.addAttribute("userId", user.getId());
        //自选产品物料类型
        List<Record> typeList = MaterialUtils.findMaterialTypeForSXXD("0");
        model.addAttribute("typeList",typeList);
        List<Record> qqProjectList= Q7DataUtil.getQQProjectByCode(trader.getQqProjectCode());
        model.addAttribute("qqProjectList",qqProjectList);
        return "modules/supply/order/createApplyOrder";
    }


    /**
     * 代理商端，现金下单
     */
    @RequestMapping("/createZjOrder")
    public String createZjOrder(Model model) {
        User user = UserUtils.getUser();
        Ascription ascription = CrmUtils.getAscription();
        CrmTrader trader = traderService.getById(ascription.getAscriptionId());
        List<Record> list = MaterialUtils.findMaterialWarehouseByAscriptionId(ascription.getAscriptionId());
        //获取所有省份
        List<Record> province = addressService.getProvinces();
        model.addAttribute("province", province);
        if(list.size()==1){
            Record rd = list.get(0);
            //获取当前省下的市
            //获取当前市下的区县
            String provin = rd.getStr("province");
            String city = rd.getStr("city");
            //根据省查询下面的
            List<Record> citys = addressService.getCityByProviceName(provin);
            List<Record> areas = addressService.getAreaByCityName(city);
            model.addAttribute("faccitys",citys);
            model.addAttribute("areas",areas);
            model.addAttribute("rd", list.get(0));
        }
        model.addAttribute("wares", list);
        model.addAttribute("userId", user.getId());
        //获取所有支架物料
        Map<String,String> params =Maps.newHashMap();
        params.put("materialTypeId","4");
        List<Record> recordList = materialApplyService.findCanApplyMaterialsByKeyWord(params, null);
        model.addAttribute("recordList", recordList);
        List<Record> qqProjectList= Q7DataUtil.getQQProjectByCode(trader.getQqProjectCode());
        model.addAttribute("qqProjectList",qqProjectList);
        return "modules/supply/order/createZjApplyOrder";
    }
    @RequestMapping("/supplyOrderZjEdit")
    public String supplyOrderZjEdit(HttpServletRequest request,Model model) {
        User user = UserUtils.getUser();
        Ascription ascription = CrmUtils.getAscription();
        CrmTrader trader = traderService.getById(ascription.getAscriptionId());
        String orderId=request.getParameter("orderId");
        // 订单详情
        Record order=materialApplyService.orderDetail(orderId);
        model.addAttribute("order",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=materialApplyService.getOrderDetail(orderId,"0");
        model.addAttribute("details",mates1);
        model.addAttribute("detailSize",mates1.size()+1);
        List<Record> list = MaterialUtils.findMaterialWarehouseByAscriptionId(ascription.getAscriptionId());
        //获取所有省份
        List<Record> province = addressService.getProvinces();
        model.addAttribute("province", province);
            //获取当前省下的市
            //获取当前市下的区县
            String provin = order.getStr("province");
            String city = order.getStr("city");
            //根据省查询下面的
            List<Record> citys = addressService.getCityByProviceName(provin);
            List<Record> areas = addressService.getAreaByCityName(city);
            model.addAttribute("faccitys",citys);
            model.addAttribute("areas",areas);
            CrmSupplyWarehouse warehouse = warehouseSettingService.getWarehouseDetail(order.getStr("in_warehouse_id"));
        model.addAttribute("warehouse", warehouse);
        model.addAttribute("wares", list);
        model.addAttribute("userId", user.getId());
        //获取所有支架物料
        Map<String,String> params =Maps.newHashMap();
        params.put("materialTypeId","4");
        List<Record> recordList = materialApplyService.findCanApplyMaterialsByKeyWord(params, null);
        model.addAttribute("recordList", recordList);
        List<Record> qqProjectList= Q7DataUtil.getQQProjectByCode(trader.getQqProjectCode());
        model.addAttribute("qqProjectList",qqProjectList);
        return "modules/supply/order/zj/supplyZjOrderEdit";
    }
    /**
     * 根据物料id 获取
     */
    @ResponseBody
    @RequestMapping("findMaterialByCode")
    public Object findMaterialByCode(String id, String qqProjectCode){
        if(StringUtil.isBlank(id)){
            return Result.fail("203","参数为空");
        }
        SupplyMaterial material = materialApplyService.fingMaterialById(id);
        String qqMaterialCode = material.getQqCode();
        Record record = projectPriceService.findPriceByCodes(qqProjectCode, qqMaterialCode);
        if (record == null){
            material.setCustomerPrice("0");
        }else {
            material.setCustomerPrice(record.getBigDecimal("price").toPlainString());
        }
        return Result.success(material);
    }


    /**
     * 根据仓库id 获取
    */
    @ResponseBody
    @RequestMapping("findWarehouseById")
    public Object findWarehouseById(String id){
        if(StringUtil.isBlank(id)){
            return Result.fail("203","参数为空");
        }
        CrmSupplyWarehouse warehouse = warehouseSettingService.getWarehouseDetail(id);


        return Result.success(warehouse);
    }


    /**
     * 代理商端，物料申请单管理
     */
    @RequestMapping("/orderList")
    public String orderList(Model model) {
        Ascription ascription = CrmUtils.getAscription();
        model.addAttribute("traderId", ascription.getAscriptionId());
        model.addAttribute("wares", MaterialUtils.findMaterialWarehouseByAscriptionId(ascription.getAscriptionId()));
        return "modules/supply/order/applyOrderList";
    }

    /**
     * 新增或编辑物料申请单页面
     */
    @RequestMapping("/addApply")
    public String orderList(String id, Model model) {
        //获取所有省份
        List<Record> province = addressService.getProvinces();
        model.addAttribute("province", province);
        if (StrKit.notBlank(id)) {
            Record apply = materialApplyService.getRecordById(id, Operator.of(UserUtils.getUser()));
            model.addAttribute("apply", apply);
            List<Record> applyDetails = materialApplyService.listGatherByApplyId(id);
            model.addAttribute("applyDetails", applyDetails);

                //获取当前省下的市
                //获取当前市下的区县
                String provin = apply.getStr("province");
                String city = apply.getStr("city");
                //根据省查询下面的
                List<Record> citys = addressService.getCityByProviceName(provin);
                List<Record> areas = addressService.getAreaByCityName(city);
                model.addAttribute("faccitys",citys);
                model.addAttribute("areas",areas);
        }

        Ascription ascription = CrmUtils.getAscription();

        model.addAttribute("wares", MaterialUtils.findMaterialWarehouseByAscriptionId(ascription.getAscriptionId()));
        model.addAttribute("id", id);
        return "modules/supply/order/addApply";
    }

    /**
     * 模糊查询
     * 根据代码和描述查询可申请的一级BOM和物料
     */
    @ResponseBody
    @RequestMapping("/findCanApplyMaterials")
    public Object findCanApplyMaterials(String code, String desc, String materialTypeId){
        List<Record> materialList = materialApplyService.findCanApplyMaterials(code, desc, materialTypeId);
        return JsonKit.toJson(materialList);
    }

    @ResponseBody
    @RequestMapping("/findElectricMaterialDate")
    public Object findElectricMaterialDate(String type){
        return materialApplyService.findElectricMaterialDate(type);
    }

    @ResponseBody
    @RequestMapping("/findElectricMaterial2Date")
    public Object findElectricMaterial2Date(String typeId){
        return materialApplyService.findElectricMaterial2Date(typeId);
    }

    /**
     * 物料申请单列表数据
     */
    @ResponseBody
    @RequestMapping("/ajaxForApplyOrderList")
    public Object ajaxForApplyOrderList(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        LayuiPage<Record> page = new LayuiPage<>(request);
        materialApplyService.applyOrderListPage(page, map, Operator.of(UserUtils.getUser()));
        return page.renderJson();
    }

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

    /**
     * 匹配操作时，修改物料申请单物料信息
     */
    @ResponseBody
    @RequestMapping("/modifyApplyOrder")
    public Result modifyApplyOrder(@Valid @RequestBody ApplyOrderReq req){
        materialApplyService.modifyApplyOrder(req, Operator.of(UserUtils.getUser()));
        return Result.ok();
    }

    @ResponseBody
    @RequestMapping("/deleteApplyOrder")
    public Result deleteApplyOrder(String ids) {
        materialApplyService.deleteApplyOrder(ids, Operator.of(UserUtils.getUser()));
        return Result.ok();
    }

    /**
     * 查看物料申请单物料明细
     */
    @RequestMapping("/materialDetail")
    public String materialDetail(String applyId, Model model){
        Record apply = materialApplyService.getRecordById(applyId, Operator.of(UserUtils.getUser()));
        model.addAttribute("apply", apply);
        List<Record> gatherDetails = materialApplyService.listGatherByApplyId(applyId);
        model.addAttribute("gatherDetails", gatherDetails);
        List<Record> applyDetails = materialApplyService.listDetailsByApplyId(applyId);
        model.addAttribute("applyDetails", applyDetails);
        List<CrmSupplyMaterialApplyMsg> msgList = materialApplyService.listMsgByApplyId(applyId);
        model.addAttribute("msgList", msgList);
        return "modules/supply/order/applyMaterialDetail";
    }

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

    /**
     * 导入物料页面
     */
    @RequestMapping(value = "ImportMaterialForm")
    public String ImportMaterialForm(Model model, HttpServletRequest request) {

        return "modules/supply/order/importApplyMaterial";
    }

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

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

    /**
     * 获取类型规格下 物料的最高销售价
    */
    @ResponseBody
    @RequestMapping(value = "fingMaterialPrice")
    public Object fingMaterialPrice(String specs,String materialType, String qqProjectCode){
        BigDecimal price = materialApplyService.fingMaterialPrice(specs, materialType,qqProjectCode);
        if(price==null){
            price=BigDecimal.ZERO;
        }
        return price;
    }
    /**
     * 选择电站
    */
    @RequestMapping(value = "findCustomerEntryList")
    public String findCustomerEntryList(HttpServletRequest request,Model model){
        String entryIds = request.getParameter("entryIds");
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
        List<Record> list = customerService.findEntryLists(entryIds,operator,"");

        model.addAttribute("entryList",list);
        return "modules/supply/order/customerEntryPage";
    }

    /**
     * 获取选择后的电站物料
    */
    @ResponseBody
    @RequestMapping(value = "fingMaterialList")
    public Object fingMaterialList(String entryIds, String qqProjectCode, Model model) {
        // 查询汇总下单物料信息
        List<Record> list = new ArrayList<>();
        if (StringUtil.isNotBlank(entryIds)){
            String[] split = entryIds.split(",");
            list =customerEntryComponentService.findByEntryIds(Arrays.asList(split.clone()));
        }
        for(Record rd:list){
            BigDecimal price = materialApplyService.fingMaterialPrice(rd.getStr("model"), rd.getStr("type"),qqProjectCode);
            if(price==null){
                price=BigDecimal.ZERO;
            }
            rd.set("price",price);
        }
        return list;
    }


}
