package com.sifang.modules.customer.Service;

import com.jfinal.plugin.activerecord.Record;
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.customer.utils.CheckMustFillUtil;
import com.sifang.modules.flowable.constants.ItemConstants;
import com.sifang.modules.flowable.dao.ItemManageDao;
import com.sifang.modules.flowable.dao.ItemTaskDetailDao;
import com.sifang.modules.flowable.entity.ItemManage;
import com.sifang.modules.flowable.utils.FormUtils;
import com.sifang.modules.platform.utils.PlantformUtils;
import com.sifang.modules.setting.constant.ProcessSetConstants;
import com.sifang.modules.sunshine.SystemSetting.dao.ProjectSettingDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmProjectSetting;
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.service.BaseService;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.dao.FormSetDao;
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.taskdispatch.dao.CrmReviewDispatchDao;
import com.sifang.modules.taskdispatch.service.CrmPriorReviewSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class CustomerEntryOrgFilesService extends BaseService {

    @Autowired
    private CustomerEntryOrgFilesDao orgFilesDao;

    @Autowired
    private FormSetDao formSetDao;

    @Autowired
    ProjectSettingDao projectDao;

    @Autowired
    private CustomerEntryDao entryDao;

    @Autowired
    private CustomerEntrySurveyRecordDao surveyRecordDao;

    @Autowired
    private CustomerEntryTenantDao tenantDao;

    @Autowired
    private PartnerService partnerService;

    @Autowired
    CustomerEntryMsgService msgService;

    @Autowired
    private CustomerEntryService entryService;

    @Autowired
    private TenantYxBankCardDao tenantYxBankCardDao;

    @Autowired
    private ItemManageDao itemManageDao;

    @Autowired
    private ItemTaskDetailDao itemTaskDetailDao;

    @Autowired
    private CrmReviewDispatchDao reviewDispatchDao;

    @Autowired
    private CrmPriorReviewSettingService crmPriorReviewSettingService;

    public CustomerEntryOrgFiles getOneByEntryId(String entryId) {
        return orgFilesDao.findOneByEntryId(entryId);
    }

    /**
     * 档案审核
     */
    @Transactional(rollbackFor = Exception.class)
    public Result auditArchives(AuditArchivesReq req, Operator operator) {
        // 查询档案信息
        CustomerEntryOrgFiles orgFiles = orgFilesDao.get(req.getId());
        // 校验状态
        if (!Objects.equals("1", orgFiles.getStatus())) {
            return Result.fail("审核失败，档案状态已改变");
        }
        CustomerEntry entry = entryDao.get(orgFiles.getEntryId());
        String checkApplyResult = CrmUtils.checkExistApply(entry.getStatus(), entry.getId());
        if (StringUtil.isNotBlank(checkApplyResult)) {
            return Result.fail(checkApplyResult);
        }
        // 调用进件申请
        String str="档案审核通过";
        short type = CustomerEntryConstants.ENTRY_DA_PASS;
        if (Objects.equals("1", req.getType())) {
            // 审核通过
            orgFiles.setStatus("3");
            if (StringUtil.equalsAny(entry.getDesignAuditFlag(), CustomerEntryConstants.DESIGN_AUDIT_FLAG_SJSHTG, CustomerEntryConstants.DESIGN_AUDIT_FLAG_JJSHBH)) {
                //isHistory 历史电站标记：0.否 1.是
                boolean hisFlag = true;
                if ("1".equals(entry.getIsHistory()) && PartnerConstants.PARTNER_ID_GF.equals(entry.getPartnerId())){
                    hisFlag = false;
                }
                if (FormSetUtils.processSetEnable(entry.getPartnerId(), ProcessSetConstants.NODE_KEY_NAME_ZFSH) && hisFlag) {
                    if ((PartnerConstants.PARTNER_ID_YX.equals(entry.getPartnerId())&&!"NEW".equals(entry.getFirstApplyStatus()) && !"APPROVING".equals(entry.getFirstApplyStatus()) && !"APPROVED".equals(entry.getFirstApplyStatus()) && !"CLOSED".equals(entry.getFirstApplyStatus()))
                            ||(PartnerConstants.PARTNER_ID_GF.equals(entry.getPartnerId())&&!"20".equals(entry.getFirstApplyStatus()) &&  !"30".equals(entry.getFirstApplyStatus())&& !"60".equals(entry.getFirstApplyStatus()))
                            ||(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId()) &&  !"FR".equals(entry.getFirstApplyStatus()) && !"FS".equals(entry.getFirstApplyStatus()) && !"FT".equals(entry.getFirstApplyStatus()))
                    ) {
                        CrmTenantYxBankCard card = tenantYxBankCardDao.getByIdCard(entry.getIdCode(), entry.getManagementType(), entry.getPartnerId());
                        Result result = entryService.accessProjectApply(entry, card, operator,null);
                        entry.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_JJSHZ);
                        if (!"200".equals(result.getCode())) {
                            throw new IllegalArgumentException("审核失败，进件同步返回错误信息:" + result.getErrMsg());
                        }
                    }
                } else {
                    // 如果设计审核通过了就走安装流程
                    entry.setStatus(CustomerEntryConstants.ENTRY_STATUS_DAZ);
                    entry.setInstallFlag(CustomerEntryConstants.INSTALL_FLAG_DPG);
                    entry.setFirstApplyStatus("APPROVED");
                    if (PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
                        entry.setFirstApplyStatus("FT");
                    }
                    if (PartnerConstants.PARTNER_ID_GF.equals(entry.getPartnerId())){
                        entry.setFirstApplyStatus("30");
                    }
                    entry.setDesignAuditFlag(CustomerEntryConstants.DESIGN_AUDIT_FLAG_SJSHTG);
//                entry.setApplyStatus(CustomerEntryConstants.APPLY_STATUS_JJTG);
                    entry.setApplyStatus(null);
                }
            }
            entryDao.save(entry);
        } else {
            // 审核不通过
            orgFiles.setStatus("2");
            str="档案审核不通过";
            type = CustomerEntryConstants.ENTRY_DA_REFUSE;
        }
        if (StringUtil.isNotBlank(req.getRemark())) {
            str = str + ";" + req.getRemark();
        }
        orgFiles.setRemark(req.getRemark());
        orgFiles.setAuditTime(new Date());
        orgFiles.setAuditBy(operator.getUserId());
        orgFiles.setAuditor(operator.getUserName());
        msgService.saveCustomerEntryMsg(operator, orgFiles.getEntryId(), type, str,operator.getUserName());
        //生成审核的task
        Date date=new Date();
        String itemStatus="1".equals(req.getType())?ItemConstants.RESULT_OK:ItemConstants.RESULT_BACK;
        ItemManage itemManage= itemManageDao.getItemManagementByEntryId(orgFiles.getEntryId(),FormUtils.ENTRY_STATUS_DASH);
        if (itemManage != null) {
            itemTaskDetailDao.addItemTaskDetail2(FormUtils.ENTRY_STATUS_DASH, orgFiles.getEntryId(), itemManage.getProcessInstanceId(), itemManage.getProcessInstanceId(), itemStatus, date, operator, "档案审核");
            itemManage.setStatus(ItemConstants.ITEM_STATUS_FINISH);
            itemManage.setEndTime(date);
            itemManageDao.save(itemManage);
            reviewDispatchDao.markDispatchFinish(itemManage);
        }
        return Result.ok();
    }

    /**
     * 提交档案
     */
    @Transactional(rollbackFor = Exception.class)
    public Result submitArchives(SubmitArchivesReq req,Operator operator) {
        // 查询电站信息
        CustomerEntry customerEntry = entryDao.get(req.getEntryId());
        if (customerEntry == null) {
            return Result.fail("未查询到电站信息");
        }
        String checkApplyResult = CrmUtils.checkExistApply(customerEntry.getStatus(), customerEntry.getId());
        if (StringUtil.isNotBlank(checkApplyResult)) {
            return Result.fail(checkApplyResult);
        }

        // 判断操作类型是否为 提交
        boolean saveFlag = Objects.equals("2", req.getType());

        if (saveFlag && StringUtil.isBlank(req.getAddress())) {
            return Result.fail("请填写完整的安装地址");
        }

        // 客户类型是否为法人
        boolean frFlag = Objects.equals("2", customerEntry.getTenantType());
        if (!frFlag) {
            if (StringUtil.isBlank(req.getIdCardFront())) {
                return Result.fail("请上传身份证正面");
            }
            if (StringUtil.isBlank(req.getIdCardBack())) {
                return Result.fail("请上传身份证背面");
            }
            customerEntry.setIdCardFront(req.getIdCardFront());
            customerEntry.setIdCardBack(req.getIdCardBack());
            CustomerEntryTenant tenant = tenantDao.get(customerEntry.getTenantId());
            tenant.setIdCardFront(req.getIdCardFront());
            tenant.setIdCardBack(req.getIdCardBack());
            tenant.setBirthdayDate(req.getBirthdayDate());
            tenant.setIcValidityBegin(req.getIcValidityBegin());
            tenant.setIcValidityEnd(req.getIcValidityEnd());
            tenantDao.save(tenant);
        }

        // 查询勘测信息
        CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(customerEntry.getId());
        if (surveyRecord == null) {
            surveyRecord = new CustomerEntrySurveyRecord();
            surveyRecord.setEntryId(customerEntry.getId());
            surveyRecord.setTraderId(customerEntry.getDistributorId());
            surveyRecord.setCreateTime(new Date());
        }
        // 查询档案信息
        CustomerEntryOrgFiles orgFiles = orgFilesDao.findOneByEntryId(customerEntry.getId());
        if (orgFiles == null) {
            return Result.fail("未查询到档案信息");
        }
        boolean tenantFlag = Objects.equals("2", customerEntry.getTenantType());
        if (saveFlag) {
            // 查询项目信息
//            CrmProjectSetting projectSetting = projectDao.get(customerEntry.getProjectId());
            // 获取资方信息
            CrmPartner partner = partnerService.getById(customerEntry.getPartnerId());
            // 校验参数 stage ：05 档案表单设置
            List<Record> checkList = formSetDao.findListByCondition("05", customerEntry.getPartnerId());
            Result result = requiredCheckForOrgFiles(req, checkList, tenantFlag, partner, customerEntry.getAge());
            if (!"200".equals(result.getCode())) {
                return result;
            }
        }
        // 修改电站信息 --->

        // 详细地址
        customerEntry.setAddress(req.getAddress());

        // 银行账号名称
        customerEntry.setBankName(req.getBankName());

        // 银行账号
        customerEntry.setBankCode(req.getBankCode().trim());

        // 联行号
        customerEntry.setTssBankNum(req.getTssBankNum());

        // 开户行
        customerEntry.setTssBankNumName(req.getTssBankNumName());

        // 银行卡照片
        customerEntry.setBankCard(req.getBankCard());

        //紧急联系人
        customerEntry.setExigenceName(req.getExigenceName());

        //紧急联系人手机号
        customerEntry.setExigencePhone(req.getExigencePhone());

        // 个人
        if (!tenantFlag) {
            // 承租类型为 个人 需要修改的信息
            orgFiles.setCreditCertificate(req.getCreditCertificate());

            // 复口本复印件
            customerEntry.setResidenceBooklet(req.getResidenceBooklet());

            // 房产证
            surveyRecord.setHouseOwnership(req.getHouseOwnership());

            //共签人信息
            customerEntry.setBpName(req.getBpName());
            customerEntry.setBpRelation(req.getBpRelation());
            customerEntry.setBpIdCard(req.getBpIdCard());
            customerEntry.setBpMobile(req.getBpMobile());
            customerEntry.setBpCardFront(req.getBpCardFront());
            customerEntry.setBpCardBack(req.getBpCardBack());
            customerEntry.setBpFile(req.getBpFile());
            surveyRecordDao.save(surveyRecord);
        } else {
            // 承租类型为 单位 需要修改的信息

            // 村民代表大会决议书
            orgFiles.setResolutionPaperUrl(req.getResolutionPaperUrl());

            // 村委议事章程
            orgFiles.setYszcUrl(req.getYszcUrl());

            // 对公账户信息
            orgFiles.setAccountInfoUrl(req.getAccountInfoUrl());

            // 产权证明-集体土地使用证
            orgFiles.setOwnershipCertificateUrl(req.getOwnershipCertificateUrl());

            // 产权证明-不动产证书/查册证明/相关确权文件
            orgFiles.setOtherOwnershipCertificateUrl(req.getOtherOwnershipCertificateUrl());
        }
        customerEntry.setBirthdayDate(req.getBirthdayDate());
        customerEntry.setIcValidityBegin(req.getIcValidityBegin());
        customerEntry.setIcValidityEnd(req.getIcValidityEnd());
        entryDao.save(customerEntry);
        if (saveFlag) {
            orgFiles.setStatus("1");
            msgService.saveCustomerEntryMsg(operator, customerEntry.getId(), CustomerEntryConstants.ENTRY_DA, "提交档案",operator.getUserName());
            //创建档案审核的任务
            Date date=new Date();
            String stationName = CrmUtils.getStationName(customerEntry);
            ItemManage itemManage = itemManageDao.addItem(FormUtils.ENTRY_STATUS_DASH,customerEntry.getId(), PlantformUtils.getOrderNumber(),"档案审核("+stationName+"-"+customerEntry.getPowerStationCode()+")-"+DateUtils.formatDate(date,"yyyy-MM-dd HH:mm:ss"),date,operator.getUserName());
            //大代理商优先审核
            String groupName = "档案审核";
            crmPriorReviewSettingService.traderPriorityReview(customerEntry.getCreateTraderId(),itemManage.getId(),groupName);
            //清空档案审核备注
            orgFiles.setRemark("");
        }
        orgFilesDao.save(orgFiles);
        return Result.ok();
    }

    // 提交档案必填校验
    public Result requiredCheckForOrgFiles(SubmitArchivesReq req, List<Record> list, boolean tenantFlag,
                                           CrmPartner partner, Integer age) {
        Result result = new Result();
        result.setCode("205");
        if (tenantFlag) {
            // 村民代表大会决议书 resolution_paper_url
            if (StringUtil.isBlank(req.getResolutionPaperUrl())
                    && CheckMustFillUtil.checkMustFill("resolution_paper_url", list)) {
                result.setErrMsg("村民代表大会决议书为空");
                return result;
            }
            // 村委议事章程 yszc_url
            if (StringUtil.isBlank(req.getYszcUrl())
                    && CheckMustFillUtil.checkMustFill("yszc_url", list)) {
                result.setErrMsg("村委议事章程为空");
                return result;
            }
            // 对公账户信息 account_info_url
            if (StringUtil.isBlank(req.getAccountInfoUrl())
                    && CheckMustFillUtil.checkMustFill("account_info_url", list)) {
                result.setErrMsg("对公账户信息为空");
                return result;
            }
            // 产权证明-集体土地使用证 ownership_certificate_url
            if (StringUtil.isBlank(req.getOwnershipCertificateUrl())
                    && CheckMustFillUtil.checkMustFill("ownership_certificate_url", list)) {
                result.setErrMsg("集体土地使用证为空");
                return result;
            }
            // 产权证明-不动产证书/查册证明/相关确权文件 other_ownership_certificate_url
            if (StringUtil.isBlank(req.getOtherOwnershipCertificateUrl())
                    && CheckMustFillUtil.checkMustFill("other_ownership_certificate_url", list)) {
                result.setErrMsg("不动产证书为空");
                return result;
            }
        } else {
            // 出生日期 birthday_date
            if (Objects.isNull(req.getBirthdayDate())
                    && CheckMustFillUtil.checkMustFill("birthday_date", list)) {
                result.setErrMsg("出生日期为空,请重新上传身份证正面");
                return result;
            }
            // 身份证生效日 ic_validity_begin
            if (Objects.isNull(req.getIcValidityBegin())
                    && CheckMustFillUtil.checkMustFill("ic_validity_begin", list)) {
                result.setErrMsg("身份证生效日为空,请重新上传身份证反面");
                return result;
            }// 身份证到期日 ic_validity_end
            if (Objects.isNull(req.getIcValidityEnd())
                    && CheckMustFillUtil.checkMustFill("ic_validity_end", list)) {
                result.setErrMsg("身份证到期日为空,请重新上传身份证反面");
                return result;
            }
            // 户口本复印件 residence_booklet
            if (StringUtil.isBlank(req.getResidenceBooklet())
                    && CheckMustFillUtil.checkMustFill("residence_booklet", list)) {
                result.setErrMsg("户口本复印件为空");
                return result;
            }
            // 房产证 house_ownership
            if (StringUtil.isBlank(req.getHouseOwnership())
                    && CheckMustFillUtil.checkMustFill("house_ownership", list)) {
                result.setErrMsg("房产证为空");
                return result;
            }
            //信誉凭证
            if (StringUtil.isBlank(req.getCreditCertificate()) && CheckMustFillUtil.checkMustFill("credit_certificate", list)){
                result.setErrMsg("信誉凭证为空");
                return result;
            }
            if (Objects.equals("1", partner.getOverageFlag()) && age >= partner.getNeedSignerAge()) {
                if (StringUtil.isBlank(req.getBpName()) && CheckMustFillUtil.checkMustFill("bp_name", list) ) {
                    result.setErrMsg("共签人名称为空");
                    return result;
                }
                if (StringUtil.isBlank(req.getBpIdCard()) && CheckMustFillUtil.checkMustFill("bp_id_card", list)) {
                    result.setErrMsg("共签人证件号码为空");
                    return result;
                }
                if (StringUtil.isBlank(req.getBpMobile()) && CheckMustFillUtil.checkMustFill("bp_mobile", list)) {
                    result.setErrMsg("共签人手机号为空");
                    return result;
                }
                if (StringUtil.isBlank(req.getBpRelation()) && CheckMustFillUtil.checkMustFill("bp_relation", list)) {
                    result.setErrMsg("共签人与业主关系为空");
                    return result;
                }
                if (StringUtil.isBlank(req.getBpCardFront()) && CheckMustFillUtil.checkMustFill("bp_card_front", list))  {
                    result.setErrMsg("共签人身份证正面为空");
                    return result;
                }
                if (StringUtil.isBlank(req.getBpCardBack()) && CheckMustFillUtil.checkMustFill("bp_card_back", list)) {
                    result.setErrMsg("共签人身份证反面为空");
                    return result;
                }
                if (StringUtil.isBlank(req.getBpFile()) && CheckMustFillUtil.checkMustFill("bp_file", list))  {
                    result.setErrMsg("共签人子女证明材料为空");
                    return result;
                }
            }
        }


        // 银行账户名称 bank_name
        if (StringUtil.isBlank(req.getBankName())
                && CheckMustFillUtil.checkMustFill("bank_name", list)) {
            result.setErrMsg("银行账户名称为空");
            return result;
        }
        // 银行账号 bank_code
        if (StringUtil.isBlank(req.getBankCode())
                && CheckMustFillUtil.checkMustFill("bank_code", list)) {
            result.setErrMsg("银行账号为空");
            return result;
        }
        // 开户行 tss_bank_num_name
        if (StringUtil.isBlank(req.getTssBankNumName())
                && CheckMustFillUtil.checkMustFill("tss_bank_num_name", list)) {
            result.setErrMsg("开户行为空");
            return result;
        }
        // 银行卡照片 bank_card
        if (StringUtil.isBlank(req.getBankCard())
                && CheckMustFillUtil.checkMustFill("bank_card", list)) {
            result.setErrMsg("银行卡照片为空");
            return result;
        }
        //紧急联系人
        if (StringUtil.isBlank(req.getExigenceName())
                && CheckMustFillUtil.checkMustFill("exigence_name", list)) {
            result.setErrMsg("紧急联系人为空");
            return result;
        }
        //紧急联系人电话
        if (StringUtil.isBlank(req.getExigencePhone())
                && CheckMustFillUtil.checkMustFill("exigence_phone", list)) {
            result.setErrMsg("紧急联系人电话为空");
            return result;
        }
        return Result.ok();
    }

    @Transactional(rollbackFor = Exception.class)
    public Result auditArchivesTemp(String id ,String remark) {
        // 查询档案信息
        CustomerEntryOrgFiles orgFiles = orgFilesDao.get(id);
        orgFiles.setRemark(remark);
        orgFilesDao.save(orgFiles);
        return Result.ok();
    }
}
