package com.sifang.modules.customer.controller;

import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.Service.CustomerEntryComponentService;
import com.sifang.modules.customer.Service.CustomerEntryOrgFilesService;
import com.sifang.modules.customer.Service.CustomerEntryService;
import com.sifang.modules.customer.constant.CustomerEntryConstants;
import com.sifang.modules.customer.constant.PartnerConstants;
import com.sifang.modules.customer.dao.*;
import com.sifang.modules.customer.entity.*;
import com.sifang.modules.customer.form.AuditArchivesReq;
import com.sifang.modules.customer.form.SubmitArchivesReq;
import com.sifang.modules.platform.service.AddressService;
import com.sifang.modules.platform.utils.AddressUtils;
import com.sifang.modules.setting.service.MemberService;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmProjectSetting;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmTrader;
import com.sifang.modules.sunshine.SystemSetting.service.*;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
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.dao.SysCapitalDictDao;
import com.sifang.modules.sys.entity.Operator;
import com.sifang.modules.sys.web.BaseController;
import com.sifang.modules.utils.util.IsInteger;
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.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping("${adminPath}/customer/org/files")
public class CustomerEntryOrgFilesController extends BaseController {

    @Autowired
    private CustomerEntryOrgFilesService service;

    @Autowired
    private CustomerEntryService customerEntryService;

    @Autowired
    private CustomerEntrySurveyRecordDao surveyRecordDao;

    @Autowired
    private MemberService memberService;

    @Autowired
    private ProjectInfoSettingService projectService;

    @Autowired
    private FormSetService formSetService;

    @Autowired
    private TenantYxBankCardDao tenantYxBankCardDao;

    @Autowired
    private CustomerEntryTenantDao tenantDao;

    @Autowired
    ProjectInstallService projectInstallService;

    @Autowired
    PlanService planService;

    @Autowired
    TraderService traderService;

    @Autowired
    CustomerEntryService customerService;

    @Autowired
    AddressService addressService;

    @Autowired
    private CustomerEntryComponentService customerEntryComponentService;

    @Autowired
    private PartnerService partnerService;

    @Autowired
    private SysCapitalDictDao sysCapitalDictDao;

    @Autowired
    private CrmCustomerEntryProjectDao crmCustomerEntryProjectDao;
    @Autowired
    private CrmEntryCombinerBoxGroupDao combinerBoxGroupDao;

    @Autowired
    private ProjectInfoSettingService projectInfoSettingService;

    @Autowired
    private CrmCustomerEntrySurveyRecordDetailDao crmCustomerEntrySurveyRecordDetailDao;

    @Autowired
    private CrmCustomerEntryDesignDao crmCustomerEntryDesignDao;

