package com.sifang.modules.esign.service;


import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.alioss.AliyunOSSClientUtil;
import com.sifang.modules.customer.Service.CustomerEntryMsgService;
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.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.comm.EsignHttpResponse;
import com.sifang.modules.esign.cn.tsign.hz.exception.EsignDemoException;
import com.sifang.modules.esign.constants.ESignConstants;
import com.sifang.modules.esign.query.*;
import com.sifang.modules.flowpath.dao.TraderAgentDao;
import com.sifang.modules.flowpath.dao.TraderApplyAgentDao;
import com.sifang.modules.flowpath.entity.TraderAgent;
import com.sifang.modules.flowpath.entity.TraderApplyAgent;
import com.sifang.modules.sunshine.SystemSetting.dao.ProjectCompanyDao;
import com.sifang.modules.sunshine.SystemSetting.dao.TraderDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmTrader;
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.entity.User;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.dao.UserDao;
import com.sifang.modules.sys.entity.Operator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class ESignService {

    Logger logger= LoggerFactory.getLogger(getClass());

    @Autowired
    UserDao userDao;

    @Autowired
    private TraderAgentDao traderAgentDao;

    @Autowired
    private TraderDao traderDao;

    @Autowired
    private ContractManagementDao contractManagementDao;

    @Autowired
    private CustomerEntryDao entryDao;

    @Autowired
    private CustomerEntryMsgService msgService;

    @Autowired
    private ProjectCompanyDao projectCompanyDao;
    @Autowired
    OperatingLeaseService operatingLeaseService;
    @Autowired
    private CustomerEntryService entryService;

    @Transactional(rollbackFor = Exception.class)
    public void signContractCallBack(FlowPathEndReq backRes){

        if("SIGN_FLOW_COMPLETE".equals(backRes.getAction())){
            //1.更改合同签署状态
            TraderAgent agent = traderAgentDao.findTraderAgentByflowId(backRes.getSignFlowId());
            if(agent == null){
                throw new BusinessException("更新合同签署状态失败！");
            }
            agent.setSignContract("1");//已簽署
            //判斷是否還有未簽署的區域合同
            CrmTrader trader = traderDao.get(agent.getTraderId());
            long count = Db.queryLong("SELECT COUNT(*) FROM `crm_trader_apply_agent` WHERE trader_id=? AND sign_contract='0' and sign_flow_id !=?",agent.getTraderId(),backRes.getSignFlowId());
            if(count<1){
                trader.setContractSigning("1");
                traderDao.save(trader);
                Db.update("UPDATE `sys_user` SET status='0' WHERE id=?",trader.getUserId());
            }
            traderAgentDao.save(agent);

        }

    }

    //农户合同签署回调（华融）
    @Transactional(rollbackFor = Exception.class)
    public void signTentContractCallback(SignCallBackRes backRes) {
        // 查询合同
        CrmCustomerContractManagement management = contractManagementDao.getBySignFlowId(backRes.getSignFlowId());
        if(management==null){
            logger.error(">>>>>>>>>>>>>>>>>>signTentContractCallback  未找到合同 signFlowId:{}",backRes.getSignFlowId());
        }
        CustomerEntry entry = entryDao.get(management.getEntryId());
        // 修改状态
        Date now = new Date();
        short type = 0;
        String name="";
        String content = "";
        if ("2".equals(backRes.getSignOrder())) {
            // 用户签署
            if ("2".equals(backRes.getSignResult())) { //签署完成

                management.setStatus(ESignConstants.STATUS_REFUSE_SIGNED_BY_COMPANY);
                entry.setSignStatus(CustomerEntryConstants.SIGN_STATUS_FINISH);

                management.setTenantSignTime(now);
                type = CustomerEntryConstants.SIGN_TENANT_DONE;
            } else if ("4".equals(backRes.getSignResult())) {  //拒签
                management.setStatus(ESignConstants.STATUS_REFUSE);
                entry.setSignStatus(CustomerEntryConstants.SIGN_STATUS_REFUSE);
                type = CustomerEntryConstants.SIGN_TENANT_REFUSE;
            }
            name=entry.getTenantName();
        } else if("3".equals(backRes.getSignOrder())){
            // 共签人签署
            if ("2".equals(backRes.getSignResult())) {  //签署完成
                management.setStatus(ESignConstants.STATUS_REFUSE_SIGNED_BY_COMPANY);
                entry.setSignStatus(CustomerEntryConstants.SIGN_STATUS_FINISH);
                management.setCompanySignTime(now);
                content="共签人签约";
            } else if ("4".equals(backRes.getSignResult())) {   //拒签
                management.setStatus(ESignConstants.STATUS_REFUSE);
                entry.setSignStatus(CustomerEntryConstants.SIGN_STATUS_REFUSE);
                content="共签人拒签";
            }
            name=entry.getBpName();//共签人
        }
        if(ESignConstants.STATUS_REFUSE_SIGNED_BY_COMPANY.equals(management.getStatus())){ //合同完成了
            try {
                String url = ESignSignService.fileDownloadUrl(backRes.getSignFlowId());
                String pathUrl= AliyunOSSClientUtil.saveUrlWeb(url);
                management.setContractUrl(pathUrl);
            } catch (EsignDemoException e) {
                e.printStackTrace();
                logger.error("获取 下载已签署文件及附属材料 signTentContractCallback 失败 e:{}",e);
            }catch (IOException i){
                i.printStackTrace();
                logger.error("获取 下载已签署文件及附属材料 signTentContractCallback 失败 i:{}",i);
            }
        }
        management.setUpdateTime(now);
        contractManagementDao.save(management);
        entryDao.save(entry);
        if (type != 0) {
            Operator operator = new Operator();
            operator.setUserId("1");
            operator.setUserName(name);
            msgService.saveCustomerEntryMsg(operator, entry.getId(), type, content,operator.getUserName());
        }
    }

    //机构认证回调
    @Transactional(rollbackFor = Exception.class)
    public void authConfirmCallBack(AuthCallBackRes callBackRes) throws EsignDemoException {
        logger.info(">>>>>>>>>>>>>>>>>>authConfirmCallBack   authFlowId:{}",callBackRes.getAuthFlowId());
        if("AUTHORIZE_FINISH".equals(callBackRes.getAction())){

           // Db.update("UPDATE `crm_platform` SET orgId=? WHERE id='1'",callBackRes.getOrgId());
            ProjectCompanySettings companySettings=projectCompanyDao.getByAuthFlowId(callBackRes.getAuthFlowId());
            companySettings.setSignerCode(callBackRes.getOrgId());  // 机构id
            companySettings.setPsnId(callBackRes.getPsnId());  //经办人id
            companySettings.setOrgStatus(ESignConstants.ORG_STATUS_CERTIFIED);
            //companySettings.setStatus(ESignConstants.status_enable);
            //获取公司印章--合同章
            String sealId=ESignAuthService.orgOwnSealList(callBackRes.getOrgId());
            companySettings.setSealId(sealId);


            //如果公司开始授权了 那么是不是就不需要这一步了
            //需要项目公司给经办人授权印章
            try{
               /* //第一步 给经办人添加（成员角色）印章保管员
                ESignAuthService.addCompanyMemberRole(companySettings.getSignerCode(), companySettings.getPsnId());
                // 第二步 经办人自己给子授权
                if(StringUtil.isNotBlank(sealId)){
                    ESignAuthService.companyInternalAuth(companySettings.getSignerCode(),sealId,companySettings.getPsnId(),companySettings.getTelephone());
                }*/
                //项目公司授权成功后，那么调用  印章 跨企业授权
                String sealAuthBizId= ESignAuthService.orgSealExternalAuth(callBackRes.getOrgId(),sealId,callBackRes.getPsnId(),companySettings);
                companySettings.setSealExternalAuth("1");
                companySettings.setSealEffectiveTime(new Date());
                companySettings.setSealExpireTime(DateUtils.yearSub(new Date(),3));
                companySettings.setSealAuthBizId(sealAuthBizId);
            }catch (Exception e){
                  logger.error(">>>>>>>>>>>>>>>>>>>>>>>>>>>authConfirmCallBack  e:{}",e);
            }

            projectCompanyDao.save(companySettings);
        }

    }

    //农户签署授权合同回调
    @Transactional(rollbackFor = Exception.class)
    public void authTenantCallBack(SignCallBackRes backRes) throws EsignDemoException, IOException {
        logger.info(">>>>>>>>>>>>authTenantCallBack  signFlowId:{}",backRes.getSignFlowId());
        if("2".equals(backRes.getSignResult())){
            String url= ESignSignService.fileDownloadUrl(backRes.getSignFlowId());
            String pathUrl= AliyunOSSClientUtil.saveUrlWeb(url);
            int i=Db.update("UPDATE `crm_customer_yx_condition` SET authorization='3',authorization_contract_path=?  WHERE sign_flow_id=? ",
                    pathUrl,backRes.getSignFlowId());
            int j=Db.update("UPDATE `crm_customer_yx_authorization` SET authorization='3',authorization_contract_path=? ,sign_time = ?  WHERE sign_flow_id=? ",
                    pathUrl,new Date() ,backRes.getSignFlowId());
            Record record=Db.findFirst(" SELECT c.id,c.name,c.mobile,c.id_code,c.partner_id FROM `crm_customer_yx_condition` c WHERE c.sign_flow_id=? ",backRes.getSignFlowId());
            logger.info(">>>>>>>>authTenantCallBack  i:{}",i);
            if(i==0){
                throw new BusinessException("更新农户授权状态失败！");
            }
            //记录过程信息
            try{
                List<Record> list=Db.find(" SELECT id,power_station_code FROM `crm_customer_entry` " +
                                "WHERE  id_code=? AND mobile=? AND tenant_type = '1' and partner_id=? and authorization = '2' ",
                        record.get("id_code"),record.getStr("mobile"),record.getStr("partner_id"));
                for(Record record1:list){
                    msgService.saveCustomerEntryMsg(record1.getStr("id"), "农户签署授权合同! ");
                }
            }catch (Exception e){
                logger.error(">>>>>>>>authTenantCallBack e:",e);
            }
            //提交预审
            String entryId = Db.queryStr("select id from crm_customer_entry " +
                            "where id_code=? AND mobile=? AND tenant_type = '1' and authorization = '2' and partner_id=? and status!='b' order by create_time desc limit 1",
                    record.get("id_code"),record.getStr("mobile"), record.getStr("partner_id"));

            Db.update(" UPDATE `crm_customer_entry` SET authorization='3' WHERE  id_code=? AND tenant_type = '1' AND mobile=? and partner_id=? and authorization = '2' ",
                    record.get("id_code"),record.getStr("mobile"),record.getStr("partner_id"));
            if (StringUtil.isNotBlank(entryId)) {
                Result result = null;
                try {
                    String isHistory = Db.queryStr(" select is_history from crm_customer_entry where id = ? ", entryId);
                    if ("0".equals(isHistory)) {
                        logger.info("信息授权回调，提交预审，entryId:{}", entryId);
                        result = entryService.submitAudit(entryId);
                    }else {
                        //历史电站不用预审
                        Db.update(" UPDATE `crm_customer_entry` SET credit='4',apply_status = '2' ,design_audit_flag = '1' WHERE  id = ? ",
                                entryId);
                    }

                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
                if (result != null && "200".equals(result.getCode())) {
                    Db.update(" UPDATE `crm_customer_entry` SET credit='2' WHERE  id = ? and credit in ('0','1')",
                            entryId);

                }
            }
        }
    }

    //公司签署跨企业印章权限
    @Transactional(rollbackFor = Exception.class)
    public void orgSealExternalAuthCallBack(OrgSealAuthVo authVo){
        if("SEAL_AUTH_SIGN".equals(authVo.getAction())){
             String sealAuthBizId=authVo.getSealAuthBizId();
             if("1".equals(authVo.getAuthStatus())){
                 Db.update(" UPDATE `crm_project_company_settings` s SET seal_external_auth='3' WHERE seal_auth_biz_id=? ",sealAuthBizId);
             }
        }
    }

}
