package com.hzya.frame.seeyon.cbs8.service.impl;

import cn.hutool.core.map.MapBuilder;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.hzya.frame.basedao.service.impl.BaseService;
import com.hzya.frame.seeyon.cbs8.dao.ICbsLogDao;
import com.hzya.frame.seeyon.cbs8.entity.CbsLogEntity;
import com.hzya.frame.seeyon.cbs8.entity.PaymentEntity;
import com.hzya.frame.seeyon.cbs8.service.ICbsLogService;
import com.hzya.frame.seeyon.util.OAPayState;
import com.hzya.frame.seeyon.util.OARestUtil;
import com.hzya.frame.stringutil.StringUtil;
import com.hzya.frame.sysnew.application.entity.SysExtensionApiEntity;
import com.hzya.frame.web.exception.BaseSystemException;
import org.apache.commons.collections.CollectionUtils;
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 java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description cbs8支付日志
 * @Author xiangerlin
 * @Date 2024/6/14 17:22
 **/
@Service(value = "CbsLogServiceImpl")
public class CbsLogServiceImpl extends BaseService<CbsLogEntity,String> implements ICbsLogService {


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

    private ICbsLogDao cbsLogDao;
    @Value("${OA.data_source_code:}")
    private String oa_data_source_code;
    @Autowired
    public void setCbsLogDao(ICbsLogDao cbsLogDao) {
        this.cbsLogDao = cbsLogDao;
        this.dao = cbsLogDao;
    }
    @Autowired
    private OARestUtil restUtil;

    /**
     * 查询支付中的数据
     *
     * @param logEntity
     * @return
     */
    @DS("#logEntity.dataSourceCode")
    @Override
    public List<CbsLogEntity> queryInPayment(CbsLogEntity logEntity) {
        List<CbsLogEntity> logList = cbsLogDao.queryList(logEntity, "CbsLogEntity_list_base_in_payment");
        return logList;
    }

    /**
     * 保存日志，通过rest接口的形式
     *
     * @param cbsLogEntity
     */
    @Override
    public void saveLog(CbsLogEntity cbsLogEntity) {
        String oa_id = StringUtil.nullConvert(cbsLogEntity.getOa_id());
        String bill_code = StringUtil.nullConvert(cbsLogEntity.getBill_code());
        String tab_name_en = StringUtil.nullConvert(cbsLogEntity.getTab_name_en());
        String tab_name_ch = StringUtil.nullConvert(cbsLogEntity.getTab_name_ch());
        String pay_state = StringUtil.nullConvert(cbsLogEntity.getPay_state());
        String message = StringUtil.nullConvert(cbsLogEntity.getMessage());
        String apply_state = StringUtil.nullConvert(cbsLogEntity.getApply_state());
        String successed = StringUtil.nullConvert(cbsLogEntity.getSuccessed());
        String title = StringUtil.nullConvert(cbsLogEntity.getTitle());
        String pay_company = StringUtil.nullConvert(cbsLogEntity.getPay_company());
        String payee = StringUtil.nullConvert(cbsLogEntity.getPayee());
        String amount = StringUtil.nullConvert(cbsLogEntity.getAmount());
        String cbs_apply_code = StringUtil.nullConvert(cbsLogEntity.getCbs_apply_code());
        //根据oaid判断是否在日志表中存在，如果存在，则更新，如果不存在，则新增
        CbsLogEntity cbsLogEntityResend=new CbsLogEntity();
        cbsLogEntityResend.setOa_id(cbsLogEntity.getOa_id());
        cbsLogEntityResend.setDataSourceCode(oa_data_source_code);
        List<CbsLogEntity> queryList = query(cbsLogEntityResend);
        if(CollectionUtils.isEmpty(queryList)){
            String data = StrUtil.format(getXmlTemplate(),title,pay_company,payee,amount,cbs_apply_code,bill_code,oa_id,tab_name_ch,tab_name_en,pay_state,message,apply_state,successed);
            Map<String, String> headerMap = MapBuilder.<String, String>create(true)
                    .put("apiCode", "8000240007")
                    .put("publicKey","ZJYAorA7JuRDfrVjywcx78BFcqlLwthgXNC65TXxxQMUHuxCe7eDIk+3zDUT+v578prj")//发送者
                    .put("secretKey","a54vt9Wx7gdBig+4JCkZ/lISIIL2m4ZEyZkXtW0uQVBDHS+V4SVgT6xhNblacri/j3JzOP8MtA1LSGvL+2BWG8c/o7DKi92S4mr3zcGearA=")//发送者
                    .put("appId","800024")
                    .build();
            JSONObject paramsTemplate = new JSONObject();
            paramsTemplate.put("loginName", "hzya_rest");
            paramsTemplate.put("dataXml", data);
            String params = JSONObject.toJSONString(paramsTemplate);
            logger.info("保存支付申请日志到OA底表请求参数:{}",params);
            String body = HttpRequest.post("http://127.0.0.1:9999/kangarooDataCenterV3/entranceController/externalCallInterface").addHeaders(headerMap).body(params).timeout(60000).execute().body();
            logger.info("保存支付申请日志到OA底表响应参数:{}",body);
        }else{
            for (CbsLogEntity logEntity : queryList) {
                logEntity.setPay_state(pay_state);
                logEntity.setMessage(message);
                logEntity.setApply_state(apply_state);
                logEntity.setSuccessed(successed);
                logEntity.setBill_code(cbsLogEntity.getBill_code());
                logEntity.setDataSourceCode(oa_data_source_code);
                try {
                    update(logEntity);
                }catch (Exception e){
                    e.printStackTrace();
                    logger.error("更新");
                }
            }
        }
    }