    /**
     * 跳转审核页面
     */
    @RequestMapping(value = "toFileReviewForm")
    public String toFileReviewForm(HttpServletRequest request, Model model) {
        String entryId = request.getParameter("entryId");

        String type = request.getParameter("type");
        model.addAttribute("type", type);
        CustomerEntry entry = customerService.getById(entryId);
        model.addAttribute("entry", entry);
        if ("1".equals(entry.getTenantType())) {
            model.addAttribute("authorizationUrl", customerService.getContractPath(entry));
        }
        // 获取资方信息
        model.addAttribute("partner", partnerService.getById(entry.getPartnerId()));

        CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(entryId);
        model.addAttribute("surveyRecord", surveyRecord);
        String projectId = entry.getProjectId();
        if(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
            List<Record> projects = crmCustomerEntryProjectDao.getProjectsByEntryId(entry.getId());
            projectId = projects.get(0).getStr("id");
        }
        CrmProjectSetting pro = projectService.getById(projectId);
        model.addAttribute("pro", pro);
        //地址信息
        List<Record> pros = addressService.getProvinces();
        model.addAttribute("pros", pros);
        String province = entry.getProvince();
        String city = entry.getCity();
        //根据省查询下面的
        List<Record> citys = AddressUtils.getCityByProName(province);
        List<Record> areas = AddressUtils.getAreaByCityName(city);
        model.addAttribute("faccitys", citys);
        model.addAttribute("areas", areas);
        CrmTrader trader = traderService.getById(entry.getDistributorId());

        model.addAttribute("trader", trader);
        //获取所有项目信息
        model.addAttribute("project", memberService.getProjectByTraderLists(trader.getId()));
        //获取安装方式
        model.addAttribute("insta", projectInstallService.findProjectInstalls());

        //获取方案
        model.addAttribute("plan", planService.findAllPlan());
        if(CustomerEntryConstants.SCHEME_TYPE_TWO.equals(entry.getSchemeType())){
            model.addAttribute("compose", customerService.findPlanInfoEntryId(entryId));
            model.addAttribute("comPlan",planService.findPlanByAssembly("","",""));
            if(entry.getDesignCapacity() == null){
                entry.setDesignCapacity(0);
            }
            //根据组件规格和组件块数查找电气配置
            if(StringUtil.isNotBlank(entry.getComponentSpec())&& entry.getDesignCapacity()!= null&& entry.getDesignCapacity()>0){
                model.addAttribute("elect",planService.findElectricPlan(entry.getComponentSpec(),entry.getDesignCapacity().toString()));
            }
            // planService.findPlanByAssembly(entry.getComponentSpec(),"",entry);

        }else{
            model.addAttribute("composeOne",customerService.findByEntrySchemeId(entry.getSchemeId()));
        }
        // 获取电站电器材料
        List<Record> componentList = customerEntryComponentService.findByEntryId(entryId);
        List<Record> assemblyList = componentList.stream().filter(r -> r.getStr("item_type").equals("3")).collect(Collectors.toList());
        List<Record> inverterList = componentList.stream().filter(r -> r.getStr("item_type").equals("1")).collect(Collectors.toList());
        List<Record> gridConnectionList = componentList.stream().filter(r -> r.getStr("item_type").equals("2")).collect(Collectors.toList());
        List<Record> gridSupportList = componentList.stream().filter(r -> r.getStr("item_type").equals("4")).collect(Collectors.toList());
        // 获取系统设置的电器材料
        List<Record> allElectric = planService.findAllElectric();
        List<Record> sysAssemblyList = allElectric.stream().filter(r -> r.getStr("type").equals("3") && Integer.valueOf(r.get("model"))>=pro.getAssemblySpecs() ).collect(Collectors.toList());

        List<Record> sysInverterList = allElectric.stream().filter(r -> r.getStr("type").equals("1")).collect(Collectors.toList());
        List<Record> sysGridConnectionList = allElectric.stream().filter(r -> r.getStr("type").equals("2")).collect(Collectors.toList());
        List<Record> sysGridSupportList = allElectric.stream().filter(r -> r.getStr("type").equals("4")).collect(Collectors.toList());
        model.addAttribute("assemblyList", assemblyList);
        model.addAttribute("inverterList", inverterList);
        model.addAttribute("gridConnectionList", gridConnectionList);
        model.addAttribute("sysAssemblyList", sysAssemblyList);
        model.addAttribute("sysInverterList", sysInverterList);
        model.addAttribute("sysGridConnectionList", sysGridConnectionList);
        model.addAttribute("sysGridSupportList", sysGridSupportList);
        model.addAttribute("gridSupportList", gridSupportList);
        //获取所欲逆变器和并网箱
        model.addAttribute("inverters",planService.getElectricSet("1"));
        model.addAttribute("boxs",planService.getElectricSet("2"));
        model.addAttribute("quaimgsCount",0);
        if(surveyRecord != null && StringUtil.isNotBlank(surveyRecord.getHouseOwnership())){
            String[] arr=surveyRecord.getHouseOwnership().split(",");
            model.addAttribute("quaimgs",arr);
            model.addAttribute("quaimgsCount", arr.length);
        }
        // 获取表单设置 信息登记阶段
        model.addAttribute("info", formSetService.getListByCondition("01", entry.getPartnerId()));
        //获取表单设置  勘测设计
        model.addAttribute("info2", formSetService.getListByCondition("02", entry.getPartnerId()));
        //获取表单设置  档案资料
        model.addAttribute("info3", formSetService.getListByCondition("05", entry.getPartnerId()));
        CrmTenantYxBankCard card=tenantYxBankCardDao.getByIdCard(entry.getIdCode(),entry.getManagementType(),entry.getPartnerId());
        model.addAttribute("card",card);
        CustomerEntryTenant tenant = tenantDao.getByTenantId(entry.getTenantId());
        model.addAttribute("tenant",tenant);
        IsInteger str = new IsInteger();
        if(str.isInteger(entry.getStatus())&& (entry.getStatus().equals("0")|| entry.getStatus().equals("1") || entry.getStatus().equals("2") || entry.getStatus().equals("3") || entry.getStatus().equals("4")) ){
            String stationName=entry.getProvince()+entry.getArea()+entry.getTenantName()+(new BigDecimal(entry.getDesignCapacity()).divide(new BigDecimal(1000),3, RoundingMode.DOWN).stripTrailingZeros().toPlainString())+"KW光伏电站";
            model.addAttribute("stationName", stationName);
        }else{
            String stationName=entry.getProvince()+entry.getArea()+entry.getTenantName()+(entry.getActualCapacity().divide(new BigDecimal(1000),3, RoundingMode.DOWN).stripTrailingZeros().toPlainString())+"KW光伏电站";
            model.addAttribute("stationName", stationName);
        }


        // 查询档案信息
        model.addAttribute("orgFiles", service.getOneByEntryId(entryId));

        if(PartnerConstants.PARTNER_ID_YX.equals(entry.getPartnerId())){
            //获取历史设置的汇流方式
            Record recordBox=combinerBoxGroupDao.getEntryCombinerBoxSet(entryId);
            model.addAttribute("recordBox",recordBox);
            //获取一户多站的信息
            Record oneToAnyBoxSet=combinerBoxGroupDao.getOneToAnyBoxSet(entry.getIdCode(),entry.getRegno(),entry.getCreateTraderId(),entry.getTenantType());
            model.addAttribute("oneToAnyBoxSet",oneToAnyBoxSet);
        }
        if(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
            List<Record> entryProject = crmCustomerEntryProjectDao.getProjectsByEntryId(entry.getId());
            List<CrmCustomerEntryDesign> entryDesigns = crmCustomerEntryDesignDao.findByEntryId(entry.getId());
            List<CrmCustomerEntrySurveyRecordDetail> entrySurveys = crmCustomerEntrySurveyRecordDetailDao.findByEntryId(entry.getId());
            int entryProjectNum = entryProject.size();
            if(entryProjectNum<5){
                for(int i=0;i<5-entryProjectNum;i++){
                    entryProject.add(new Record());
                }
            }
            int entryDesignsNum = entryDesigns.size();
            if(entryDesignsNum<5){
                for(int i=0;i<5-entryDesignsNum;i++){
                    entryDesigns.add(new CrmCustomerEntryDesign());
                }
            }
            int entrySurveysNum = entrySurveys.size();
            if(entrySurveysNum<5){
                for(int i=0;i<5-entrySurveysNum;i++){
                    entrySurveys.add(new CrmCustomerEntrySurveyRecordDetail());
                }
            }
            if (CustomerEntryConstants.SCHEME_TYPE_TWO.equals(entry.getSchemeType())) {
                model.addAttribute("compose", customerService.findPlanInfoEntryId(entryId));
            } else {//标准方案
                List<Record> composeOnes = new ArrayList<>();
                for(CrmCustomerEntryDesign entryDesign:entryDesigns){
                    Record composeOne = customerService.findByEntrySchemeId(entryDesign.getSchemeId());
                    if(composeOne!=null){
                        composeOne.set("projectId",entryDesign.getProjectId());
                    }
                    composeOnes.add(composeOne);
                }
                model.addAttribute("composeOneHr", composeOnes);
            }
            model.addAttribute("entryProject",entryProject);
            model.addAttribute("entryProjectNum",entrySurveysNum);
            model.addAttribute("entryDesigns",entryDesigns);
            model.addAttribute("entrySurveys",entrySurveys);
            List<Record> projectList = projectInfoSettingService.getEntryProjectByEntryId(entryId);
            model.addAttribute("projectList",projectList);
            return "modules/yangguang/customer/entry/toFileReviewHRForm";
        }else{
            return "modules/yangguang/customer/entry/toFileReviewForm";
        }
    }

