package com.sifang.modules.customer.Service;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.constant.YueXiuConstants;
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.HuaRongBankCardVo;
import com.sifang.modules.partner.service.HuaRongApiService;
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.utils.img.Base64ToFile;
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.Transactional;

import java.util.List;

/**
 * @title: HuaRongBankCardService
 * @Author Tan
 * @Date: 2024/7/11 16:05
 * @Version 1.0
 */
@Service
public class HuaRongBankCardService extends BaseService {

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

    @Autowired
    private HuaRongApiService huaRongApiService;

    @Autowired
    private TenantYxBankCardDao tenantYxBankCardDao;

    @Autowired
    private CustomerEntryDao entryDao;

    @Transactional(rollbackFor = Exception.class)
    public void activityGetOpenCardStatus(String partnerId) {
        logger.info(">>activityGetOpenCardStatus :{} ", DateUtils.getDate());
        StringBuffer sb = new StringBuffer();
        sb.append("SELECT c.id,c.name,c.id_code,c.management_type ");
        sb.append("FROM `crm_tenant_yx_bank_card` c WHERE c.status = '-1' and c.partner_id='"+partnerId+"' ");
        sb.append("ORDER BY c.status ASC ");
        List<Record> needToGetOpenCardStatus= Db.find(sb.toString());
        logger.info("needToGetOpenCardStatus.size:{}", needToGetOpenCardStatus.size());
        if(needToGetOpenCardStatus.size()>0){
            for(Record r:needToGetOpenCardStatus){
                try {
                    JSONObject jsonObject = huaRongApiService.querySecondCard(partnerId,r.getStr("id_code"),r.getStr("management_type"));
                    if (jsonObject.size()>0) {
                        HuaRongBankCardVo cardVo = JSONObject.parseObject(jsonObject.toJSONString(), HuaRongBankCardVo.class);
                        //修改开卡状态
                        CrmTenantYxBankCard card = tenantYxBankCardDao.getInfoByIdCard(cardVo.getIdCardNo(), partnerId);
                        editBankCardStatus(cardVo,card);
                        saveCard(card);
                    } else {
                        logger.error("操作失败!失败原因："+jsonObject.get("message"));
                    }
                }catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }else{
            logger.error("未查询到需要开卡的记录!");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void editBankCardStatus(HuaRongBankCardVo vo,CrmTenantYxBankCard card) {
        String result = "4";
        String status = YueXiuConstants.ENTRY_CARD_STATUS_HAVE;
        card.setStatus(result);
        card.setAccountName(vo.getName());
        card.setAccountCode(vo.getSecCardNo());
        card.setOpenBankNumber("102331002044");
        card.setOpenBankName(vo.getBank());
        card.setOpeningTime(vo.getOpeningTime());
        card.setWithHolding(vo.getWithHolding());
        //二类卡开通后，后台自动出发进件申请，申请所涉及的字段内容处理如下：
        if (StringUtil.isNotBlank(card.getAccountCode())) { //正式开户成功
            logger.info(">>>>>>>>>>editBankCardStatus ");
            //根据 手机号 和身份证和资方 获取电站
            List<CustomerEntry> entries = entryDao.findHuaRongEntryByIdCodeVsManagementType(card.getIdCode(),
                    card.getManagementType(), card.getPartnerId());
            logger.info(">>>>>>>>>>editBankCardStatus entries.size:{}", entries.size());
            if (entries.size() > 0) {
                for (CustomerEntry entry : entries) {
                    entry.setSecCardStatus(status);
                    entryDao.save(entry);
                }
            }
            if(vo.getImageData() != null){
                String url = Base64ToFile.convertBase64ToFile(vo.getImageData());
                card.setFrontImg(url);
            }
            card.setBackImg("static/img/bank_card_back-yj.png");
        }
    }

    public void saveCard(CrmTenantYxBankCard card) {
        tenantYxBankCardDao.save(card);
        try {
            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 viewBankCardByIdCode(String partnerId, String IdCode) {
        logger.info(">>viewBankCardByIdCode :{} ", DateUtils.getDate());
        StringBuffer sb = new StringBuffer();
        sb.append("SELECT c.id,c.name,c.id_code,c.management_type FROM `crm_tenant_yx_bank_card` c WHERE partner_id="+partnerId+"  AND id_code= "+"'"+IdCode+"'");
        List<Record> needToGetOpenCardStatus= Db.find(sb.toString());
        logger.info("needToGetOpenCardStatus.size:{}", needToGetOpenCardStatus.size());
        if(needToGetOpenCardStatus.size()>0){
            for(Record r:needToGetOpenCardStatus){
                JSONObject jsonObject = huaRongApiService.querySecondCard(partnerId,IdCode,r.getStr("management_type"));
                if (jsonObject.size()>0) {
                    HuaRongBankCardVo cardVo = JSONObject.parseObject(jsonObject.toJSONString(), HuaRongBankCardVo.class);
                    if (StringUtil.isBlank(cardVo.getIdCardNo()) ||
                            StringUtil.isBlank(cardVo.getSecCardNo())) {
                        return Result.fail(cardVo.getDesc());
                    }
                    //修改开卡状态
                    CrmTenantYxBankCard card = tenantYxBankCardDao.getInfoByIdCard(cardVo.getIdCardNo(), partnerId);
                    if ("4".equals(card.getStatus())) {
                        return Result.ok();
                    }
                    editBankCardStatus(cardVo,card);
                    saveCard(card);
                } else {
                    throw new BusinessException("操作失败!失败原因："+jsonObject.get("message"));
                }
            }
        }else{
            throw new BusinessException("未查询到需要开卡的记录!");
        }
        return Result.ok();
    }

}
