package com.sifang.modules.changes.controller;


import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.changes.entity.CustomerEntryCompletionChangeRecord;
import com.sifang.modules.changes.entity.CustomerEntryCompletionChangeRecordDetail;
import com.sifang.modules.changes.service.CrmCompletionInfoChangeService;
import com.sifang.modules.changes.dao.CrmCompletionInfoChangeDao;
import com.sifang.modules.changes.vo.CrmCompletionInfoChangeDTO;
import com.sifang.modules.changes.vo.SurveyAuditVo;
import com.sifang.modules.customer.Service.CustomerEntryService;
import com.sifang.modules.customer.Service.CustomerEntrySurveyRecordService;
import com.sifang.modules.customer.constant.PartnerConstants;
import com.sifang.modules.customer.constant.UserConstants;
import com.sifang.modules.customer.dao.CrmAcceptingReportDetailDao;
import com.sifang.modules.customer.dao.CrmCustomerIncomingApplicationInsuranceDao;
import com.sifang.modules.customer.entity.CrmAcceptingReport;
import com.sifang.modules.customer.entity.CrmAcceptingReportDetail;
import com.sifang.modules.customer.entity.CustomerEntry;
import com.sifang.modules.customer.entity.CustomerEntrySurveyRecord;
import com.sifang.modules.customer.form.AddReportReq;
import com.sifang.modules.platform.utils.AddressUtils;
import com.sifang.modules.sunshine.SystemSetting.dao.TraderDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmProjectSetting;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmTraderEmploye;
import com.sifang.modules.sunshine.SystemSetting.service.FormSetService;
import com.sifang.modules.sunshine.SystemSetting.service.ProjectInfoSettingService;
import com.sifang.modules.sunshine.SystemSetting.service.TraderEmployeService;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sunshine.partnerManagement.entity.CrmPartner;
import com.sifang.modules.sunshine.partnerManagement.service.PartnerService;
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.FormSetUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.web.BaseExceptionController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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 java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value = "${adminPath}/completion/change")
public class CrmCompletionInfoChangeController extends BaseExceptionController {

    @Autowired
    CrmCompletionInfoChangeService changeService;

    @Autowired
    CrmCompletionInfoChangeDao changeDao;

    @Autowired
    private PartnerService partnerService;

    @Autowired
    TraderEmployeService traderEmployeService;

    @Autowired
    CustomerEntryService entryService;

    @Autowired
    ProjectInfoSettingService projectService;

    @Autowired
    CustomerEntrySurveyRecordService surveyRecordService;

    @Autowired
    CustomerEntryService customerEntryService;

    @Autowired
    TraderDao traderDao;

    @Autowired
    private CrmCustomerIncomingApplicationInsuranceDao insuranceDao;

    @Autowired
    private FormSetService formSetService;

    @Autowired
    private CrmAcceptingReportDetailDao crmAcceptingReportDetailDao;



    @RequestMapping(value = "findCompletionChangeList")
    public String customerContractList(HttpServletRequest request, Model model) {
        User user = UserUtils.getUser();
        model.addAttribute("user", user);
        return "modules/yangguang/changes/complete/completionInfoChange";
    }


    @ResponseBody
    @RequestMapping(value = "completionChangeList")
    public Object bankCardListDate(HttpServletRequest request) {
        LayuiPage<Record> page = new LayuiPage<>(request);
        Map<String, String> params = getParams(request);
        User user = UserUtils.getUser();
        if (User.USER_TYPE_HZS.equals(user.getUserType())) {
            String parId = CrmUtils.getPartnerId(user.getId());
            CrmPartner partner = partnerService.getById(parId);
            params.put("authorizedId", partner.getAuthorizedId());
        } else if (User.USER_TYPE_PARTNER.equals(user.getUserType())) {
            CrmPartner partner = partnerService.findByUserId(user.getId());
            params.put("authorizedId", partner.getAuthorizedId());
        } else if (User.USER_TYPE_ADVISOR.equals(user.getUserType())) {
            CrmTraderEmploye employe = traderEmployeService.findByUserId(user.getId());
            params.put("engineerId", employe.getId());
        }
        Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
        changeService.listData(page, params, "0", operator);
        return page.renderJson();
    }


