package com.sifang.modules.customer.controller;


import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.changes.dao.CustomerEntrySupplementDetailDao;
import com.sifang.modules.changes.entity.CustomerEntrySupplementDetail;
import com.sifang.modules.customer.Service.CustomerEntryExtraService;
import com.sifang.modules.customer.Service.CustomerEntryService;
import com.sifang.modules.customer.Service.OperatingLeaseService;
import com.sifang.modules.customer.constant.CustomerEntryConstants;
import com.sifang.modules.customer.constant.Nationals;
import com.sifang.modules.customer.dao.*;
import com.sifang.modules.customer.entity.*;
import com.sifang.modules.customer.form.AddIncomingApplication;
import com.sifang.modules.platform.service.AddressService;
import com.sifang.modules.platform.utils.AddressUtils;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
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.web.BaseExceptionController;
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.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;

@Controller
@RequestMapping(value = "${adminPath}/customerEntryExtra")
public class CustomerEntryExtraController extends BaseExceptionController {

    private static final Logger logger = LoggerFactory.getLogger(CustomerEntryExtraController.class);

    @Autowired
    AddressService addressService;

    @Autowired
    CustomerEntryExtraService customerEntryExtraService;

    @Autowired
    CustomerEntryService customerService;

    @Autowired
    private CustomerEntryOrgFilesDao orgFilesDao;

    @Autowired
    private CrmCustomerIncomingApplicationBasicDao basicDao;

    @Autowired
    private CrmCustomerIncomingApplicationPerInfoDao perInfoDao;

    @Autowired
    private CrmCustomerIncomingApplicationRetailPayInfoDao retailPayInfoDao;

    @Autowired
    private CrmCustomerIncomingApplicationDao applicationDao;

    @Autowired
    private CrmCustomerIncomingApplicationLeaseItemDao equipInfoNormalDao;

    @Autowired
    private CrmCustomerIncomingApplicationInsuranceDao insuranceDao;

    @Autowired
    OperatingLeaseService operatingLeaseService;

    @Autowired
    private CustomerEntrySupplementDetailDao supplementDetailDao;

    @RequestMapping(value = "preInputEntry")
    public String preInputEntry(HttpServletRequest request, Model model){
        String entryId=request.getParameter("id");
        model.addAttribute("entryId",entryId);
        //地址信息
        List<Record> pros = AddressUtils.getProvincesList();
        model.addAttribute("province", pros);

        CustomerEntry entry = customerService.getById(entryId);
        if(StringUtil.isNotBlank(entry.getApplyStatus())){

            CrmCustomerIncomingApplication application=applicationDao.getByEntryId(entryId);
            model.addAttribute("application",application);
            CrmCustomerIncomingApplicationBasic basic=basicDao.getByApplicationId(application.getId());
            model.addAttribute("basic",basic);
            CrmCustomerIncomingApplicationPerInfo perInfo=perInfoDao.getByApplicationId(application.getId());
            model.addAttribute("perInfo",perInfo);
            List<CrmCustomerIncomingApplicationInsurance> insurances = insuranceDao.getByEntryIds(entryId);
            model.addAttribute("insurances",insurances);

            CrmCustomerIncomingApplicationLeaseItem leaseItem=equipInfoNormalDao.getByEntryId(entryId);
            model.addAttribute("leaseItem",leaseItem);

            List<Record> cityList=AddressUtils.getCityByProName(leaseItem.getElectricProvince());
            model.addAttribute("city",cityList);

            List<Record> areaList= AddressUtils.getAreaByCityName(leaseItem.getElectricCity());
            model.addAttribute("area",areaList);
        }
        model.addAttribute("entry", entry);
        model.addAttribute("nationals", Nationals.getNationalList());
        return "modules/yangguang/customer/entry/extra/inputEntryPage";
    }

