package com.sifang.modules.customer.Service;

import com.google.common.collect.Lists;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.contract.dao.TraderContractTemplateDao;
import com.sifang.modules.contract.entity.TraderContractTemplate;
import com.sifang.modules.customer.constant.CustomerEntryConstants;
import com.sifang.modules.customer.dao.ContractManagementDao;
import com.sifang.modules.customer.dao.CustomerEntryDao;
import com.sifang.modules.customer.entity.CrmCustomerContractManagement;
import com.sifang.modules.customer.entity.CustomerEntry;
import com.sifang.modules.esign.cn.tsign.hz.exception.EsignDemoException;
import com.sifang.modules.esign.constants.ESignConstants;
import com.sifang.modules.esign.service.ESignFileService;
import com.sifang.modules.esign.service.ESignSignService;
import com.sifang.modules.esign.utils.BeanUtils;

import com.sifang.modules.esign.utils.ConvertUpMoney;
import com.sifang.modules.esign.vo.ComponentVo;
import com.sifang.modules.esign.vo.FileVo;
import com.sifang.modules.platform.utils.PlantformUtils;
import com.sifang.modules.sunshine.SystemSetting.dao.ProjectCompanyDao;
import com.sifang.modules.sunshine.SystemSetting.dao.ProjectSettingDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmProjectSetting;
import com.sifang.modules.sunshine.SystemSetting.entity.ProjectCompanySettings;
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.service.BaseService;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.entity.Operator;
import com.sifang.modules.sys.util.SqlBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class SignContractService extends BaseService {

    @Autowired
    private CustomerEntryDao customerDao;

    @Autowired
    ProjectSettingDao projectDao;

    @Autowired
    private ProjectCompanyDao projectCompanySettingsDao;

    @Autowired
    private TraderContractTemplateDao templateDao;

    @Autowired
    private ContractManagementDao contractManagementDao;

    @Autowired
    CustomerEntryMsgService msgService;



    @Transactional(rollbackFor = Exception.class)
    public void inviteSign(String id,Operator operator) {
        Date now = new Date();
        // 获取电站信息
        CustomerEntry entry = customerDao.get(id);
        if(StringUtil.equalsAny(entry.getSignStatus(), CustomerEntryConstants.SIGN_STATUS_TENANT_ING,
                CustomerEntryConstants.SIGN_STATUS_COMPANY_ING,CustomerEntryConstants.SIGN_STATUS_COMPLETED)){
            throw new BusinessException("该电站已邀请了签约合同，请勿重复签约!");
        }
        if(StringUtil.isBlank(entry.getTenantName()) || StringUtil.isBlank(entry.getMobile())){
            throw new BusinessException("农户姓名和联系方式不能为空!");
        }
        if(!"0".equals(entry.getSignStatus())){
            throw new BusinessException("该电站已邀请了签约合同，请勿重复签约!");
        }
        // 查询项目信息
        CrmProjectSetting projectSetting = projectDao.get(entry.getProjectId());
        // 查询项目公司信息
        ProjectCompanySettings companySettings = projectCompanySettingsDao.get(projectSetting.getProjectCompanyId());
        if(companySettings==null){
            throw new BusinessException("项目信息未关联项目公司!");
        }
        entry.setSignStatus(CustomerEntryConstants.SIGN_STATUS_TENANT_ING);
        // 创建合同信息
        CrmCustomerContractManagement contractManagement = new CrmCustomerContractManagement();
        contractManagement.setContractNumber(PlantformUtils.getContractNumber(companySettings.getContractPrefix(), companySettings.getContractIndex()));
        contractManagement.setEntryId(entry.getId());
        contractManagement.setPowerStationCode(entry.getPowerStationCode());
        contractManagement.setTraderId(entry.getDistributorId());
        contractManagement.setProjectCompanyId(companySettings.getId());
        contractManagement.setProjectCompanyName(companySettings.getName());
        contractManagement.setTenantMobile(entry.getMobile());
        contractManagement.setStatus(ESignConstants.STATUS_SIGNED_BY_TENANT);
        contractManagement.setInvitationId(operator.getUserId());
        contractManagement.setInvitationName(operator.getUserName());
        contractManagement.setInvitationTime(now);
        contractManagement.setPsnId(companySettings.getPsnId());
        contractManagement.setOrgId(companySettings.getSignerCode());
        //获取模板
        TraderContractTemplate template = templateDao.findOneByCompanyId(projectSetting.getProjectCompanyId());
        if (template == null) {
            throw new BusinessException("请先维护合同模板");
        }
        try {
            List<ComponentVo> componentS = Lists.newArrayList();
          /*  ContractTemplateVo templateVo = ESignFileService.getComponentsInfo(template.getDocTemplateId());
            if (templateVo == null) {
                throw new BusinessException("请先维护合同模板");
            }*/
            //获取项目公司信息
            SqlBuilder sql = new SqlBuilder();

            sql.line("select s.code,s.name,s.`epc_price` as epcPrice,p.`enterprise_qualification_number` as enterpriseQualificationNumber,");
            sql.line("p.`charge_person` as chargePerson,p.`charge_person_id_card` as chargePersonIdCard,p.`telephone`");
            sql.line(",concat(p.province, p.city, p.area, p.address) as companyAddress");
            sql.line("from `crm_project_setting` s");
            sql.line("left join `crm_project_company_settings` p on p.`id`=s.`project_company_id`");
            sql.line("where  s.`id`=?",entry.getProjectId());
            Record setting = Db.findFirst(sql.build(),sql.params());
            List<Record> list = Db.find(" SELECT * FROM `crm_sign_file` WHERE  form='2'  ");
            for(Record rd :list){
                ComponentVo vo = new ComponentVo();
                String key = rd.getStr("component_key");
                if("epcPrice".equals(key)){
                    BigDecimal toAmount =setting.getBigDecimal("epcPrice").multiply(new BigDecimal(entry.getDesignCapacity()));
                    String macAmount = ConvertUpMoney.toChinese(toAmount.toString());
                    ComponentVo vo0 = new ComponentVo();
                    vo0.setComponentKey("macAmount");
                    vo0.setComponentValue(macAmount);//大写
                    componentS.add(vo0);
                    ComponentVo vo1 = new ComponentVo();
                    vo1.setComponentKey("epcPriceTotal");
                    vo1.setComponentValue(toAmount);//总价
                    componentS.add(vo1);
                    ComponentVo vo2 = new ComponentVo();
                    vo2.setComponentKey(key);
                    vo2.setComponentValue(setting.getBigDecimal("epcPrice"));//单价
                    componentS.add(vo2);
                    continue;
                }

                Object eomValue = BeanUtils.getValueByStringField(entry,key);
                if(eomValue != null){
                    vo.setComponentKey(key);
                    vo.setComponentValue(eomValue);
                    componentS.add(vo);
                    if("tenantName".equals(key)){
                        ComponentVo vo3 = new ComponentVo();
                        vo3.setComponentKey("tenantName1");
                        vo3.setComponentValue(eomValue);
                        componentS.add(vo3);
                        ComponentVo vo4 = new ComponentVo();
                        vo4.setComponentKey("tenantName2");
                        vo4.setComponentValue(eomValue);
                        componentS.add(vo4);
                        ComponentVo vo5 = new ComponentVo();
                        vo5.setComponentKey("tenantName3");
                        vo5.setComponentValue(eomValue);
                        componentS.add(vo5);
                    }
                    if("traderName".equals(key)){
                        ComponentVo vo3 = new ComponentVo();
                        vo3.setComponentKey("traderName1");
                        vo3.setComponentValue(eomValue);
                        componentS.add(vo3);
                        ComponentVo vo4 = new ComponentVo();
                        vo4.setComponentKey("traderName2");
                        vo4.setComponentValue(eomValue);
                        componentS.add(vo4);
                        ComponentVo vo5 = new ComponentVo();
                        vo5.setComponentKey("traderName3");
                        vo5.setComponentValue(eomValue);
                        componentS.add(vo5);
                    }

                }

                try {
                    if(setting.getStr(key)!= null){
                        ComponentVo vo3 = new ComponentVo();
                        vo3.setComponentKey(key);
                        vo3.setComponentValue(setting.getStr(key));//单价
                        componentS.add(vo3);
                    }
                }catch (Exception e){
                    logger.error("============ {}",e);
                }
            }

            //未邀请，流程ID为空
            FileVo fileVo = ESignFileService.createByDocTemplate(template.getDocTemplateId(), template.getContractName(), componentS);
            contractManagement.setFileId(fileVo.getFileId());
            String signFlowTitle = String.format("能辉光伏%s年户用电站运营合同(%s)-%s",
                    DateUtils.formatDate(new Date(), "yy"), entry.getTraderName(), entry.getTenantName());
            //基于文件发起签署---获取到流程ID
            String signFlow = ESignSignService.createTentConcatByFile(fileVo.getFileId(), template.getContractName(),
                    contractManagement, signFlowTitle, companySettings,"",template);
            contractManagement.setSignFlowId(signFlow);
            contractManagementDao.save(contractManagement);

            companySettings.setContractIndex(companySettings.getContractIndex() + 1);
            

            projectCompanySettingsDao.save(companySettings);


            customerDao.save(entry);
            String content = "";
            msgService.saveCustomerEntryMsg(operator, entry.getId(), CustomerEntryConstants.SIGN_INVITE,content,operator.getUserName());
            //发邀请签约短信 到农户手机号上
            Map<String,String> map=ESignSignService.signUrl(signFlow, contractManagement.getTenantMobile(), "");
        /*    String shortUrl=map.get("shortUrl");
            StringBuilder contextString = new StringBuilder("尊敬的" + entry.getTenantName()
                    + "，您好！能辉光伏邀请您签署合同。点击进入:"+shortUrl);
            Map<String, Object> result = SfSmsNUtils.sendBatchMsg(contractManagement.getTenantMobile(), contextString.toString(), "能辉光伏", "", SfSmsNUtils.SMS_TYPE_A);
           */
            logger.info("SfSmsUtils.sendMsg result:{}", map);
        } catch (EsignDemoException e) {
            logger.error("邀请签约获取链接出错=================  {}", e);
           throw new BusinessException(e.getMessage());
        }

    }

    /**
     * 平台签署 获取链接
     */
    public Map<String,String> platformSign(String id) throws EsignDemoException {
        // 获取合同
        CrmCustomerContractManagement contractManagement = contractManagementDao.get(id);
        if (!CustomerEntryConstants.SIGN_STATUS_COMPANY_ING.equals(contractManagement.getStatus())) {
            throw new EsignDemoException("合同状态已改变，请刷新列表查看");
        }
        // 根据流程ID获取签署链接
        Map<String,String> remap = ESignSignService.signUrl(contractManagement.getSignFlowId(), null, contractManagement.getPsnId());
        String url=remap.get("url");
        logger.info("平台签署====================== url:{}",url);
        return remap;
    }

    /***
     * 查看合同
     * @param id
     */
    public String fileDownloadUrl(String id) throws EsignDemoException {
        CrmCustomerContractManagement one = contractManagementDao.get(id);
        if (!ESignConstants.STATUS_COMPLETED.equals( one.getStatus() )) {
            Map<String,String> map=ESignSignService.signUrl(one.getSignFlowId(), one.getTenantMobile(), "");
            return map.get("url");
        }
        return ESignSignService.fileDownloadUrl(one.getSignFlowId());
    }

}