    @RequestMapping("changeRecord")
    public String record(){
        return "modules/yangguang/changes/complete/completionInfoChangeRecord";
    }


    /**
     * 变更记录列表数据
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "recordData")
    public Object recordData(HttpServletRequest request) {
        LayuiPage<Record> page = new LayuiPage<>(request);
        Map<String, String> params = getParams(request);
        User user = UserUtils.getUser();
        if(User.USER_TYPE_HZS.equals(user.getUserType())){
            String parId = CrmUtils.getPartnerId(user.getId());
            CrmPartner partner = partnerService.getById(parId);
            params.put("authorizedId", partner.getAuthorizedId());
        }else if(User.USER_TYPE_PARTNER.equals(user.getUserType())){
            CrmPartner partner = partnerService.findByUserId(user.getId());
            params.put("authorizedId", partner.getAuthorizedId());
        } else if (User.USER_TYPE_ADVISOR.equals(user.getUserType())) {
            CrmTraderEmploye employe = traderEmployeService.findByUserId(user.getId());
            params.put("engineerId", employe.getId());
        }
        Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
        changeService.listData(page, params, "1", operator);
        return page.renderJson();
    }

    @RequestMapping("/toAddPage")
    public String toAddPage(HttpServletRequest request,Model model) {
        String partnerId = request.getParameter("partnerId");
        model.addAttribute("partnerId", partnerId);
        if (PartnerConstants.PARTNER_ID_HR.equals(partnerId)){
            return "modules/yangguang/changes/complete/addCompletionChangeHR";
        }
        return "modules/yangguang/changes/complete/addComplete";
    }

    /**
     * 根据电站编号获取电站信息
     * @param stationCode
     * @return
     */
    @ResponseBody
    @RequestMapping("selectNumber/{stationCode}")
    public Result selectNumber(@PathVariable("stationCode") String stationCode) {
        Result ret = Result.ok();
        Map<String, Object> resMap = Maps.newHashMap();
        CustomerEntry customerEntry = entryService.findCustomerEntryById(stationCode);
        if (customerEntry == null) {
            ret = Result.fail("未找到电站信息");
            return ret;
        }

        //判断电站与角色是否相符
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
        if(StringUtil.equalsAny(operator.getUserType(), UserConstants.TYPE_TRADER, User.USER_TYPE_ADVISOR)){
            Record record= CrmUtils.getUserTrader(operator.getUserType(),operator.getUserId());
            String traderId =record.getStr("id");
            if(UserConstants.TYPE_TRADER.equals(operator.getUserType())){  //代理商
                if ("1".equals(record.getStr("type"))){  // 1.一级代理商 2.二级代理商
                    if (!customerEntry.getDistributorId().equals(traderId)) {
                        ret = Result.fail("未找到电站信息");
                        return ret;
                    }
                }else{  //二级代理商
                    if (UserConstants.TYPE_TRADER.equals(operator.getUserType())) {
                        //代理商只能查看自己的
                        if (!traderId.equals(customerEntry.getCreateTraderId())) {
                            ret = Result.fail("未找到电站信息");
                            return ret;
                        }
                    }
                }
            }else { //代理商人员
                if (!traderId.equals(customerEntry.getCreateTraderId())) {
                    ret = Result.fail("未找到电站信息");
                    return ret;
                }
            }
        }
       /* if (!StringUtil.equalsAny(customerEntry.getStatus(), CustomerEntryConstants.ENTRY_STATUS_DBW, CustomerEntryConstants.ENTRY_STATUS_YSBH
                , CustomerEntryConstants.ENTRY_STATUS_DYS)) {
            ret = Result.fail("电站状态不可进行该操作");
            return ret;
        }*/
        // 验收报告
        CrmAcceptingReport report = new CrmAcceptingReport();
        if (StringUtil.isNotBlank(customerEntry.getReceivingReportId())) {
            report = customerEntryService.getReportById(customerEntry.getReceivingReportId());
        }
        resMap.put("report", report);
        CustomerEntrySurveyRecord surveyRecord = surveyRecordService.findByEntryId(customerEntry.getId());
        resMap.put("customerEntry", customerEntry);
        resMap.put("surveyRecord", surveyRecord);
        resMap.put("project", projectService.getById(customerEntry.getProjectId()));
        resMap.put("formSet", FormSetUtils.getFormPartSetByStep(null, "", "09", customerEntry.getPartnerId(), false));
        resMap.put("formSetMerge", FormSetUtils.getFormPartSetByStep(null, "", "10", customerEntry.getPartnerId(), false));
        List<String> needUploadImg=formSetService.getMustFillFlag("10",customerEntry.getPartnerId());
        resMap.put("mergeInfoSet",needUploadImg);
        resMap.put("insurances", insuranceDao.getByEntryIds(customerEntry.getId()));
        //获取电力公司
        String powerCompany=AddressUtils.findProCodeNameByCode(customerEntry.getProvinceCode());
        resMap.put("powerCompany",powerCompany);
        if (PartnerConstants.PARTNER_ID_HR.equals(customerEntry.getPartnerId())){
            List<Record> projectList = projectService.getEntryProjectByEntryId(customerEntry.getId());
            //华融多产品
            for(Record record : projectList){
                CrmAcceptingReportDetail acceptReport = crmAcceptingReportDetailDao.findByEntryIdAndProjectId(customerEntry.getId(),record.getStr("projectId"));
                record.set("acceptReport", acceptReport);
            }
            resMap.put("projectList",projectList);
        }
        ret.setData(resMap);
        return ret;
    }