    @RequestMapping(value = "supplyInputEntry")
    public String supplyInputEntry(HttpServletRequest request, Model model){
        String entryId=request.getParameter("id");
        model.addAttribute("entryId",entryId);
        //地址信息
        List<Record> pros = AddressUtils.getProvincesList();
        model.addAttribute("province", pros);

        CustomerEntry entry = customerService.getById(entryId);
        if(StringUtil.isNotBlank(entry.getApplyStatus()) ){

            CrmCustomerIncomingApplication application=applicationDao.getByEntryId(entryId);
            model.addAttribute("application",application);

            CrmCustomerIncomingApplicationRetailPayInfo retailPayInfo=retailPayInfoDao.getByApplicationId(application.getId());
            model.addAttribute("retailPayInfo",retailPayInfo);
            CrmCustomerIncomingApplicationLeaseItem equipInfoNormal=equipInfoNormalDao.getByEntryId(entryId);
            model.addAttribute("equipInfoNormal",equipInfoNormal);
            CrmCustomerIncomingApplicationBasic basic=basicDao.getByApplicationId(application.getId());
            model.addAttribute("basic",basic);
        }

        model.addAttribute("entry", entry);
        model.addAttribute("nationals", Nationals.getNationalList());
        return "modules/yangguang/customer/entry/extra/supplyInputEntryPage";
    }

    // 进件申请
    @ResponseBody
    @RequestMapping(value = "addIncomingApplication")
    public Result addIncomingApplication(@RequestBody AddIncomingApplication addIncomingApplication){
        logger.info(">>>>>>>>>>>>tempSave :{}",addIncomingApplication);
        User user = UserUtils.getUser();
        try {
             Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
             customerEntryExtraService.addIncomingApplication(addIncomingApplication,operator);
        }catch(IllegalArgumentException i){
            return Result.fail(i.getMessage());
        }catch(Exception e){
            e.printStackTrace();
            logger.error(">>>>>>>>>>>>>>>>>>>addIncomingApplication  e:{}",e);
            return Result.fail("内部错误!");
        }
        return Result.ok();
    }

    @RequestMapping(value = "examineInputEntryPage")
    public String examineInputEntryPage(HttpServletRequest request, Model model){
        String entryId=request.getParameter("id");
        model.addAttribute("entryId",entryId);
        //地址信息
        List<Record> pros = AddressUtils.getProvincesList();
        model.addAttribute("province", pros);

        CustomerEntry entry = customerService.getById(entryId);
        CrmCustomerIncomingApplication application=applicationDao.getByEntryId(entryId);
        model.addAttribute("application",application);

        logger.info(">>>>>>>>>>>>>>>>>> examineInputEntryPage application:{}",application);

        CrmCustomerIncomingApplicationBasic basic=basicDao.getByApplicationId(application.getId());
        model.addAttribute("basic",basic);
        CrmCustomerIncomingApplicationPerInfo perInfo=perInfoDao.getByApplicationId(application.getId());
        model.addAttribute("perInfo",perInfo);
        if(perInfo!=null && StringUtil.isNotBlank(perInfo.getMailingAddr())){
            String[] arr=perInfo.getMailingAddr().split(",");
            model.addAttribute("mPro",arr[0]);
            model.addAttribute("mCity",arr[1]);
            model.addAttribute("mArea",arr[2]);
            Record record=AddressUtils.getProCityArea(arr[0],arr[1],arr[2]);

            if(record !=null){
                model.addAttribute("province",record.get("ProvinceName"));
                model.addAttribute("city",record.get("CityName"));
                model.addAttribute("area",record.get("DistrictName"));
            }
        }
        CrmCustomerIncomingApplicationRetailPayInfo retailPayInfo=retailPayInfoDao.getByApplicationId(application.getId());
        model.addAttribute("retailPayInfo",retailPayInfo);
        CrmCustomerIncomingApplicationLeaseItem equipInfoNormal=equipInfoNormalDao.getByEntryId(entryId);
        model.addAttribute("equipInfoNormal",equipInfoNormal);
        model.addAttribute("nationals", Nationals.getNationalList());
        return "modules/yangguang/customer/entry/extra/examineInputEntryPage";
    }

