package com.sifang.modules.customer.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.config.EsignConfig;
import com.sifang.modules.customer.constant.CustomerEntryConstants;
import com.sifang.modules.customer.constant.PartnerConstants;
import com.sifang.modules.customer.constant.YueXiuConstants;
import com.sifang.modules.customer.dao.CrmYxProcessDao;
import com.sifang.modules.customer.dao.CustomerEntryDao;
import com.sifang.modules.customer.dao.TenantYxBankCardDao;
import com.sifang.modules.customer.entity.CrmTenantYxBankCard;
import com.sifang.modules.customer.entity.CustomerEntry;
import com.sifang.modules.customer.form.YueXueBankCardVo;
import com.sifang.modules.customer.utils.YueXiuUtils;
import com.sifang.modules.customer.vo.GetStatusVo;
import com.sifang.modules.customer.vo.OpenBankCardVo;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmTrader;
import com.sifang.modules.sunshine.SystemSetting.service.TraderService;
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.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.utils.img.DownImg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class YueXiuBankCardService extends BaseService {

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

    @Autowired
    private CustomerEntryDao entryDao;

    @Autowired
    private TenantYxBankCardDao tenantYxBankCardDao;

    @Autowired
    private OperatingLeaseService operatingLeaseService;

    @Autowired
    private TraderService traderService;

    @Autowired
    private CustomerEntryService entryService;

    @Value("${yx.setting}")
    private String YX;

    //type=1  开户; type=2 销户
    @Transactional(rollbackFor = Exception.class)
    public String openBankCard(String entryId,String type){
        logger.info("openBankCard entryId:{}",entryId);
        CustomerEntry entry = entryDao.get(entryId);
        if (!"1".equals(entry.getFilingType())) {
            throw new BusinessException("非农户备案 不需要开卡！");
        }
        //判断是否已开卡
        CrmTenantYxBankCard card=tenantYxBankCardDao.getByIdCard(entry.getIdCode(),entry.getManagementType(),entry.getPartnerId());
        if("1".equals(type) && card !=null){
            logger.info("获取开卡信息 entryId：{} , 开卡状态 ：{}",entryId,card.getStatus());
            //查询开卡状态
            boolean fg=false;
            if(YueXiuConstants.BANK_CODE_SAVE.equals(card.getStatus()) && StringUtil.isNotBlank(card.getCorpCommSerno())){
                YueXueBankCardVo re=fundBankCardStatus(card.getCorpCommSerno());
//                card.setStatus(re.getResult());
                if(StringUtil.isNotBlank(re.getRetMsg())){
                    card.setReason(re.getRetMsg());
                }
                editBankCardStatus(re,card);
                fg=true;
            }

            if(StringUtil.equalsAny(card.getStatus(),YueXiuConstants.BANK_CODE_YKH_SUCCESS,YueXiuConstants.BANK_CODE_SUCCESS)){
                if(fg){
                    saveCard(card);
                }
                return "10000";
            }
            // 重新开卡时 需要给记录重新赋值
            if (YueXiuConstants.BANK_CODE_CANCEL_SUCCESS.equals(card.getStatus())) {
                card.setAccountCode(null);
                card.setAccountName(null);
                card.setName(entry.getTenantName());
                card.setIdCode(entry.getIdCode());
                card.setMobile(entry.getMobile());
                card.setManagementType(entry.getManagementType());
            }
        }else if("1".equals(type)){
            card=new CrmTenantYxBankCard();
            card.setName(entry.getTenantName());
            card.setIdCode(entry.getIdCode());
            card.setMobile(entry.getMobile());
            card.setManagementType(entry.getManagementType());
            card.setPartnerId(PartnerConstants.PARTNER_ID_YX);
            card.setOpenBankNumber("102581000353");
            card.setOpenBankName("中国工商银行股份有限公司广州南方支行");
        }

        card.setStatus(YueXiuConstants.BANK_CODE_SAVE);
        String url=YueXiuConstants.OPEN_ACCOUNT_URL;
        OpenBankCardVo vo=new OpenBankCardVo();
        if("2".equals(type)){
            card.setStatus(YueXiuConstants.BANK_CODE_CANCEL_IN);
            url=YueXiuConstants.CANCEL_ACCOUNT_URL;
            vo.setCorpCommSerno(card!=null?card.getCorpCommSerno():"");
        }
        vo.setCustName(card.getName());
        vo.setCertNo(card.getIdCode());
        vo.setMobile(card.getMobile());
        vo.setLessorCode(card.getManagementType());
        vo.setReturnUrl(EsignConfig.NotifyUrl+"/a/main/redirect/eSignSuccess");

        Map<String, Object> map = new HashMap<>();
        List<OpenBankCardVo> bodyData=new ArrayList<>();
        bodyData.add(vo);
        map.put("body",bodyData);
        Map<String, Object> head = new HashMap<>();
        head.put("serialNumber", UUID.randomUUID().toString());
        head.put("systemId",YueXiuConstants.CLIENT_ID);
        head.put("transactionCode",YueXiuConstants.TRANSACTION_CODE_CARD+YX);
        head.put("transactionTime", DateUtils.formatDate(new Date(),"yyyyMMdd HH:mm:ss"));
        head.put("version",1);
        map.put("head",head);
        logger.info(">>开户/销户  openBankCard json:{}",new Gson().toJson(map));
        JSONObject jieMap = operatingLeaseService.clientPostZYMap(map, url);
        logger.info("开户/销户 openBankCard -------返回结果：{}", jieMap);
        JSONArray reqMap = jieMap.getJSONArray("body");
        JSONObject re = reqMap.getJSONObject(0);
        String gdUrl="";
        //type: S-请求成功 E-请求失败
        if ("S".equals(re.get("type"))) {
            logger.info(">>>openBankCard   re:{}",re);
             gdUrl=re.getString("gdUrl");
             String corpCommSerno=re.getString("corpCommSerno");
             card.setCorpCommSerno(corpCommSerno);
          /*  card.setStatus(YueXiuConstants.BANK_CODE_SL);*/

            CrmYxProcessDao.addProcess(entry.getId(),"5","越秀开卡接口",JSONObject.toJSONString(map),jieMap.toJSONString(),"0");
        } else {
            card.setReason(re.getString("message"));
            throw new BusinessException("操作失败!失败原因："+re.get("message"));
        }
        saveCard(card);
        return gdUrl;
    }

    public void saveCard(CrmTenantYxBankCard card) {
        card.setOpenBankNumber("102581000353");
        card.setOpenBankName("中国工商银行股份有限公司广州南方支行");
        card.setOpeningTime(new Date());
        card.setWithHolding("0");
        tenantYxBankCardDao.save(card);
        try {
            updateCorpserno(card.getCorpCommSerno(), card.getStatus());
            StringBuilder saveHistorySql = new StringBuilder();
            saveHistorySql.append("INSERT INTO `crm_tenant_yx_bank_card_history` (`id`,`name`,`id_code`,`mobile`,`management_type`,");
            saveHistorySql.append("   `corp_comm_serno`,`account_code`,`account_name`,`status`,`reason`,`create_time`) ");
            saveHistorySql.append("VALUES( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, now() )");
            Db.update(saveHistorySql.toString(), card.getId(), card.getName(), card.getIdCode(), card.getMobile(), card.getManagementType(),
                    card.getCorpCommSerno(), card.getAccountCode(), card.getAccountName(), card.getStatus(), card.getReason());
        }catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
    public void saveCard2(CrmTenantYxBankCard card) {
        Db.update(" update crm_tenant_yx_bank_card set open_bank_number = '102581000353' " +
                " ,open_bank_name = '中国工商银行股份有限公司广州南方支行',opening_time = NOW(),with_holding = '0' where id = ? ", card.getId());
        try {
            card.setOpenBankNumber("102581000353");
            card.setOpenBankName("中国工商银行股份有限公司广州南方支行");
            card.setOpeningTime(new Date());
            card.setWithHolding("0");
            updateCorpserno(card.getCorpCommSerno(), card.getStatus());
            StringBuilder saveHistorySql = new StringBuilder();
            saveHistorySql.append("INSERT INTO `crm_tenant_yx_bank_card_history` (`id`,`name`,`id_code`,`mobile`,`management_type`,");
            saveHistorySql.append("   `corp_comm_serno`,`account_code`,`account_name`,`status`,`reason`,`create_time`) ");
            saveHistorySql.append("VALUES( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, now() )");
            Db.update(saveHistorySql.toString(), card.getId(), card.getName(), card.getIdCode(), card.getMobile(), card.getManagementType(),
                    card.getCorpCommSerno(), card.getAccountCode(), card.getAccountName(), card.getStatus(), card.getReason());
        }catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    //查看卡状态
    @Transactional(rollbackFor = Exception.class)
    public Result lookBankCardByIdCode(String idCode){
        logger.info("lookBankCardByIdCode cardId:{}",idCode);
        //判断是否销户
        CrmTenantYxBankCard card=tenantYxBankCardDao.getInfoByIdCard(idCode, PartnerConstants.PARTNER_ID_YX);
        if (card == null){
            logger.info("未查询到卡记录");
        }
        logger.info("card:{}",new Gson().toJson(card));
        //判断是否处于 销户中
        if (StringUtil.isNotBlank(card.getCorpCommSerno())){
            //查询三方接口状态
            YueXueBankCardVo vo = fundBankCardStatus(card.getCorpCommSerno());
            if (card.getStatus().equals(vo.getResult())) {
                return Result.fail("未查询到变更信息，等待资方返回结果");
            }
            editBankCardStatus(vo, card);
            saveCard(card);
            return Result.ok("同步成功!");
        }
        return Result.fail("未查询到开卡编号");
    }



    //销户
    @Transactional(rollbackFor = Exception.class)
    public Result cancelBankCardByIdCode(String idCode){
        logger.info("cancelBankCard idCode:{}",idCode);
        String partnerId = PartnerConstants.PARTNER_ID_YX;
        //判断是否销户
        CrmTenantYxBankCard card=tenantYxBankCardDao.getInfoByIdCard(idCode, partnerId);
        if (card != null){
            logger.info("获取 销户状态 entryId：{} ,  销户状态 ：{}",idCode,card.getStatus());
        }
        //判断是否处于 销户中
        if (card.getStatus().equals(YueXiuConstants.BANK_CODE_CANCEL_IN)){
            //查询三方接口状态
            YueXueBankCardVo yueXueBankCardVo = fundBankCardStatus(card.getCorpCommSerno());
            if (yueXueBankCardVo.getProtocolStatus().equals(YueXiuConstants.BANK_CODE_CANCEL_SUCCESS)){
                 List<CustomerEntry> customerEntry = tenantYxBankCardDao.findCustomerEntryByIdCode(idCode, partnerId);
                for (CustomerEntry entry : customerEntry) {
                    entry.setSecCardStatus("0");
                    entryDao.save(entry);
                }
                card.setStatus(YueXiuConstants.BANK_CODE_CANCEL_SUCCESS);
                saveCard(card);
                return Result.fail("503","已销户成功，请勿重复销户!");
            }
        }
        String url=YueXiuConstants.CANCEL_ACCOUNT_URL;
        OpenBankCardVo vo=new OpenBankCardVo();
        vo.setCorpCommSerno(card.getCorpCommSerno());
        vo.setCustName(card.getName());
        vo.setCertNo(card.getIdCode());
        vo.setMobile(card.getMobile());
        vo.setLessorCode(card.getManagementType());
        vo.setReturnUrl(EsignConfig.NotifyUrl+"/a/main/redirect/eSignSuccess");
        Map<String, Object> map = new HashMap<>();
        List<OpenBankCardVo> bodyData=new ArrayList<>();
        bodyData.add(vo);
        map.put("body",bodyData);
//        System.out.println(bodyData);
        Map<String, Object> head = new HashMap<>();
        head.put("serialNumber", UUID.randomUUID().toString());
        head.put("systemId",YueXiuConstants.CLIENT_ID);
        head.put("transactionCode",YueXiuConstants.TRANSACTION_CODE_CARD+YX);
        head.put("transactionTime", DateUtils.formatDate(new Date(),"yyyyMMdd HH:mm:ss"));
        head.put("version",1);
        map.put("head",head);
        logger.info(">>销户  openBankCard json:{}",new Gson().toJson(map));
        JSONObject jieMap = operatingLeaseService.clientPostZYMap(map, url);
        logger.info("销户 openBankCard -------返回结果：{}", jieMap);
        JSONArray reqMap = jieMap.getJSONArray("body");
        JSONObject re = reqMap.getJSONObject(0);
        //type: S-请求成功 E-请求失败
        if ("S".equals(re.get("type"))) {
            logger.info(">>>cancelBankCard   re:{}",re);
            String corpCommSerno=re.getString("corpCommSerno");
            card.setCorpCommSerno(corpCommSerno);
            card.setStatus(YueXiuConstants.BANK_CODE_CANCEL_IN);
        } else {
            card.setReason(re.getString("message"));
            return Result.fail("503", (String) re.get("message"));
        //    throw new BusinessException("操作失败!失败原因："+re.get("message"));
        }
        saveCard(card);
        return  Result.ok();
    }

    //查看开卡状态--目前用主动推送，那么这个暂不用
    public CrmTenantYxBankCard lookBankCardStatus(String entryId){
        logger.info("..lookBankCardStatus  entryId:{}",entryId);
        CustomerEntry entry = entryDao.get(entryId);
        CrmTenantYxBankCard card=tenantYxBankCardDao.getByIdCard(entry.getIdCode(),entry.getManagementType(),entry.getPartnerId());

        Map<String, Object> map = new HashMap<>();
        List<Object> bodyData=new ArrayList<>();
        Map<String,Object> params=new LinkedHashMap<>();
        params.put("corpCommSerno",card.getCorpCommSerno()); //合作方交易单号
        bodyData.add(params);
        map.put("body",bodyData);
        Map<String, Object> head = new HashMap<>();
        head.put("serialNumber", UUID.randomUUID().toString());
        head.put("systemId",YueXiuConstants.CLIENT_ID);
        head.put("transactionCode",YueXiuConstants.TRANSACTION_CODE_CARD+YX);
        head.put("transactionTime", DateUtils.formatDate(new Date(),"yyyyMMdd HH:mm:ss"));
        head.put("version",1);
        map.put("head",head);
        logger.info(">>查看开卡状态  lookBankCardStatus json:{}",new Gson().toJson(map));
        JSONObject jieMap = operatingLeaseService.clientPostZYMap(map, YueXiuConstants.QUERY_BANK_CARD_STATUS_URL);
        logger.info("查看开卡状态 lookBankCardStatus -------返回结果：{}", jieMap);
        JSONArray reqMap = jieMap.getJSONArray("body");
        JSONObject re = reqMap.getJSONObject(0);
        //type: S-请求成功 E-请求失败
        if ("S".equals(re.get("type"))) {
            logger.info(">>>lookBankCardStatus   re:{}",re);
            YueXueBankCardVo vo=JSONObject.parseObject(re.toJSONString(), YueXueBankCardVo.class);
//            card.setStatus(re.getString("result"));
            editBankCardStatus(vo,card);
        } else {
            card.setStatus(re.getString("result"));
            card.setReason(re.getString("message"));
            throw new BusinessException("操作失败!失败原因："+re.get("message"));
        }
        saveCard(card);
        return card;
    }

    public YueXueBankCardVo fundBankCardStatus(String corpCommSerno){
        Map<String, Object> map = new HashMap<>();
        List<Object> bodyData=new ArrayList<>();
        Map<String,Object> params=new LinkedHashMap<>();
        params.put("corpCommSerno",corpCommSerno); //合作方交易单号
        bodyData.add(params);
        map.put("body",bodyData);
        Map<String, Object> head = new HashMap<>();
        head.put("serialNumber", UUID.randomUUID().toString());
        head.put("systemId",YueXiuConstants.CLIENT_ID);
        head.put("transactionCode",YueXiuConstants.TRANSACTION_CODE_CARD+YX);
        head.put("transactionTime", DateUtils.formatDate(new Date(),"yyyyMMdd HH:mm:ss"));
        head.put("version",1);
        map.put("head",head);
        logger.info(">>查看开卡状态  lookBankCardStatus json:{}",new Gson().toJson(map));
        JSONObject jieMap = operatingLeaseService.clientPostZYMap(map, YueXiuConstants.QUERY_BANK_CARD_STATUS_URL);
        logger.info("查看开卡状态 lookBankCardStatus -------返回结果：{}", jieMap);
        JSONArray reqMap = jieMap.getJSONArray("body");
        JSONObject re = reqMap.getJSONObject(0);
        //type: S-请求成功 E-请求失败
        if ("S".equals(re.get("type"))) {
            logger.info(">>>lookBankCardStatus   re:{}",re);
            YueXueBankCardVo vo=JSONObject.parseObject(re.toJSONString(), YueXueBankCardVo.class);
            return vo;
        } else {
            throw new BusinessException("操作失败!失败原因："+re.get("message"));
        }
    }

    //修改开卡状态
    @Transactional(rollbackFor = Exception.class)
    public void editBankCardStatus(YueXueBankCardVo vo,CrmTenantYxBankCard card){
        String result=vo.getResult();
        if(card.getStatus().equals(result)){
            return;
        }
        String status="";
        if("1".equals(result)){
              status=YueXiuConstants.ENTRY_CARD_STATUS_IN;
        }else if("2".equals(result)){
            status=YueXiuConstants.ENTRY_CARD_STATUS_IN;
        }else if("3".equals(result)){
            status=YueXiuConstants.ENTRY_CARD_STATUS_FAIL;
        }else if("4".equals(result)){
            status=YueXiuConstants.ENTRY_CARD_STATUS_HAVE;
        }else if("5".equals(result)){
            status=YueXiuConstants.ENTRY_CARD_STATUS_FAIL;
        }else if("6".equals(result)){
            status=YueXiuConstants.ENTRY_CARD_STATUS_NO;
        }
        card.setStatus(result);
        card.setAccountName(vo.getAcctName());
        card.setAccountCode(vo.getAccount());
      /*  //修改电站的开卡状态
        Db.update(" UPDATE `crm_customer_entry` SET sec_card_status=? WHERE  id_code=? AND management_type=?  ",status,card.getIdCode(),card.getManagementType());*/
        //二类卡开通后，后台自动出发进件申请，申请所涉及的字段内容处理如下：
        if ("4".equals(result) && StringUtil.isNotBlank(card.getAccountCode())) { //正式开户成功
            logger.info(">>>>>>>>>>editBankCardStatus ");
            //根据 手机号 和身份证和资方 获取电站
            List<CustomerEntry> entries = entryDao.findEntryByIdCodeVsManagementType(card.getIdCode(), card.getManagementType());
            logger.info(">>>>>>>>>>editBankCardStatus entries.size:{}", entries.size());
            if (entries.size() > 0) {
                for (CustomerEntry entry : entries) {
                    entry.setSecCardStatus(status);
                    entryDao.save(entry);
                }
            }
            DownImg img = new DownImg();
            String url = img.downImg(card.getAccountCode());
            card.setFrontImg(url);
            card.setBackImg("static/img/bank_card_back-yj.png");
        } else if ("6".equals(result)) {
            logger.info(">>>>>>>>>> 销户成功结果返回 ");
            List<CustomerEntry> entries = entryDao.findEntryByIdCodeVsManagementType(card.getIdCode(), card.getManagementType());
            logger.info(">>>>>>>>>>editBankCardStatus entries.size:{}", entries.size());
            if (entries.size() > 0) {
                for (CustomerEntry entry : entries) {
                    entry.setSecCardStatus(status);
                    entryDao.save(entry);
                }
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void editBankCardStatus2(YueXueBankCardVo vo,CrmTenantYxBankCard card){
        String result=vo.getResult();
        if(card.getStatus().equals(result)){
            return;
        }
        String status="";
        if("1".equals(result)){
            status=YueXiuConstants.ENTRY_CARD_STATUS_IN;
        }else if("2".equals(result)){
            status=YueXiuConstants.ENTRY_CARD_STATUS_IN;
        }else if("3".equals(result)){
            status=YueXiuConstants.ENTRY_CARD_STATUS_FAIL;
        }else if("4".equals(result)){
            status=YueXiuConstants.ENTRY_CARD_STATUS_HAVE;
        }else if("5".equals(result)){
            status=YueXiuConstants.ENTRY_CARD_STATUS_FAIL;
        }else if("6".equals(result)){
            status=YueXiuConstants.ENTRY_CARD_STATUS_NO;
        }
        card.setStatus(result);
        card.setAccountName(vo.getAcctName());
        card.setAccountCode(vo.getAccount());
      /*  //修改电站的开卡状态
        Db.update(" UPDATE `crm_customer_entry` SET sec_card_status=? WHERE  id_code=? AND management_type=?  ",status,card.getIdCode(),card.getManagementType());*/
        //二类卡开通后，后台自动出发进件申请，申请所涉及的字段内容处理如下：
        if ("4".equals(result) && StringUtil.isNotBlank(card.getAccountCode())) { //正式开户成功
            logger.info(">>>>>>>>>>editBankCardStatus ");
            //根据 手机号 和身份证和资方 获取电站
            List<CustomerEntry> entries = entryDao.findEntryByIdCodeVsManagementType(card.getIdCode(), card.getManagementType());
            logger.info(">>>>>>>>>>editBankCardStatus entries.size:{}", entries.size());
            if (entries.size() > 0) {
                for (CustomerEntry entry : entries) {
                    entry.setSecCardStatus(status);
                    entryDao.save(entry);
                }
            }
            DownImg img = new DownImg();
            String url = img.downImg(card.getAccountCode());
            Db.update(" update  crm_tenant_yx_bank_card set status = ? , account_name = ?, account_code = ? " +
                    " ,front_img = ? ,back_img = 'static/img/bank_card_back-yj.png' where id = ?  ",result,vo.getAcctName(),vo.getAccount(),url,card.getId());
        } else if ("6".equals(result)) {
            logger.info(">>>>>>>>>> 销户成功结果返回 ");
            List<CustomerEntry> entries = entryDao.findEntryByIdCodeVsManagementType(card.getIdCode(), card.getManagementType());
            logger.info(">>>>>>>>>>editBankCardStatus entries.size:{}", entries.size());
            if (entries.size() > 0) {
                for (CustomerEntry entry : entries) {
                    entry.setSecCardStatus(status);
                    entryDao.save(entry);
                }
            }
            Db.update(" update  crm_tenant_yx_bank_card set status = ? , account_name = ?, account_code = ? where id = ?  ",result,vo.getAcctName(),vo.getAccount(),card.getId());
        }
    }

    public void updateCorpserno(String corpCommSerno, String status) {
        StringBuffer sb=new StringBuffer();
        sb.append("DELETE FROM crm_tenant_yx_bank_card_corpserno WHERE corp_comm_serno = ? ");
        Db.update(sb.toString(), corpCommSerno);
        StringBuffer sb2=new StringBuffer();
        sb2.append("INSERT INTO `crm_tenant_yx_bank_card_corpserno`(`corp_comm_serno`, `status`, `update_time`) ");
        sb2.append("VALUES (?,?,?) ");
        Db.update(sb2.toString(), corpCommSerno, status, DateUtils.getNowDate());
    }

    public void listDate(LayuiPage<Record> page, Map<String, String> map) {
        User user = UserUtils.getUser();
        String traderId="";
        if(User.USER_TYPE_ADVISOR.equals(user.getUserType())){
            traderId = CrmUtils.getUserRelId(user);
        }else if(User.USER_TYPE_KJ.equals(user.getUserType())){
            CrmTrader trader = traderService.getTraderBuserId(user.getId());
            traderId=trader.getId();
        }
        map.put("traderId",traderId);
        page.setData(tenantYxBankCardDao.selectList(page, map,traderId));
        page.setCount(tenantYxBankCardDao.countList(map,traderId));
    }

    public CrmTenantYxBankCard bankCardDetail(String idCard,String managementType,String partnerId){
        CrmTenantYxBankCard card=tenantYxBankCardDao.getByIdCard(idCard,managementType,partnerId);
        if(card==null){
            throw new IllegalArgumentException("未找到开卡信息!");
        }
        card.setBankName("中国工商银行股份有限公司广州南方支行");
        card.setTssBankNum("102581000353");
        return card;
    }

    public Result initFirstApplyEntry(String powerStationCode){
        CustomerEntry entry=entryDao.findCustomerEntryById(powerStationCode);
        if(!StringUtil.equals(entry.getAuthorization(), CustomerEntryConstants.AUTHORIZATION_SUCCESS)){  //已授权
            throw new IllegalArgumentException("未授权，不可进件!");
        }
        if(!StringUtil.equals(entry.getCredit(), CustomerEntryConstants.CREDIT_APPROVED)){  //预审通过
            throw new IllegalArgumentException("预审未通过，不可进件!");
        }

        if (!StringUtil.equalsAny(entry.getDesignAuditFlag(),CustomerEntryConstants.DESIGN_AUDIT_FLAG_SJSHTG,
                CustomerEntryConstants.DESIGN_AUDIT_FLAG_JJSHZ)) {
            throw new IllegalArgumentException("设计审核通过之后，才可进件!");
        }

        // 第一次进件状态(NEW-待审批、APPROVING - 审批中、APPROVED - 审批通过、REJECTED - 审批拒绝、CLOSED - 取消、APPROVED_RETURN - 退回、CANCEL - 撤回)
        if (!StringUtil.equalsAny(entry.getFirstApplyStatus(), "APPROVING", "APPROVED", "CLOSED")) {
            CrmTenantYxBankCard card=tenantYxBankCardDao.getByIdCard(entry.getIdCode(),entry.getManagementType(),entry.getPartnerId());
            Result result = entryService.accessProjectApply(entry,card,null,null);
            if (!"200".equals(result.getCode())) {
                throw new IllegalArgumentException("进件请求失败；"+result.getErrMsg());
            }
            entryDao.save(entry);
            return Result.ok();
        }
        else {
            return Result.fail("操作失败，当前进件状态：" + YueXiuUtils.tofirstStatusStr(entry.getFirstApplyStatus()));
        }
    }

    //定时任务 获取开卡状态
    @Transactional(rollbackFor = Exception.class)
    public void activityGetOpenCardStatus(){
        logger.info(">>activityGetOpenCardStatus :{} ",DateUtils.getDate());
        StringBuffer sb=new StringBuffer();
        sb.append("SELECT c.id,c.name,c.id_code,c.corp_comm_serno FROM `crm_tenant_yx_bank_card` c WHERE c.status NOT IN ('4','6','10') and partner_id='01' ORDER BY c.status ASC ");

        List<Record> needToGetOpenCardStatus=Db.find(sb.toString());
        logger.info("needToGetOpenCardStatus.size:{}", needToGetOpenCardStatus.size());
//        if(needToGetOpenCardStatus==null || needToGetOpenCardStatus.size()==0){
//           return;
//        }
        Map<String, Object> head = new HashMap<>();
        head.put("serialNumber", UUID.randomUUID().toString());
        head.put("systemId",YueXiuConstants.CLIENT_ID);
        head.put("transactionCode",YueXiuConstants.TRANSACTION_CODE_CARD+YX);
        head.put("transactionTime", DateUtils.formatDate(new Date(),"yyyyMMdd HH:mm:ss"));
        head.put("version",1);
        for(Record r:needToGetOpenCardStatus){
            if(StringUtil.isNotBlank(r.getStr("corp_comm_serno"))){
                try {
                    List<GetStatusVo> needSerno=new ArrayList<>();
                    GetStatusVo vo=new GetStatusVo(r.getStr("corp_comm_serno"));
                    needSerno.add(vo);
                    Map<String, Object> map = new HashMap<>();
                    map.put("body",needSerno);
                    map.put("head",head);
                    logger.info(">>查看开卡状态  activityGetOpenCardStatus json:{}",new Gson().toJson(map));
                    JSONObject jieMap = operatingLeaseService.clientPostZYMap(map, YueXiuConstants.QUERY_BANK_CARD_STATUS_URL);
                    logger.info("查看开卡状态 activityGetOpenCardStatus -------返回结果：{}", jieMap);
                    JSONArray reqMap = jieMap.getJSONArray("body");
                    logger.info(">>>>>>activityGetOpenCardStatus reqMap:{}",reqMap.toJSONString());
                    JSONObject re = reqMap.getJSONObject(0);
                    //type: S-请求成功 E-请求失败
                    if ("S".equals(re.get("type"))) {
                        logger.info(">>>activityGetOpenCardStatus   re:{}",re);
                        YueXueBankCardVo cardVo=JSONObject.parseObject(re.toJSONString(), YueXueBankCardVo.class);
                        //修改开卡状态
                        CrmTenantYxBankCard card=tenantYxBankCardDao.getByCorpCommSerno(cardVo.getBusinessKey());
                        editBankCardStatus2(cardVo,card);
                        saveCard2(card);
                    } else {
                        logger.error("操作失败!失败原因："+re.get("message"));
                    }
                }
                catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }

        // 对操作日志的历史合作方交易单号 进行补充查询
        //获取前一天使日期
        Date newDate = new Date();
        String date = DateUtils.dateChangeDays(newDate, -1,"yyyy-MM-dd");
        String minDate = date+" 00:00:00";

        StringBuffer sb2=new StringBuffer();
        sb2.append("SELECT a.`id_code`, a.`management_type`, a.`corp_comm_serno` ");
        sb2.append("FROM crm_tenant_yx_bank_card_history a ");
        sb2.append("INNER JOIN crm_tenant_yx_bank_card c ");
        sb2.append("ON c.`management_type` = a.`management_type` AND c.`id_code` = a.`id_code` AND c.`status` NOT IN ('2','4') ");
        sb2.append("LEFT JOIN crm_tenant_yx_bank_card_corpserno cc ");
        sb2.append("ON cc.`corp_comm_serno` = a.`corp_comm_serno` AND cc.`status` IN ('2','4','10') ");
        sb2.append("WHERE a.`create_time` > ? AND cc.`corp_comm_serno` IS NULL ");
        sb2.append("AND c.partner_id = '01' ");
        sb2.append("  AND a.`corp_comm_serno` NOT IN ");
        sb2.append("  ( SELECT bc.`corp_comm_serno` FROM crm_tenant_yx_bank_card bc WHERE bc.`status` IN ('6') AND bc.partner_id = '01' ) ");
        sb2.append("GROUP BY a.`id_code`, a.`management_type`, a.`corp_comm_serno` ");
        List<Record> getHistoryList=Db.find(sb2.toString(),minDate);
        logger.info("getHistoryList.size:{}", getHistoryList.size());
        for(Record r:getHistoryList){
            String corpCommSerno = r.getStr("corp_comm_serno");
            if(StringUtil.isNotBlank(corpCommSerno)){
                try {
                    List<GetStatusVo> needSerno=new ArrayList<>();
                    GetStatusVo vo=new GetStatusVo(corpCommSerno);
                    needSerno.add(vo);
                    Map<String, Object> map = new HashMap<>();
                    map.put("body",needSerno);
                    map.put("head",head);
                    logger.info(">>查看开卡状态  activityGetOpenCardStatus getHistoryList json:{}",new Gson().toJson(map));
                    JSONObject jieMap = operatingLeaseService.clientPostZYMap(map, YueXiuConstants.QUERY_BANK_CARD_STATUS_URL);
                    logger.info("查看开卡状态 activityGetOpenCardStatus getHistoryList -------返回结果：{}", jieMap);
                    JSONArray reqMap = jieMap.getJSONArray("body");
                    logger.info(">>>>>>activityGetOpenCardStatus getHistoryList reqMap:{}",reqMap.toJSONString());
                    JSONObject re = reqMap.getJSONObject(0);
                    //type: S-请求成功 E-请求失败
                    if ("S".equals(re.get("type"))) {
                        logger.info(">>>activityGetOpenCardStatus getHistoryList  re:{}",re);
                        YueXueBankCardVo cardVo=JSONObject.parseObject(re.toJSONString(), YueXueBankCardVo.class);
                        //修改开卡状态
                        List<Record> cardList = tenantYxBankCardDao.getListByIdCard(r.getStr("id_code"), r.getStr("management_type"));
                        if (!cardList.isEmpty() && StringUtil.equalsAny(cardVo.getResult(), "2","4","6")) {
                            Record record = cardList.get(0);
                            CrmTenantYxBankCard card = tenantYxBankCardDao.get(record.getStr("id"));
                            card.setCorpCommSerno(corpCommSerno);
                            editBankCardStatus2(cardVo, card);
                            saveCard2(card);
                            String retainId = record.getStr("id"); // 保留id
                            tenantYxBankCardDao.delUnnecessaryData(card.getIdCode(), card.getManagementType(), retainId);
                        }
                        else {
                            updateCorpserno(corpCommSerno, cardVo.getResult());
                        }
                    } else {
                        logger.error("操作失败!失败原因："+re.get("message"));
                    }
                }
                catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }

        // 处理开卡记录重复问题
        StringBuffer sb3 = new StringBuffer();
        sb3.append("SELECT a.`id_code`, a.`management_type` ");
        sb3.append("FROM crm_tenant_yx_bank_card a ");
        sb3.append("WHERE a.status not in('0','6') ");
        sb3.append("AND a.partner_id = '01' ");
        sb3.append("GROUP BY a.`id_code`, a.`management_type` ");
        sb3.append("HAVING COUNT(1) > 1 ");
        List<Record> duplicationList = Db.find(sb3.toString());
        logger.info("cfList.size:{}", duplicationList.size());
        for (Record r : duplicationList) {
            String idCode = r.getStr("id_code");
            String managementType = r.getStr("management_type");
            logger.info("idCode:{}, managementType:{}", idCode, managementType);
            List<Record> cards = tenantYxBankCardDao.getListByIdCard(idCode, managementType);
            if (cards.isEmpty()) {
                continue;
            }
            String retainId = cards.get(0).getStr("id"); // 保留id
            tenantYxBankCardDao.delUnnecessaryData(idCode, managementType, retainId);
        }
    }


    public Result isCancel(String idCode) {
        List<String> cancel = tenantYxBankCardDao.isCancel();
        if (cancel.contains(idCode)){
         return Result.success("true");
        }else {
            return Result.success("false");
        }
    }

}