    /**
     * 去选择电站页面
     */
    @RequestMapping("/toSelectEntry")
    public String toSelectEntry(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/complete/selectEntry";
    }


    /**
     * 添加变更记录/暂存变更记录/修改变更记录
     * @param recordVo
     * @return
     */
    @ResponseBody
    @RequestMapping("addChangeRecord")
    public Result addChangeRecord(CrmCompletionInfoChangeDTO recordVo) {
        return changeService.addChangeRecord(recordVo);
    }

    /**
     * 添加变更记录--华融
     * @return
     */
    @ResponseBody
    @RequestMapping("addHRChangeRecord")
    public Result addHRChangeRecord(@RequestBody AddReportReq req) {
        return changeService.addHRChangeRecord(req);
    }

    /**
     * 审核页面
     *
     * @return
     */
    @RequestMapping("audit/{id}")
    public String toAuditPage(@PathVariable("id") String id, Model model) {
        CustomerEntryCompletionChangeRecord record = changeService.selectById(id);
        CustomerEntryCompletionChangeRecord oldRecord = changeService.selectPre(record.getEntryId(), record.getNum());
        CustomerEntry customerEntry = entryService.getById(record.getEntryId());
        CrmProjectSetting projectSetting = projectService.getById(customerEntry.getProjectId());
        model.addAttribute("customerEntry", customerEntry);
        model.addAttribute("project", projectSetting);
        model.addAttribute("change", record);
        model.addAttribute("oldChange", oldRecord);
        model.addAttribute("formSet", JSONObject.toJSONString(FormSetUtils.getFormPartSetByStep(null, "", "09", customerEntry.getPartnerId(), false)));
        if (PartnerConstants.PARTNER_ID_HR.equals(customerEntry.getPartnerId())){
            model.addAttribute("info2",formSetService.getListByCondition("09", customerEntry.getPartnerId()) );
            List<Record> projectList = projectService.getEntryProjectByEntryId(customerEntry.getId());
            model.addAttribute("projectDetailList",projectList);
            //华融多产品--获取更新的记录
            List<CustomerEntryCompletionChangeRecordDetail> newList=changeService.getByRecordId(record.getId());
            model.addAttribute("newList",newList);
            Map<String, CustomerEntryCompletionChangeRecordDetail> newEntryChangeMap = newList.stream().collect(Collectors.toMap(e -> e.getProjectId(), e -> e, (a, b) -> a));
            model.addAttribute("newListMap",newEntryChangeMap);
            List<CustomerEntryCompletionChangeRecordDetail> oldList=changeService.getByRecordId(oldRecord.getId());
            model.addAttribute("oldList",oldList);
            Map<String, CustomerEntryCompletionChangeRecordDetail> oldEntryChangeMap = oldList.stream().collect(Collectors.toMap(e -> e.getProjectId(), e -> e, (a, b) -> a));
            model.addAttribute("oldListMap",oldEntryChangeMap);
            model.addAttribute("from","audit");
            model.addAttribute("completionChange", record);
            model.addAttribute("remarks",record.getRemarks());
            return "modules/yangguang/changes/complete/completeChangeDetailHR";
        }
        return "modules/yangguang/changes/complete/completeChangeAudit";
    }