    /**
     *   审核进件申请
     * @param entryId
     * @param result   1 审核通过  2 审核不通过
     * @param failReason  审核不通过原因
     */
    @ResponseBody
    @RequestMapping(value = "examineIncomingApplication")
    public Result examineIncomingApplication(String entryId,String result,String failReason,String originalAssetValue,String equipValue,String financingAmount,String reservedFieldFive,String netOriginalAssetValue){
        logger.info(">>>>>>>>>>>>examineIncomingApplication :{}",entryId);
        User user = UserUtils.getUser();
        if("2".equals(result) && StringUtil.isBlank(failReason)){
            return Result.fail("请输入审核不通过原因!");
        }
        try{
            Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
            customerEntryExtraService.examineIncomingApplication(entryId,operator,result,failReason,originalAssetValue,equipValue,financingAmount,reservedFieldFive,netOriginalAssetValue);
        }catch (IllegalArgumentException e){
            e.printStackTrace();
            logger.info(">>>>>>>>>>>examineIncomingApplication >IllegalArgumentException  e:{} ",e);
            return Result.fail(e.getMessage());
        }
        catch (Exception e){
            e.printStackTrace();
            logger.info(">>>>>>>>>>>>examineIncomingApplication  e:{} ",e);
            return Result.fail("内部错误!");
        }
        return Result.ok();
    }



    //第二次进件申请（待并网的时候)
    @ResponseBody
    @RequestMapping(value = "supplyIncomingApplication")
    public Result supplyIncomingApplication(@RequestBody AddIncomingApplication addIncomingApplication){
        logger.info(">>>>>>>>>>>>supplyIncomingApplication :{}",addIncomingApplication);
        User user = UserUtils.getUser();
        try {
            Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
            customerEntryExtraService.supplyIncomingApplication(addIncomingApplication,operator);
        }catch(IllegalArgumentException i){
            return Result.fail(i.getMessage());
        }catch(Exception e){
            e.printStackTrace();
            logger.error(">>>>>>>>>>>>>>>>>>>supplyIncomingApplication  e:{}",e);
            return Result.fail("内部错误!");
        }
        return Result.ok();
    }

    @RequestMapping(value = "supplyTwoInputEntry")
    public String supplyTwoInputEntry(HttpServletRequest request, Model model){
        String entryId=request.getParameter("id");
        model.addAttribute("entryId",entryId);
        //地址信息
        List<Record> pros = AddressUtils.getProvincesList();
        model.addAttribute("province", pros);

        CustomerEntry entry = customerService.getById(entryId);
        if(StringUtil.isNotBlank(entry.getApplyStatus()) ){

            CrmCustomerIncomingApplication application=applicationDao.getByEntryId(entryId);
            model.addAttribute("application",application);
            CrmCustomerIncomingApplicationRetailPayInfo retailPayInfo=retailPayInfoDao.getByApplicationId(application.getId());
            model.addAttribute("retailPayInfo",retailPayInfo);
            CrmCustomerIncomingApplicationLeaseItem equipInfoNormal=equipInfoNormalDao.getByEntryId(entryId);
            model.addAttribute("equipInfoNormal",equipInfoNormal);
        }
        model.addAttribute("entry", entry);
        model.addAttribute("nationals", Nationals.getNationalList());
        return "modules/yangguang/customer/entry/extra/exaTwoInputEntryPage";
    }