    /**
     * 档案审核
     */
    @ResponseBody
    @RequestMapping(value = "auditArchives")
    public Result auditArchives(@RequestBody @Validated AuditArchivesReq req) {
        try {
            User user = UserUtils.getUser();
            return service.auditArchives(req, Operator.of(user));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
    }
    /**
     * 跳转编辑档案页面
     */
    @RequestMapping(value = "toFileReviewForm2")
    public String toFileReviewForm2(HttpServletRequest request, Model model) {
        String entryId = request.getParameter("entryId");

        // 获取电站信息
        CustomerEntry entry = customerEntryService.getById(entryId);
        model.addAttribute("entry", entry);

        CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(entryId);
        model.addAttribute("surveyRecord", surveyRecord);
        //获取所有项目信息
        model.addAttribute("project", memberService.getProjectByTraderLists(entry.getDistributorId()));
        CrmProjectSetting pro=null;
        if(StringUtil.isNotBlank(entry.getProjectId()))
         pro = projectService.getById(entry.getProjectId());
        model.addAttribute("pro", pro);

        // 获取表单设置 信息登记阶段
        model.addAttribute("info", formSetService.getListByCondition("01", entry.getPartnerId()));
        //获取表单设置  勘测设计
        model.addAttribute("info2", formSetService.getListByCondition("02", entry.getPartnerId()));
        //获取表单设置  档案资料
        model.addAttribute("info3", formSetService.getListByCondition("05", entry.getPartnerId()));
        CrmTenantYxBankCard card = tenantYxBankCardDao.getByIdCard(entry.getIdCode(), entry.getManagementType(),entry.getPartnerId());
        model.addAttribute("card", card);
        CustomerEntryTenant tenant = tenantDao.getByTenantId(entry.getTenantId());
        model.addAttribute("tenant", tenant);
        // 查询档案信息
        model.addAttribute("orgFiles", service.getOneByEntryId(entryId));
        // 获取资方信息
        model.addAttribute("partner", partnerService.getById(entry.getPartnerId()));
        //获取共签人关系字典
        List<Record> bpRelationList = sysCapitalDictDao.getDictionaryList("bp_relation", entry.getPartnerId());
        model.addAttribute("bpRelationList",bpRelationList);
        if("04".equals(entry.getPartnerId())){
            List<Record> projectList = projectInfoSettingService.getEntryProjectByEntryId(entryId);
            model.addAttribute("projectList",projectList);
            return "modules/yangguang/customer/entry/toFileReviewHRForm2";
        }else{
            return "modules/yangguang/customer/entry/toFileReviewForm2";
        }
    }

    /**
     * 提交档案
     */
    @ResponseBody
    @RequestMapping(value = "submitArchives")
    public Result submitArchives(@RequestBody @Validated SubmitArchivesReq req) {
        try {
            User user = UserUtils.getUser();
            Operator operator = Operator.of(user);
            return service.submitArchives(req,operator);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 档案审核暂存
     */
    @ResponseBody
    @RequestMapping(value = "auditArchivesTemp")
    public Result auditArchivesTemp(String id ,String remark) {
        try {
            return service.auditArchivesTemp(id, remark);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
    }
}
