package com.sifang.modules.sunshine.SystemSetting.service;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.bestsign.constant.TraderContractConstant;
import com.sifang.modules.bestsign.service.BestSignDeltaApiService;
import com.sifang.modules.bestsign.vo.BestSignCallBackDataRes;
import com.sifang.modules.bestsign.vo.BestSignCallBackRes;
import com.sifang.modules.bestsign.vo.BestSignOperationResVo;
import com.sifang.modules.bestsign.vo.BestSignOperationVo;
import com.sifang.modules.platform.utils.PlantformUtils;
import com.sifang.modules.sunshine.SystemSetting.dao.CrmTraderContractDao;
import com.sifang.modules.sunshine.SystemSetting.dao.TraderDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmTrader;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmTraderContract;
import com.sifang.modules.sunshine.SystemSetting.form.AddTraderContractVo;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
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.common.service.BaseService;
import com.sifang.modules.sys.util.LayuiPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
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 CrmTraderContractService extends BaseService {

    @Autowired
    private CrmTraderContractDao traderContractDao;

    @Autowired
    private TraderService traderService;

    @Autowired
    private BestSignDeltaApiService bestSignDeltaApiService;

    public void listPageData(LayuiPage<Record> page, Map<String, String> map){
        List<Record> list=traderContractDao.listDate(page,map);
        page.setData(list);
        Long count=traderContractDao.countList(map);
        page.setCount(count);
    }

    public CrmTraderContract getById(String id){
        return traderContractDao.get(id);
    }

    public CrmTraderContract getByContractId(String id){
        return traderContractDao.getByContractId(id);
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveContract(AddTraderContractVo addVo){
      logger.info(">>>>saveContract  提交代理商合同 ifSubmit:{}",addVo.getIfSubmit());
        User user= UserUtils.getUser();
        CrmTraderContract addContract;
      if(StringUtil.isBlank(addVo.getId())){
          addContract=new CrmTraderContract();
          addContract.setCreateName(user.getUserName());
          addContract.setCreateTime(new Date());
      }else {
          addContract=traderContractDao.get(addVo.getId());
      }
        //判断有没有生效中的合同编码
         Long sameContract=traderContractDao.getSameContractNumber(addVo.getContractNumber(),addVo.getId());
      if(sameContract>0){
          throw new BusinessException(addVo.getContractNumber()+" 该合同编码有生效中的合同，不能重复添加！");
      }
        addContract.setTraderId(addVo.getTraderId());
        addContract.setStatus(addVo.getIfSubmit());
        addContract.setContractNumber(addVo.getContractNumber());
        addContract.setStartTime(addVo.getStartTime());
        addContract.setEndTime(addVo.getEndTime());
        addContract.setContractUrl(addVo.getContractUrl());
        addContract.setContractFileName(addVo.getContractFileName());
        addContract.setUpdateTime(new Date());
        addContract.setUpdateName(user.getUserName());
        if("2".equals(addVo.getIfSubmit())){ //提交
            try {
                CrmTrader trader=traderService.getById(addContract.getTraderId());
                String contractId= bestSignDeltaApiService.sendContract(trader.getName(),trader.getMobile(),addContract.getContractUrl(),addContract.getContractFileName());
                addContract.setCreateTime(new Date());
                addContract.setCreateName(user.getUserName());
                addContract.setContractId(contractId);
            }catch (IOException i){
                i.printStackTrace();
                logger.error("saveContract 上上签  处理文件流异常 i:",i);
                throw new BusinessException("创建合同失败！输入输出异常，原因："+i.getMessage());
            }catch (Exception e) {
                e.printStackTrace();
                throw new BusinessException(e.getMessage());
            }
        }
        traderContractDao.save(addContract);
    }

    public String getLatestContractStatus(String traderId,String id){
        StringBuilder sb=new StringBuilder();
        sb.append("  SELECT IFNULL(c.status,'') as status FROM `crm_trader_contract` c ");
        sb.append(" WHERE trader_id=? AND c.status<>'0'  ");
        if(StringUtil.isNotBlank(id)){
            sb.append(" AND c.id<>'"+id+"' ");
        }
        sb.append(" ORDER BY create_time DESC limit 1 ");
        return Db.queryStr(sb.toString(),traderId);
    }

    //获取签署链接
    public Map<String,String> signUrl(String id){
        CrmTraderContract traderContract=getById(id);
        if(StringUtil.isBlank(traderContract.getContractId())){
            throw new BusinessException("没有找到合同信息！");
        }
        Map<String,String> map= bestSignDeltaApiService.signUrl(traderContract.getContractId());
        return map;
    }

    //获取下载地址
    public String downLoadContract(String id){
        CrmTraderContract traderContract=getById(id);
        if(StringUtil.isBlank(traderContract.getContractId())){
            throw new BusinessException("没有找到合同信息！");
        }
        if(!StringUtil.equalsAny(traderContract.getStatus(), TraderContractConstant.CONTRACT_USE,TraderContractConstant.CONTRACT_VALID)){
            throw new BusinessException("合同状态不允许下载！");
        }
        if(StringUtil.isNotBlank(traderContract.getContractSignedPath())){
           return traderContract.getContractSignedPath();
        }else{
            String path= bestSignDeltaApiService.downloadContract(traderContract.getContractId());
            traderContract.setContractSignedPath(path);
            traderContractDao.save(traderContract);
            return path;
        }

    }

    //合同作废
    @Transactional(rollbackFor = Exception.class)
    public void cancelContract(String id){
        CrmTraderContract traderContract=getById(id);
        if(StringUtil.isBlank(traderContract.getContractId())){
            throw new BusinessException("没有找到合同信息！");
        }
        if(!StringUtil.equalsAny(traderContract.getStatus(), TraderContractConstant.CONTRACT_TRADER_SIGN,TraderContractConstant.CONTRACT_NH_SIGN,TraderContractConstant.CONTRACT_USE)){
            throw new BusinessException("合同状态不允许作废！");
        }
        User user=UserUtils.getUser();
        if(!TraderContractConstant.CONTRACT_USE.equals(traderContract.getStatus())){
            //未完成的合同可以撤销
            bestSignDeltaApiService.revoke(traderContract.getContractId());
        }
        traderContract.setStatus(TraderContractConstant.CONTRACT_CANCEL);
        traderContract.setUpdateName(user.getUserName());
        traderContract.setUpdateTime(new Date());
        traderContractDao.save(traderContract);
    }

    //删除合同
    @Transactional(rollbackFor = Exception.class)
    public void deleteContract(String id){
        CrmTraderContract traderContract=getById(id);
        if(!StringUtil.equalsAny(traderContract.getStatus(), TraderContractConstant.CONTRACT_CANCEL)){
            throw new BusinessException("合同状态不允许删除！");
        }
        User user=UserUtils.getUser();
        traderContract.setStatus(TraderContractConstant.CONTRACT_DELETE);
        traderContract.setUpdateName(user.getUserName());
        traderContract.setUpdateTime(new Date());
        traderContractDao.save(traderContract);
    }


    //签署完成的回调
    @Transactional(rollbackFor = Exception.class)
    public void signedPush(BestSignCallBackRes backRes){
        logger.info(">>>>>>>>>>>>signedPush  type:{}",backRes.getType());
        //合同签署完成
        if ("CONTRACT_COMPLETE".equals(backRes.getType())) {
            BestSignCallBackDataRes responseData = backRes.getResponseData();
            for (String contractId : responseData.getContractIds()) {
                logger.info(">>>signedPush  contractId:{}",contractId);
                CrmTraderContract contract=getByContractId(contractId);
                contract.setStatus(TraderContractConstant.CONTRACT_USE);
                contract.setSignFinishTime(new Date());
                traderContractDao.save(contract);
                int i=Db.update(" UPDATE `crm_trader` t,`sys_user` u SET t.status='0',u.status='0' WHERE t.user_id=u.id AND t.id=? ",contract.getTraderId());
                logger.info(">>>>签署完成的回调 签署完成的回调  i:{}",i);
            }
        }
    }

    //签署人签署回调
    @Transactional(rollbackFor = Exception.class)
    public void operationSignPush(BestSignOperationVo signOperationVo){
        logger.info(">>>>>>>>>>>>operationSignPush  type:{}",signOperationVo.getType());
        BestSignOperationResVo responseData=signOperationVo.getResponseData();
        if("代理商".equals(responseData.getRoleName()) && "SIGN_SUCCEED".equals(responseData.getOperationStatus())){  //代理商签署完成
          int i=Db.update(" UPDATE `crm_trader_contract` SET sign_finish_time=NOW(),status='3' WHERE contract_id=? ",responseData.getContractId());
          logger.info(">>>>签署人签署回调 operationSignPush  i:{}",i);
        }
    }
}