    /**
     * 审核通过
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("pass")
    public Result pass(SurveyAuditVo auditVo) {
        Result ret = null;
        try {
            ret = changeService.pass(auditVo);
        } catch (IllegalArgumentException e) {
            ret = Result.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            ret = Result.fail("操作失败");
        }
        return ret;
    }

    /**
     * 备注暂存
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("tempRemark")
    public Result tempRemark(SurveyAuditVo auditVo) {
        Result ret = null;
        try {
            ret = changeService.tempRemark(auditVo);
        } catch (IllegalArgumentException e) {
            ret = Result.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            ret = Result.fail("操作失败");
        }
        return ret;
    }


    /**
     * 审核通过
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("passHR")
    public Result passHR(SurveyAuditVo auditVo) {
        Result ret = null;
        try {
            ret = changeService.passHR(auditVo);
        } catch (IllegalArgumentException e) {
            ret = Result.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            ret = Result.fail("操作失败");
        }
        return ret;
    }

    /**
     * 审核不通过
     * @return
     */
    @ResponseBody
    @RequestMapping("refuse")
    public Result refuse(SurveyAuditVo auditVo) {
        return changeService.refuse(auditVo);
    }

    /**
     * 变更详情
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/toComDetail/{id}")
    public String toComDetail(@PathVariable("id") String id, Model model) {
        CustomerEntryCompletionChangeRecord record = changeService.selectById(id);
        CustomerEntryCompletionChangeRecord oldRecord = changeService.selectPre(record.getEntryId(), record.getNum());
        CustomerEntry customerEntry = entryService.getById(record.getEntryId());
        CrmProjectSetting projectSetting = projectService.getById(customerEntry.getProjectId());
        model.addAttribute("customerEntry", customerEntry);
        model.addAttribute("project", projectSetting);
        model.addAttribute("change", record);
        model.addAttribute("oldChange", oldRecord);
        model.addAttribute("formSet", JSONObject.toJSONString(FormSetUtils.getFormPartSetByStep(null, "", "09", customerEntry.getPartnerId(), false)));

        if (PartnerConstants.PARTNER_ID_HR.equals(customerEntry.getPartnerId())){
            model.addAttribute("info2",formSetService.getListByCondition("09", customerEntry.getPartnerId()) );
            List<Record> projectList = projectService.getEntryProjectByEntryId(customerEntry.getId());
            model.addAttribute("projectDetailList",projectList);
            //华融多产品--获取更新的记录
            List<CustomerEntryCompletionChangeRecordDetail> newList=changeService.getByRecordId(record.getId());
            model.addAttribute("newList",newList);
            Map<String, CustomerEntryCompletionChangeRecordDetail> newEntryChangeMap = newList.stream().collect(Collectors.toMap(e -> e.getProjectId(), e -> e, (a, b) -> a));
            model.addAttribute("newListMap",newEntryChangeMap);
            List<CustomerEntryCompletionChangeRecordDetail> oldList=changeService.getByRecordId(oldRecord.getId());
            model.addAttribute("oldList",oldList);
            Map<String, CustomerEntryCompletionChangeRecordDetail> oldEntryChangeMap = oldList.stream().collect(Collectors.toMap(e -> e.getProjectId(), e -> e, (a, b) -> a));
            model.addAttribute("oldListMap",oldEntryChangeMap);
            model.addAttribute("from","detail");
            return "modules/yangguang/changes/complete/completeChangeDetailHR";
        }
        return "modules/yangguang/changes/complete/complateChangeDetail";
    }

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




}