    /**
     * 补推，从自己开发的页面或者APIpost
     * 需要传oa表单id和表单编号
     *
     * @param entity
     */
    @Override
    public void retry(CbsLogEntity entity) {
        PaymentEntity paymentEntity = new PaymentEntity();
        paymentEntity.setOaId(entity.getOa_id());
        paymentEntity.setReferenceNum(entity.getBill_code());
        CbsLogEntity logEntity = new CbsLogEntity();
        logEntity.setId(entity.getId());
        logEntity = cbsLogDao.queryOne(logEntity);
        String pay_state = logEntity.getPay_state();
        if (OAPayState.h.getValue().equals(pay_state)
                || OAPayState.three.getValue().equals(pay_state)
                || OAPayState.k.getValue().equals(pay_state)
                || "推送失败".equals(pay_state)){
            //todo 调用重试方法
        }else {
            throw new BaseSystemException("只允许补推支付失败的记录");
        }
    }

    /**
     * 补推，从OA页面
     * 只需要传日志表id就行
     *
     * @param jsonObject
     */
    @Override
    public void resend(JSONObject jsonObject) {
        if (null != jsonObject && StrUtil.isNotEmpty(jsonObject.getString("id"))){
            String id = jsonObject.getString("id");
            CbsLogEntity cbsLogEntity = new CbsLogEntity();
            cbsLogEntity.setId(id);
            cbsLogEntity =cbsLogDao.queryOne(cbsLogEntity);
            if (null != cbsLogEntity && StrUtil.isNotEmpty(cbsLogEntity.getOa_id()) && StrUtil.isNotEmpty(cbsLogEntity.getBill_code())){
                retry(cbsLogEntity);
            }
        }
    }

    /**
     * 获取token
     *
     * @param entity
     * @return
     */
    @Override
    public SysExtensionApiEntity getTokenExt(SysExtensionApiEntity entity) {
        String token = restUtil.getToken("hzya_rest", "8000240000");
        Map<String, String> headers = entity.getHeaders();
        if (null == headers){
            headers = new HashMap<>();
        }
        headers.put("token",token);
        return entity;
    }

    /**
     * 更新日志
     *
     * @param logEntity
     */
    @DS("#logEntity.dataSourceCode")
    @Override
    public void updateLog(CbsLogEntity logEntity) {
        cbsLogDao.update(logEntity);
    }

    //获取xml模板
    private String getXmlTemplate(){
        return "<forms  version=\"2.1\"><formExport><summary  id=\"9195604394844442459\" name=\"formmain_0232\"/><definitions><column  id=\"field0002\" type=\"0\" name=\"流程标题\" isNullable=\"false\" length=\"100\"/><column  id=\"field0003\" type=\"0\" name=\"付款主体公司\" isNullable=\"false\" length=\"100\"/><column  id=\"field0004\" type=\"0\" name=\"收款人\" isNullable=\"false\" length=\"100\"/><column  id=\"field0019\" type=\"4\" name=\"金额\" isNullable=\"false\" length=\"20\"/><column  id=\"field0005\" type=\"0\" name=\"CBS支付申请单号\" isNullable=\"false\" length=\"100\"/><column  id=\"field0006\" type=\"0\" name=\"OA单据编号\" isNullable=\"false\" length=\"100\"/><column  id=\"field0007\" type=\"0\" name=\"OA单据ID\" isNullable=\"false\" length=\"100\"/><column  id=\"field0008\" type=\"0\" name=\"OA中文表名\" isNullable=\"false\" length=\"100\"/><column  id=\"field0009\" type=\"0\" name=\"OA数据库表名\" isNullable=\"false\" length=\"100\"/><column  id=\"field0010\" type=\"0\" name=\"支付状态\" isNullable=\"false\" length=\"100\"/><column  id=\"field0011\" type=\"0\" name=\"支付信息\" isNullable=\"false\" length=\"100\"/><column  id=\"field0012\" type=\"0\" name=\"支付申请状态\" isNullable=\"false\" length=\"100\"/><column  id=\"field0014\" type=\"0\" name=\"成功标记\" isNullable=\"false\" length=\"100\"/></definitions><values><column  name=\"流程标题\"><value><![CDATA[{}]]></value></column><column  name=\"付款主体公司\"><value><![CDATA[{}]]></value></column><column  name=\"收款人\"><value><![CDATA[{}]]></value></column><column  name=\"金额\"><value><![CDATA[{}]]></value></column><column  name=\"CBS支付申请单号\"><value><![CDATA[{}]]></value></column><column  name=\"OA单据编号\"><value><![CDATA[{}]]></value></column><column  name=\"OA单据ID\"><value><![CDATA[{}]]></value></column><column  name=\"OA中文表名\"><value><![CDATA[{}]]></value></column><column  name=\"OA数据库表名\"><value><![CDATA[{}]]></value></column><column  name=\"支付状态\"><value><![CDATA[{}]]></value></column><column  name=\"支付信息\"><value><![CDATA[{}]]></value></column><column  name=\"支付申请状态\"><value><![CDATA[{}]]></value></column><column  name=\"成功标记\"><value><![CDATA[{}]]></value></column></values><subForms/></formExport></forms>";
    }
}
