package com.yn.bftl.thirdparty.modules.contract.service.impl;

import com.qiyuesuo.sdk.v2.bean.TemplateParam;
import com.yn.bftl.common.modules.company.entity.BrandAuthorization;
import com.yn.bftl.common.modules.company.entity.Company;
import com.yn.bftl.common.modules.company.entity.ContractLock;
import com.yn.bftl.common.modules.company.enums.CompanyType;
import com.yn.bftl.common.modules.company.enums.RelationType;
import com.yn.bftl.common.modules.relation.entity.CompanyRelation;
import com.yn.bftl.common.modules.relation.entity.CrmContract;
import com.yn.bftl.common.modules.relation.entity.CrmContractItem;
import com.yn.bftl.common.modules.relation.entity.SMArchives;
import com.yn.bftl.thirdparty.common.repository.*;
import com.yn.bftl.thirdparty.common.util.NumberToCN;
import com.yn.bftl.thirdparty.common.util.SpringContextHolder;
import com.yn.bftl.thirdparty.modules.contract.vo.LoadInfo;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author chendehuihuo
 * @date 2022/8/25 11:10
 */
@Component
public class ContractLockParams {

    @Resource
    private CompanyRelationRepository companyRelationRepository;
    @Resource
    private SMArchivesRepository smArchivesRepository;
    @Resource
    private BrandAuthorizationRepository brandAuthorizationRepository;

    public void toSupplymarketing(LoadInfo loadInfo, List<TemplateParam> params) {
        // 销售合同参数
        CompanyRelation companyRelation = loadInfo.getItem().getCompanyRelation();
        CrmContract crmContract = loadInfo.getItem().getCrmContract();

        // 设置甲乙方参数
        setPartyParams(params, loadInfo);

        SMArchives smArchives = smArchivesRepository.findFirstByCompanyRelation(companyRelation);
        BigDecimal cashDeposit = BigDecimal.ZERO;;
        params.add(new TemplateParam("保证金", cashDeposit.toString()));
        params.add(new TemplateParam("保证金大写", NumberToCN.numberToCn(cashDeposit)));

        LocalDateTime timeFrom = crmContract.getTimeFrom();
        LocalDateTime timeTo = crmContract.getTimeTo();

        // float daysDiff = (float) ChronoUnit.DAYS.between(timeFrom, timeTo) / (float) 365;

        // params.add(new TemplateParam("协议期限", String.format("%.2f", daysDiff)));
        params.add(new TemplateParam("协议期限开始年", String.valueOf(timeFrom.getYear())));
        // params.add(new TemplateParam("协议期限开始月", String.valueOf(timeFrom.getMonthValue())));
        // params.add(new TemplateParam("协议期限开始日", String.valueOf(timeFrom.getDayOfMonth())));
        params.add(new TemplateParam("协议期限结束年", String.valueOf(timeTo.getYear())));
        // params.add(new TemplateParam("协议期限结束月", String.valueOf(timeTo.getMonthValue())));
        // params.add(new TemplateParam("协议期限结束日", String.valueOf(timeTo.getDayOfMonth())));

        // 销售品牌
        params.add(new TemplateParam("晚安", "√"));
        params.add(new TemplateParam("晚安慢波", ""));
        params.add(new TemplateParam("其他", ""));
        params.add(new TemplateParam("其他品牌", ""));
        // 销售区域
        Company partyB = companyRelation.getPartyB();
        params.add(new TemplateParam("销售区域", mergeArea(partyB)));
    }

    public void toSettledService(LoadInfo loadInfo, List<TemplateParam> params) {
        // 入驻合同参数
        Company partyB = loadInfo.getItem().getCompanyRelation().getPartyB();
        CrmContract crmContract = loadInfo.getItem().getCrmContract();

        setPartyBParams(params, partyB);

        LocalDateTime timeFrom = crmContract.getTimeFrom();
        LocalDateTime timeTo = crmContract.getTimeTo();

        params.add(new TemplateParam("入驻有效期限开始年", String.valueOf(timeFrom.getYear())));
        // params.add(new TemplateParam("入驻有效期限开始月", String.valueOf(timeFrom.getMonthValue())));
        // params.add(new TemplateParam("入驻有效期限开始日", String.valueOf(timeFrom.getDayOfMonth())));
        params.add(new TemplateParam("入驻有效期限结束年", String.valueOf(timeTo.getYear())));
        // params.add(new TemplateParam("入驻有效期限结束月", String.valueOf(timeTo.getMonthValue())));
        // params.add(new TemplateParam("入驻有效期限结束日", String.valueOf(timeTo.getDayOfMonth())));

        // BigDecimal margin = partyB.getMargin();
        // if (margin == null) {
        //     margin = BigDecimal.ZERO;
        // }
        // params.add(new TemplateParam("保证金", margin.toString()));
        // params.add(new TemplateParam("保证金人民币大写", NumberToCN.numberToCn(margin)));

        params.add(new TemplateParam("平台服务费百分比",
            String.valueOf(partyB.getPlatformServiceFee().multiply(BigDecimal.valueOf(100)))));
    }

