package com.sifang.modules.changes.controller;

import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.changes.dao.CrmMaterialInformationChangeApplyDetailDao;
import com.sifang.modules.changes.entity.CrmMaterialInformationChangeApply;
import com.sifang.modules.changes.entity.CustomerEntrySurveyChangeRecord;
import com.sifang.modules.changes.service.CrmMaterialInformationChangeApplyService;
import com.sifang.modules.changes.vo.AnyProductMaterialChangeVo;
import com.sifang.modules.changes.vo.MaterialAuditVo;
import com.sifang.modules.changes.vo.MaterialInformationChangeVo;
import com.sifang.modules.changes.vo.SurveyAuditVo;
import com.sifang.modules.customer.Service.CustomerEntryService;
import com.sifang.modules.customer.constant.PartnerConstants;
import com.sifang.modules.customer.dao.CustomerEntryDao;
import com.sifang.modules.customer.entity.CustomerEntry;
import com.sifang.modules.platform.service.AddressService;
import com.sifang.modules.platform.utils.AddressUtils;
import com.sifang.modules.sunshine.SystemSetting.dao.PlanMaterialEntryDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmPlanMaterialEntry;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmProjectSetting;
import com.sifang.modules.sunshine.SystemSetting.service.ProjectInfoSettingService;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
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.BaseController;
import com.sifang.modules.youkua.service.NhPowerStationService;
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.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 物料信息变更
 */