    /**
     *   审核第二次进件申请
     * @param entryId
     * @param result   1 审核通过  2 审核不通过
     * @param failReason  审核不通过原因
     */
    @ResponseBody
    @RequestMapping(value = "examineNotApplication")
    public Result examineNotApplication(String entryId,String result,String failReason,String originalAssetValue,String netAssetValue,String netOriginalAssetValue){
        logger.info(">>>>>>>>>>>>String failReason :{}",entryId);
        User user = UserUtils.getUser();
        if("2".equals(result) && StringUtil.isBlank(failReason)){
            return Result.fail("请输入审核不通过原因!");
        }
        try{
            Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
            if("1".equals(result)){
                customerEntryExtraService.approved(entryId,operator,originalAssetValue,netAssetValue,netOriginalAssetValue);
            }else if("2".equals(result)){
                customerEntryExtraService.approvedNot(entryId,operator,failReason);
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.info(">>>>>>>>>>>>examineIncomingApplication  e:{} ",e);
            return Result.fail("内部错误!");
        }
        return Result.ok();
    }


    @RequestMapping(value = "lookInputEntryStatus")
    public String lookInputEntryStatus(HttpServletRequest request,Model model){
        String entryId=request.getParameter("id");
        String type=request.getParameter("type");
        CrmCustomerIncomingApplication application;
        if("1".equals(type)){
            application =applicationDao.getByEntryId(entryId);
        }else{
//            application=operatingLeaseService.incomingParts(entryId);
        }
//        model.addAttribute("application",application);
        return "modules/yangguang/customer/entry/extra/lookInputStatusPage";
    }

    @RequestMapping(value = "findResult")
    public String findResult(HttpServletRequest request,Model model){
        String entryId=request.getParameter("id");
        try {
            Map<String, String> resultMap = customerService.findPreauditStatus(entryId);
            model.addAttribute("resultMap",resultMap);
            model.addAttribute("code","200");
        }catch (Exception e){
            logger.error(">>>findResult e:{}",e);
            model.addAttribute("msg",e.getMessage());
            model.addAttribute("code","500");
        }
        return "modules/yangguang/customer/entry/extra/findResultPage";
    }

    @RequestMapping(value = "preInputEntrySec")
    public String preInputEntrySec(HttpServletRequest request, Model model){
        String entryId=request.getParameter("id");
        model.addAttribute("entryId",entryId);
        CustomerEntry entry = customerService.getById(entryId);
        CrmCustomerIncomingApplicationInsurance insurance = insuranceDao.getByEntryId(entryId);
        model.addAttribute("insurance",insurance);
        model.addAttribute("entry", entry);
        return "modules/yangguang/customer/entry/extra/inputEntryPageSec";
    }

    @ResponseBody
    @RequestMapping(value = "addIncomingApplicationSec")
    public Result addIncomingApplicationSec(@RequestBody AddIncomingApplication addIncomingApplication){
        logger.info(">>>>>>>>>>>>tempSave :{}",addIncomingApplication);
        User user = UserUtils.getUser();
        try {
            Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
           // customerEntryExtraService.addIncomingApplicationSec(addIncomingApplication,operator);
        }catch(IllegalArgumentException i){
            return Result.fail(i.getMessage());
        }catch (BusinessException e){
            return Result.fail("501",e.getMessage());
        }catch(Exception e){
            logger.error(">>>>>>>>>>>>>>>>>>>addIncomingApplicationSec  e:{}",e);
            return Result.fail("内部错误!");
        }
        return Result.ok();
    }

    @RequestMapping("/toUploadFilePage")
    public String toUploadFilePage(HttpServletRequest request,Model model) {

        return "modules/yangguang/customer/entry/uploadFilePage";
    }

    @ResponseBody
    @RequestMapping(value = "accessProjectApply")
    public Object accessProjectApply(HttpServletRequest request) {
        String fileType = request.getParameter("fileType");
        String powerStationCode = request.getParameter("powerStationCode");
        CustomerEntry entry = customerService.findCustomerEntryById(powerStationCode);
        if (entry == null || StringUtil.isBlank(entry.getId())) {
            return Result.fail("未查询到该电站");
        }
        CrmCustomerIncomingApplication application=applicationDao.getByEntryId(entry.getId());
        try {
            if ("1".equals(fileType)) {
                CustomerEntryOrgFiles files = null;
                if (!"1".equals(entry.getTenantType())) {
                    files = orgFilesDao.findOneByEntryId(entry.getId());
                }
                return customerService.updateIncomingApplicationFile(entry, files,application.getPartnersContractNumber());
            } else if ("2".equals(fileType)) {
                return customerService.updateSecoundFile(entry,application.getPartnersContractNumber());
            } else if ("3".equals(fileType)) {
                //查询有没有变更记录
                CustomerEntrySupplementDetail changeRecordDetail=supplementDetailDao.getLatestChangeRecordDetail(entry.getId());
                CrmCustomerIncomingApplicationInsurance insurance = insuranceDao.getByEntryId(entry.getId());
                return customerEntryExtraService.updateThirdFile(entry,insurance,application.getPartnersContractNumber(),changeRecordDetail);
            } else if ("4".equals(fileType)) {
//                return customerService.powerSellFilePush(entry);
            } else if ("5".equals(fileType)) {
                return customerService.updateAuditFile(entry);
            }
            return Result.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("失败! ");
        }
    }
}