    /**
     * 策划服务合同参数
     *
     * @param loadInfo
     * @param params
     */
    public void toDeviseService(LoadInfo loadInfo, List<TemplateParam> params) {
        CrmContractItem item = loadInfo.getItem();
        Company partyA = item.getCompanyRelation().getPartyA();
        Company partyB = item.getCompanyRelation().getPartyB();
        
        // 设置甲乙方参数
        setPartyParams(params, loadInfo);
        // 设置合作期限参数
        setDeadlineParams(params, item.getCrmContract());
        // 设置交易额百分比参数
        setServiceFeeParam(params, partyA, partyB, loadInfo.getItem().getCrmContract().getRelationType());
    }

    /**
     * 品牌服务合同参数
     *
     * @param loadInfo
     * @param params
     */
    public void toBrandService(LoadInfo loadInfo, List<TemplateParam> params) {
        CrmContractItem item = loadInfo.getItem();
        Company partyA = item.getCompanyRelation().getPartyA();
        Company partyB = item.getCompanyRelation().getPartyB();

        // 设置甲乙方参数
        setPartyParams(params, loadInfo);
        // 设置合作期限参数
        setDeadlineParams(params, item.getCrmContract());
        // 设置交易额百分比参数
        setServiceFeeParam(params, partyA, partyB, loadInfo.getItem().getCrmContract().getRelationType());
        // 设置经销区域参数
        params.add(new TemplateParam("经销区域", mergeArea(partyB)));
    }

    /**
     * 品牌授权合同参数
     *
     * @param loadInfo
     * @param params
     */
    public void toBrandAuthorization(LoadInfo loadInfo, List<TemplateParam> params) {
        CrmContractItem item = loadInfo.getItem();
        Company partyA = item.getCompanyRelation().getPartyA();
        Company partyB = item.getCompanyRelation().getPartyB();

        setPartyAParams(params, partyA);
        setPartyBParams(params, partyB);

        // 许可品牌
        params.add(new TemplateParam("晚安品牌", "√"));
        params.add(new TemplateParam("慢波品牌", ""));
        params.add(new TemplateParam("其他品牌", ""));
        params.add(new TemplateParam("其他描述", ""));
        // 许可商标
        params.add(new TemplateParam("晚安商标", "√"));
        params.add(new TemplateParam("其他商标", ""));

        // 设置许可期限参数
        setDeadlineParams(params, item.getCrmContract());
        // 设置交易额百分比参数
        BrandAuthorization brandAuthorization = brandAuthorizationRepository.findByPartyAAndPartyB(partyA, partyB);
        if (brandAuthorization == null) {
            params.add(new TemplateParam("交易额百分比", "0.00"));
        } else {
            if (brandAuthorization.getBrandAuthorRization().compareTo(BigDecimal.ZERO) == 0) {
                params.add(new TemplateParam("交易额百分比",
                        String.valueOf(brandAuthorization.getBrand().getBrandAuthorRization().multiply(BigDecimal.valueOf(100)))));
            } else {
                params.add(new TemplateParam("交易额百分比",
                        String.valueOf(brandAuthorization.getBrandAuthorRization().multiply(BigDecimal.valueOf(100)))));
            }
        }
    }

    /**
     * 设置甲乙方参数
     *
     * @param params
     * @param loadInfo
     */
    private void setPartyParams(List<TemplateParam> params, LoadInfo loadInfo) {
        Company partyA = loadInfo.getItem().getCompanyRelation().getPartyA();
        Company partyB = loadInfo.getItem().getCompanyRelation().getPartyB();
        ContractLock contractLock = SpringContextHolder.getBean(ContractLockRepository.class).findFirstByCompanyId(partyB.getId());

        setPartyAParams(params, partyA);
        if (CompanyType.COMPANY.equals(contractLock.getAuthType())) {
            params.add(new TemplateParam("乙方", partyB.getServiceAccountAuth().getName()));
            params.add(new TemplateParam("乙方法定代表人", partyB.getServiceAccountAuth().getNameOfLegalPerson()));
        } else {
            params.add(new TemplateParam("乙方", partyB.getServiceAccountAuth().getPersonalName()));
            params.add(new TemplateParam("乙方法定代表人", partyB.getServiceAccountAuth().getPersonalName()));
        }
        params.add(new TemplateParam("乙方注册地址", partyB.getRegisterAddress()));
        params.add(new TemplateParam("乙方身份证号码", partyB.getIdentityCard()));
        // params.add(new TemplateParam("乙方通讯地址", mergeAddress(partyB)));
        params.add(new TemplateParam("乙方通讯地址", partyB.getOfficeAddress()));
        params.add(new TemplateParam("乙方联系电话", partyB.getContactPhone()));
    }