@Controller
@RequestMapping(value = "${adminPath}/entryChanges/materialInformationChange")
public class CrmMaterialInformationChangeController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(CrmCustomerEntryChangeDesignController.class);
    @Autowired
    private CrmMaterialInformationChangeApplyService applyService;
    @Autowired
    private AddressService addressService;
    @Autowired
    private CustomerEntryDao customerEntryDao;
    @Autowired
    private PlanMaterialEntryDao planMaterialEntryDao;
    @Autowired
    private ProjectInfoSettingService projectService;
    @Autowired
    private CrmMaterialInformationChangeApplyDetailDao detailDao;
    @Autowired
    private ProjectInfoSettingService projectInfoSettingService;
    @Autowired
    private NhPowerStationService nhPowerStationService;
    @Autowired
    CustomerEntryService customerService;
    /**
     * 去待审核页面
     */
    @RequestMapping("/changeWaitAuditList")
    public String toChangeWaitAuditList(Model model) {
        User user = UserUtils.getUser();
        model.addAttribute("user", user);
        return "modules/yangguang/changes/materialInformationChange/changeWaitAuditList";
    }

    /**
     * 去变更记录页面
     */
    @RequestMapping("/changeList")
    public String toChangeList(Model model) {
        return "modules/yangguang/changes/materialInformationChange/changeMaterialList";
    }

    /**
     * 去新增物料信息变更申请
     */
    @RequestMapping("/toAddApplyPage")
    public String toAddApplyPage(HttpServletRequest request ,Model model) {
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
        String userName = operator.getUserName();
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String now = format.format(date);
        model.addAttribute("now",now);
        model.addAttribute("userName",userName);
        String partnerId = request.getParameter("partnerId");
        model.addAttribute("partnerId",partnerId);
        if (PartnerConstants.PARTNER_ID_HR.equals(partnerId)) {
            return "modules/yangguang/changes/materialInformationChange/addMaterialChangeApplyHR";
        }else {
            return "modules/yangguang/changes/materialInformationChange/addMaterialChangeApply";
        }
    }

    /**
     * 去选择电站页面
     */
    @RequestMapping("/toCheckEntry")
    public String toCheckEntry(HttpServletRequest request,Model model) {
        User user = UserUtils.getUser();
        //地址信息
        List<Record> pros = AddressUtils.findProvinceListByTraderId(CrmUtils.getCurrentTraderId(user.getId()), null);
        model.addAttribute("province", pros);
        model.addAttribute("partnerId", request.getParameter("partnerId"));
        return "modules/yangguang/changes/materialInformationChange/checkEntry";
    }

    /**
     * 选择条码页面
     */
    @RequestMapping("/toCheckBarcode")
    public String toCheckBarcode(String code ,String id, Model model) {
        model.addAttribute("materialCode", code);
        model.addAttribute("uniqueId", id);
        return "modules/yangguang/changes/materialInformationChange/checkBarcode";
    }
    @ResponseBody
    @RequestMapping("/findEntryById")
    public Object findEntryById(String id){
        Map<String,Object> map = new HashMap<>();
        CustomerEntry customerEntry = customerEntryDao.get(id);
        map.put("customerEntry",customerEntry);
        if (PartnerConstants.PARTNER_ID_HR.equals(customerEntry.getPartnerId())){
            List<Record> projectList = projectInfoSettingService.getEntryProjectByEntryId(id);
            for(Record record : projectList){
                Map<String, Object> materialList = customerService.findUsedMaterialByprojectId(customerEntry.getId(), record.getStr("projectId"));
                record.set("zjList", materialList.get("zj"));
                record.set("nbqList", materialList.get("nbq"));
            }
            map.put("projectList",projectList);
        }else {
            List<Record> materialEntries = planMaterialEntryDao.findMaterialListByEntryId(id);
            List<Record> nbqList = materialEntries.stream().filter(r -> "逆变器".equals(r.getStr("type"))).collect(Collectors.toList());
            List<Record> zjList = materialEntries.stream().filter(r -> "组件".equals(r.getStr("type"))).collect(Collectors.toList());
            map.put("nbqList",nbqList);
            map.put("zjList",zjList);
        }
        return map ;
    }

    /**
     * 列表数据
     *   type 1.待审核 2.变更记录
     */
    @ResponseBody
    @RequestMapping("/getChangeListDate")
    public Object getChangeListDate(HttpServletRequest request){
        LayuiPage<Record> page = new LayuiPage<>(request);
        Map<String, String> params = getParams(request);
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
        return applyService.getPageData(page,params,operator);
    }

    /**
     * 新增
     */
    @ResponseBody
    @RequestMapping(value = "addMaterialInformationChange")
    public Result addMaterialInformationChange(@RequestBody MaterialInformationChangeVo materialVo) {
        try {
            return applyService.addMaterialInformationChange(materialVo);
        }catch (BusinessException ex){
            logger.error("addMaterialInformationChange error", ex);
            return Result.fail(ex.getMessage());
        }catch (Exception ex){
            logger.error("addMaterialInformationChange error", ex);
            return Result.fail(ex.getMessage());
        }

    }
    @ResponseBody
    @RequestMapping(value = "addMaterialInformationChangeHR")
    public Result addMaterialInformationChange(@RequestBody AnyProductMaterialChangeVo materialVo) {
        try {
            return applyService.addMaterialInformationChangeHR(materialVo);
        }catch (BusinessException ex){
            logger.error("addMaterialInformationChange error", ex);
            return Result.fail(ex.getMessage());
        }catch (Exception ex){
            logger.error("addMaterialInformationChange error", ex);
            return Result.fail(ex.getMessage());
        }

    }


    /**
     *审核页面
     */
    @RequestMapping("materialAudit/{id}")
    public String toAuditPage(@PathVariable("id") String id, Model model) {
        CrmMaterialInformationChangeApply apply = applyService.selectById(id);
        CustomerEntry entry = customerEntryDao.get(apply.getEntryId());
        model.addAttribute("apply",apply);
        model.addAttribute("entry",entry);
        List<Record> records = detailDao.findMaterialDetailsByApplyId(apply.getId());
        if (PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
            List<Record> projectList = projectService.getEntryProjectByEntryId(entry.getId());
            for (Record project : projectList) {
                String projectId = project.getStr("projectId");
                List<Record> materialList = records.stream().filter(r -> projectId.equals(r.getStr("project_id"))).collect(Collectors.toList());
                List<Record> zjList = materialList.stream().filter(record -> "1".equals(record.getStr("type"))).collect(Collectors.toList());
                List<Record> nbqList = materialList.stream().filter(record -> "2".equals(record.getStr("type"))).collect(Collectors.toList());
                project.set("zjList",zjList);
                project.set("nbqList",nbqList);
            }
            model.addAttribute("projectList",projectList);
            return "modules/yangguang/changes/materialInformationChange/materialAuditHR";
        }else {
            CrmProjectSetting project = projectService.getById(entry.getProjectId());
            List<Record> zjList = records.stream().filter(record -> "1".equals(record.getStr("type"))).collect(Collectors.toList());
            List<Record> nbqList = records.stream().filter(record -> "2".equals(record.getStr("type"))).collect(Collectors.toList());
            model.addAttribute("project",project);
            model.addAttribute("zjList",zjList);
            model.addAttribute("nbqList",nbqList);
            return "modules/yangguang/changes/materialInformationChange/materialAudit";
        }

    }

    /**
     * 暂存
     */
    @ResponseBody
    @RequestMapping("temp")
    public Result temp(MaterialAuditVo materialAuditVo) {
        return applyService.temp(materialAuditVo);
    }

    /**
     * 审核不通过
     */
    @ResponseBody
    @RequestMapping("refuse")
    public Result refuse(MaterialAuditVo materialAuditVo) {
        return applyService.refuse(materialAuditVo);
    }

    /**
     * 审核通过
     */
    @ResponseBody
    @RequestMapping("pass")
    public Result pass(MaterialAuditVo materialAuditVo) {
        try {
            CrmMaterialInformationChangeApply apply = applyService.selectById(materialAuditVo.getId());
            CustomerEntry entry = customerEntryDao.get(apply.getEntryId());
            Result result = null;
            if (PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
                result = applyService.passHR(materialAuditVo);
            }else {
                result = applyService.pass(materialAuditVo);
            }

            if(result.isOk()){
                //同步能辉数据到监控运维平台
                //添加电站成功标识
                String entryId=result.getData().toString();
                boolean addStationFlag = Db.queryLong(" select count(1) from  nh_yw_interface_process where status = '0' and type = '1' and add_type = '0' and  station_id = ?", entryId) > 0;
                if(addStationFlag){
                    try{
                        //那么要推送物料信息变更的信息到监控系统
                        nhPowerStationService.materialChangeCauseDeviceChange(entryId);
                    }catch (Exception e){
                        logger.error(">>>推送物料信息变更的信息到监控系统 e:",e);
                    }

                }
            }
            return result;
        }catch (BusinessException ex){
            logger.error("materialChangeAuditPass error", ex);
            return Result.fail(ex.getMessage());
        }catch (Exception ex){
            logger.error("materialChangeAuditPass error", ex);
            return Result.fail(ex.getMessage());
        }

    }

    /**
     * 获取变更后的条码列表
     */
    @ResponseBody
    @RequestMapping("getChangeBarCodeList")
    public Object getChangeBarCodeList(String materialCode, String newBarcode){
        List<Record> list = applyService.getChangeBarCode(materialCode, newBarcode);
        return JsonKit.toJson(list);
    }

    /**
     *申请单详情页面
     */
    @RequestMapping("materialDetail/{id}")
    public String toAuditDetailPage(@PathVariable("id") String id, Model model) {
        CrmMaterialInformationChangeApply apply = applyService.selectById(id);
        CustomerEntry entry = customerEntryDao.get(apply.getEntryId());
        model.addAttribute("apply",apply);
        model.addAttribute("entry",entry);
        List<Record> records = detailDao.findMaterialDetailsByApplyId(apply.getId());
        if (PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
            List<Record> projectList = projectService.getEntryProjectByEntryId(entry.getId());
            for (Record project : projectList) {
                String projectId = project.getStr("projectId");
                List<Record> materialList = records.stream().filter(r -> projectId.equals(r.getStr("project_id"))).collect(Collectors.toList());
                List<Record> zjList = materialList.stream().filter(record -> "1".equals(record.getStr("type"))).collect(Collectors.toList());
                List<Record> nbqList = materialList.stream().filter(record -> "2".equals(record.getStr("type"))).collect(Collectors.toList());
                project.set("zjList",zjList);
                project.set("nbqList",nbqList);
            }
            model.addAttribute("projectList",projectList);
            return "modules/yangguang/changes/materialInformationChange/materialDetailHR";
        }else {
            CrmProjectSetting project = projectService.getById(entry.getProjectId());
            List<Record> zjList = records.stream().filter(record -> "1".equals(record.getStr("type"))).collect(Collectors.toList());
            List<Record> nbqList = records.stream().filter(record -> "2".equals(record.getStr("type"))).collect(Collectors.toList());
            model.addAttribute("project",project);
            model.addAttribute("zjList",zjList);
            model.addAttribute("nbqList",nbqList);
            return "modules/yangguang/changes/materialInformationChange/materialDetail";
        }

    }
    /**
     *撤回
     */
    @ResponseBody
    @RequestMapping("cancel/{id}")
    public Result cancel(@PathVariable("id") String id) {
        return applyService.cancel(id);
    }
}
