package com.sifang.modules.sunshine.SystemSetting.controller;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.Service.CrmCustomerEntrySurveyRecordDetailService;
import com.sifang.modules.customer.Service.CustomerEntryComponentService;
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.CrmCustomerEntryDesignDao;
import com.sifang.modules.customer.dao.CrmCustomerEntryProjectDao;
import com.sifang.modules.customer.dao.CrmCustomerEntrySurveyRecordDetailDao;
import com.sifang.modules.customer.entity.ComposePlan;
import com.sifang.modules.customer.entity.CrmCustomerEntryDesign;
import com.sifang.modules.customer.entity.CrmCustomerEntrySurveyRecordDetail;
import com.sifang.modules.customer.entity.CustomerEntry;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmProjectSetting;
import com.sifang.modules.sunshine.SystemSetting.form.AddElectricMaterialSet;
import com.sifang.modules.sunshine.SystemSetting.form.AddElectricPlan;
import com.sifang.modules.sunshine.SystemSetting.form.AddPlan;
import com.sifang.modules.sunshine.SystemSetting.form.FormSetPageVo;
import com.sifang.modules.sunshine.SystemSetting.service.FormSetService;
import com.sifang.modules.sunshine.SystemSetting.service.PlanService;
import com.sifang.modules.sunshine.SystemSetting.service.ProjectInstallService;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.supply.stock.utils.MaterialUtils;
import com.sifang.modules.sys.util.GuardUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.web.BaseExceptionController;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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.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.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author hongzq
 * 方案管理
 */
@Controller
@RequestMapping(value = "${adminPath}/planManage")
public class PlanController extends BaseExceptionController {

    @Autowired
    CustomerEntryService customerEntryService;

    @Autowired
    PlanService planService;

    @Autowired
    ProjectInstallService projectInstallService;

    @Autowired
    private CustomerEntryComponentService customerEntryComponentService;

    @Autowired
    private FormSetService formSetService;
    @Autowired
    private CrmCustomerEntryProjectDao crmCustomerEntryProjectDao;
    @Autowired
    private CrmCustomerEntryDesignDao crmCustomerEntryDesignDao;

    @Autowired
    private CrmCustomerEntrySurveyRecordDetailDao crmCustomerEntrySurveyRecordDetailDao;

    @Autowired
    private CrmCustomerEntrySurveyRecordDetailService recordDetailService;
    @Autowired
    CustomerEntryService customerService;

    @RequestMapping(value = "index")
    public String planList(Model model) {
        model.addAttribute("insta", projectInstallService.findProjectInstalls());
        return "modules/yangguang/systemSetting/plan/planList";
    }


    @RequestMapping(value = "toImportMaterial")
    public String toImport(){
        return "modules/yangguang/systemSetting/plan/importPlan";
    }

    @ResponseBody
    @RequestMapping(value = "checkImportMaterial")
    public Object checkImportMaterial(MultipartFile file) throws IOException {
        Map<String, String> params = Maps.newHashMap();
        params.put("extName", StringUtil.getFileExtName(file.getOriginalFilename()));
        Map<String, Object> retMap = planService.checkImportPlan(params, file.getInputStream());
        return JSONObject.fromObject(retMap);
    }

    @RequestMapping(value = "importMaterial")
    @ResponseBody
    public JSONObject importMaterial(MultipartFile file) throws IOException {
        Map<String, String> params = Maps.newHashMap();
        params.put("fileName", file.getOriginalFilename());
        Map<String, Object> retMap = planService.importPlan(params, file.getInputStream());
        return JSONObject.fromObject(retMap);
    }

    @RequestMapping(value = "toAdd")
    public String toAdd(String id,String type, String mode, Model model) {
        if (StringUtils.isNotBlank(id)) {
            Record plan = planService.getPlanById(id);
            List<Record> materials = planService.listMaterialByPlanId(id);
            model.addAttribute("plan", plan);
            model.addAttribute("materials", materials);
        }
        //获取安装方式
        model.addAttribute("insta", projectInstallService.findProjectInstalls());
        model.addAttribute("type",type);
        model.addAttribute("mode", mode);
        return "modules/yangguang/systemSetting/plan/addPlan";
    }