    /**
     * 设置甲方参数
     *
     * @param params
     * @param partyA
     */
    private void setPartyAParams(List<TemplateParam> params, Company partyA) {
        params.add(new TemplateParam("甲方", partyA.getServiceAccountAuth().getName()));
        // 办公地址在APP中就是详细地址
        params.add(new TemplateParam("甲方住所地", mergeAddress(partyA)));
        params.add(new TemplateParam("甲方统一社会信用代码", partyA.getServiceAccountAuth().getUnifiedSocialCreditCode()));
        params.add(new TemplateParam("甲方电话", partyA.getContactPhone()));
    }

    /**
     * 设置乙方参数
     *
     * @param params
     * @param partyB
     */
    private void setPartyBParams(List<TemplateParam> params, Company partyB) {
        ContractLock contractLock = SpringContextHolder.getBean(ContractLockRepository.class).findFirstByCompanyId(partyB.getId());
        if (CompanyType.COMPANY.equals(contractLock.getAuthType())) {
            params.add(new TemplateParam("乙方", partyB.getServiceAccountAuth().getName()));
            params.add(new TemplateParam("乙方法定代表人", partyB.getServiceAccountAuth().getNameOfLegalPerson()));
            params.add(new TemplateParam("乙方统一社会信用代码", partyB.getServiceAccountAuth().getUnifiedSocialCreditCode()));
        } else {
            params.add(new TemplateParam("乙方", partyB.getServiceAccountAuth().getPersonalName()));
            params.add(new TemplateParam("乙方法定代表人", partyB.getServiceAccountAuth().getPersonalName()));
            params.add(new TemplateParam("乙方统一社会信用代码", partyB.getTaxpayerIdentificationNumber()));
        }
        params.add(new TemplateParam("乙方住所地", mergeAddress(partyB)));
        params.add(new TemplateParam("乙方联系人", partyB.getContactName()));
        params.add(new TemplateParam("乙方联系电话", partyB.getContactPhone()));
    }

    /**
     * 设置合作期限参数
     * 
     * @param params
     * @param crmContract
     */
    private void setDeadlineParams(List<TemplateParam> params, CrmContract crmContract) {
        LocalDateTime timeFrom = crmContract.getTimeFrom();
        LocalDateTime timeTo = crmContract.getTimeTo();

        params.add(new TemplateParam("合作期限开始年", String.valueOf(timeFrom.getYear())));
        params.add(new TemplateParam("合作期限开始月", String.valueOf(timeFrom.getMonthValue())));
        params.add(new TemplateParam("合作期限开始日", String.valueOf(timeFrom.getDayOfMonth())));
        params.add(new TemplateParam("合作期限结束年", String.valueOf(timeTo.getYear())));
        params.add(new TemplateParam("合作期限结束月", String.valueOf(timeTo.getMonthValue())));
        params.add(new TemplateParam("合作期限结束日", String.valueOf(timeTo.getDayOfMonth())));
    }

    /**
     * 设置服务费参数
     *  @param params
     * @param partyA
     * @param partyB
     * @param relationType
     */
    private void setServiceFeeParam(List<TemplateParam> params, Company partyA, Company partyB, RelationType relationType) {
        CompanyRelation companyRelation = companyRelationRepository
            .findFirstByPartyAAndPartyBAndType(partyA, partyB, relationType);
        params.add(new TemplateParam("交易额百分比",
            String.valueOf(companyRelation.getServiceFee().multiply(BigDecimal.valueOf(100)))));
    }

    /**
     * 合并地址
     *
     * @param company
     * @return
     */
    private String mergeAddress(Company company) {
        String detailAddress = company.getOfficeAddress();
        if (company.getCity() == null || !StringUtils.hasText(company.getCity().getName())) {
            return detailAddress;
        } else {
            String temp = company.getProvince().getName() + company.getCity().getName();
            if (StringUtils.hasText(company.getCity().getName())) {
                detailAddress = detailAddress.replaceAll(company.getCity().getName(), "");
            }
            if (StringUtils.hasText(company.getProvince().getName())) {
                detailAddress = detailAddress.replaceAll(company.getProvince().getName(), "");
            }
            if (company.getArea() != null && StringUtils.hasText(company.getArea().getName())) {
                detailAddress = detailAddress.replaceAll(company.getArea().getName(), "");
                temp += company.getArea().getName();
                if (company.getStreet() != null && StringUtils.hasText(company.getStreet().getName())) {
                    detailAddress = detailAddress.replaceAll(company.getStreet().getName(), "");
                    temp += company.getStreet().getName();
                }
            }
            return temp + detailAddress;
        }
    }

    /**
     * 合并区域
     *
     * @param partyB
     * @return
     */
    private static String mergeArea(Company partyB) {
        String addr;
        if (partyB.getCity() == null || !StringUtils.hasText(partyB.getCity().getName())) {
            addr = partyB.getOfficeAddress();
        } else {
            addr = partyB.getProvince().getName() + partyB.getCity().getName();
            if (partyB.getArea() != null && StringUtils.hasText(partyB.getArea().getName())) {
                addr += partyB.getArea().getName();
                if (partyB.getStreet() != null && StringUtils.hasText(partyB.getStreet().getName())) {
                    addr += partyB.getStreet().getName();
                }
            }
        }
        return addr;
    }
}