    /**
     * 查看已匹配的方案
     */
    @RequestMapping(value = "viewMatchedPlan")
    public String viewMatchedPlan(String entryId, String readOnly, Model model) {
        CustomerEntry entry = customerEntryService.getById(entryId);
        //获取所有物料明细
        List<Record> materials = planService.listMatchedMaterialByPlanId(entryId);
        model.addAttribute("materials", materials);

        model.addAttribute("readOnly", readOnly);
        model.addAttribute("matchTime", entry.getExamineTime());
        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());
        model.addAttribute("assemblyList", assemblyList);
        model.addAttribute("inverterList", inverterList);
        model.addAttribute("designCapacity", entry.getDesignCapacity());
        model.addAttribute("gridConnectionList", gridConnectionList);
        model.addAttribute("gridSupportList", gridSupportList);
        model.addAttribute("info2",formSetService.getListByCondition("02", entry.getPartnerId()) );
        if("2".equals(entry.getSchemeType())){
            //匹配方案
            //获取方案
            model.addAttribute("entry", entry);
//            List<Record> lists = planService.findComposePlanByEntryId(entryId);
            List<Record> lists = customerEntryService.findPlanInfoEntryId(entryId);
            model.addAttribute("lists", lists);
            return "modules/yangguang/systemSetting/plan/composePlan";

        }else{
            //获取安装方式
            model.addAttribute("insta", projectInstallService.findProjectInstalls());
            model.addAttribute("mode", "view");
            model.addAttribute("entry", entry);
            Record plan = planService.getPlanById(entry.getSchemeId());
            if(plan!=null){
                plan.set("name", entry.getSchemeName());
            }
            model.addAttribute("plan", plan);
        }
        if(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
            List<CrmCustomerEntryDesign> designDetail = crmCustomerEntryDesignDao.findByEntryId(entryId);
            model.addAttribute("designDetail",designDetail);
            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());
                }
            }
            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);
            return "modules/yangguang/systemSetting/plan/addPlanHr";
        }

        return "modules/yangguang/systemSetting/plan/addPlan";
    }


    @ResponseBody
    @RequestMapping(value = "add")
    public Result<Void> addOrEditPlan(@Valid @RequestBody AddPlan req, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return errRet(bindingResult);
        }
        planService.addOrEditPlan(req);
        return Result.ok();
    }

    @ResponseBody
    @RequestMapping(value = "delete")
    public Result<Void> deleteTrader(String ids){
        GuardUtils.notBlank(ids, "ids不能为空");
        planService.deletePlan(ids);
        return Result.ok();
    }

    @ResponseBody
    @RequestMapping(value = "list")
    public Object getSite(HttpServletRequest request) {
        LayuiPage<Record> page = new LayuiPage<>(request);
        Map<String, String> map = getParams(request);
        planService.listPlan(page, map);
        return page.renderJson();
    }

    /**
     * 根据规planType取支架配置方案
    */
    @ResponseBody
    @RequestMapping(value = "findPlanByAssembly")
    public Object findPlanByAssembly(HttpServletRequest request) {

        Map<String, String> map = getParams(request);

        String projectId = map.get("projectId");
        List<Record> list = planService.findPlanByAssembly(projectId, map.get("name"), map.get("planType"));
        if(StringUtil.isNotBlank(projectId) && StringUtil.isBlank(map.get("planType"))){

            CrmProjectSetting project = customerEntryService.findrojectSettingById(projectId);
            String mode_id = project.getInstallModeId();
            List<Record> rds = Lists.newArrayList();

            for(Record rd :list){
                String plan_type_id = rd.getStr("plan_type_id");
                if(mode_id.contains(plan_type_id)){
                    rds.add(rd);
                }
            }
            return rds;
        }

        return list;
    }


    @RequestMapping(value = "/togetherProgram")
    public String togetherProgram() {
        return "modules/yangguang/systemSetting/plan/togetherProgramPage";
    }

    @RequestMapping(value = "/electricProgram")
    public String electricProgram(){
        return "modules/yangguang/systemSetting/plan/electricProgramPage";
    }

    @RequestMapping(value = "toAddElectric")
    public String toAddElectric(String id, String mode, Model model) {
        if (StringUtils.isNotBlank(id)) {
            Record plan = planService.getElectricPlanById(id);
            List<Record> materials = planService.listMaterialByPlanId(id);
            model.addAttribute("plan", plan);
            model.addAttribute("materials", materials);
        }
        model.addAttribute("inverters",planService.getElectricSet("1"));
        model.addAttribute("boxs",planService.getElectricSet("2"));
        model.addAttribute("mode", mode);
        return "modules/yangguang/systemSetting/plan/addElectricPlan";
    }
    /**
     * 根据组件规格和组件块数查找电气配置
    */
    @ResponseBody
    @RequestMapping(value = "findElectricPlan")
    public Object findElectricPlan(String assembly,String assemblyNum){
        if(StringUtil.isNotBlank(assembly) && StringUtil.isNotBlank(assemblyNum)){
         Record es= planService.findElectricPlan(assembly,assemblyNum);
        return es;
        }

        return Result.fail("2004","参数为空");
    }


    @ResponseBody
    @RequestMapping(value = "addElectricPlan")
    public Result<Void> addElectricPlan(@Valid @RequestBody AddElectricPlan req, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return errRet(bindingResult);
        }
        planService.addElectricPlan(req);
        return Result.ok();
    }

    @ResponseBody
    @RequestMapping(value = "deleteElectricPlan")
    public Result<Void> deleteElectricPlan(String ids){
        GuardUtils.notBlank(ids, "ids不能为空");
        planService.deleteElectricPlan(ids);
        return Result.ok();
    }

    @ResponseBody
    @RequestMapping(value = "electriclistDate")
    public Object electriclistDate(HttpServletRequest request) {
        LayuiPage<Record> page = new LayuiPage<>(request);
        Map<String, String> map = getParams(request);
        planService.listElectricPlan(page, map);
        return page.renderJson();
    }

    @ResponseBody
    @RequestMapping(value="downLoadMaterilList")
    public void downLoadMaterilList(HttpServletRequest request, HttpServletResponse response){
        String id=request.getParameter("id");
        HSSFWorkbook wb=planService.downLoadMaterilList(id);
        OutputStream out=null;
        try{
            out=response.getOutputStream();
            String fileName = "物料明细.xls";// 文件名
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment; filename="
                    + URLEncoder.encode(fileName, "UTF-8"));
            wb.write(out);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping(value = "electricMaterialSet")
    public String electricMaterialSet(Model model){
        model.addAttribute("types", MaterialUtils.findMaterialType());
        return "modules/yangguang/systemSetting/plan/electricMaterialSet";
    }

    @ResponseBody
    @RequestMapping(value = "electricMaterialSetList")
    public Object electricMaterialSetList(HttpServletRequest request){
        LayuiPage<Record> page = new LayuiPage<>(request);
        Map<String, String> map = getParams(request);
        planService.electricMaterialSetList(page,map);
        return page.renderJson();
    }

    @RequestMapping(value="addElectricMaterialSetPage")
    public String addElectricMaterialSetPage(String id,Model model){
        if (StringUtils.isNotBlank(id)) {
         Record set=planService.getElectricMaterielSetDetail(id);
         model.addAttribute("set",set);
        }
        return "modules/yangguang/systemSetting/plan/addElectricMaterialSetPage";
    }

    @ResponseBody
    @RequestMapping(value="saveElectricMaterialSet")
    public Result<Void> saveElectricMaterialSet(@Valid @RequestBody AddElectricMaterialSet ret,BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return errRet(bindingResult);
        }
        planService.addElectricMaterialSet(ret);
        return Result.ok();
    }

    @ResponseBody
    @RequestMapping(value="deleteElectricMaterialSet")
    public  Result<Void> deleteElectricMaterialSet(HttpServletRequest request){
        String ids=request.getParameter("ids");
        planService.deleteElectricMaterialSet(ids);
        return Result.ok();
    }

    @RequestMapping(value = "toImportElectricMaterialSet")
    public String toImportElectricMaterialSet(){
        return "modules/yangguang/systemSetting/plan/importElectricMaterial";
    }

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

    @ResponseBody
    @RequestMapping(value = "importElectricMaterialSet")
    public JSONObject importElectricMaterialSet(MultipartFile file) throws IOException {
        Map<String, String> params = Maps.newHashMap();
        params.put("fileName", file.getOriginalFilename());
        Map<String, Object> retMap = planService.importElectricMaterialSet(params, file.getInputStream());
        return JSONObject.fromObject(retMap);
    }

    /**
     * 查询电器材料
     */
    @ResponseBody
    @RequestMapping(value = "findAllElectric")
    public Result<List<Record>> findAllElectric() {
        return Result.success(planService.findAllElectric());
    }

    /**
     * 查询逆变器
     */
    @ResponseBody
    @RequestMapping(value = "findInverterSet")
    public Result<List<Record>> findInverterSet(String partnerId) {
        List<Record> records = new ArrayList<>();
        Record info2 = formSetService.getListByCondition("02", partnerId);
        FormSetPageVo vo = info2.get("component1_model");
        if (vo != null && "1".equals(vo.getStatus())){
            records = planService.findAllInverter2();
        }else {
            records = planService.findAllInverter();
        }
        return Result.success(records);
    }
}
