package com.unis.crk.mq.sub;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.unis.crk.basic.entity.BasicEnum;
import com.unis.crk.basic.entity.SysParams;
import com.unis.crk.basic.service.IBasicEnumService;
import com.unis.crk.basic.service.ISysParamsService;
import com.unis.crk.common.mapper.BillnonewgjjMapper;
import com.unis.crk.common.service.IBillnonewgjjService;
import com.unis.crk.mq.constant.BizOperateType;
import com.unis.crk.mq.dto.BaseDTO;
import com.unis.crk.mq.dto.UploadCountryDTO;
import com.unis.crk.mq.dto.UploadDTO;
import com.unis.crk.mq.utils.JsonUtils;
import com.unis.crk.utils.FunUtils;
import com.unis.crk.utils.SecureMngr;
import com.unis.crk.utils.SqpMapUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 我的订阅
 *
 * @author ybw
 * @version V1.0
 * @className MySub
 * @date 2024/5/9
 **/
@Component
public class MyMessageListener implements MessageListener {
    private Log log = LogFactory.getLog(this.getClass());
    @Autowired
    private IBillnonewgjjService billnonewgjjService;
    @Autowired
    private IBasicEnumService basicEnumService;
    @Resource
    private BillnonewgjjMapper billnonewgjjMapper;
    @Autowired
    private ISysParamsService sysParamsService;

//    String url = "http://10.2.6.63:49183/service/API/CJCURE/DateUpload";//

    @Override
    public void onMessage(Message message, byte[] bytes) {

        //1、转换为对象
        BaseDTO<com.alibaba.fastjson.JSONObject> baseDTO = JsonUtils.mqMessageToObj(message.getBody());
        //2、业务处理
        switch (baseDTO.getBizType()) {
            case YLRK: //原粮入库业务
                handleYlrk(baseDTO);
                break;
            case YLCK: //原粮出库业务
                handleYlck(baseDTO);
                break;
            case KCBD: //原粮出库业务
                handleKcbd(baseDTO);
                break;
            default:
                log.info("其他业务");
                break;
        }
    }

    /**
     * 原粮入库业务处理
     * @param baseDTO
     */
    private void handleYlrk(BaseDTO<com.alibaba.fastjson.JSONObject> baseDTO)  {
        com.alibaba.fastjson.JSONObject uploadCountryDTO =baseDTO.getData();
        com.alibaba.fastjson.JSONObject returnJson = uploadCountryDTO.getJSONObject("returnJson");
        String dataId = returnJson.getString("dataId"); //主键id
        String unitId = "";
        String unitName = "";
        String bizNo = returnJson.getString("bizNo"); //业务单据号
        //新增
        if(baseDTO.getBizOperateType() == BizOperateType.INSERT  || baseDTO.getBizOperateType() == BizOperateType.UPDATE){
            try {
                String prefix = "14";
                int noLen = 4;
                String sql = " SELECT DISTINCT "+FunUtils.fn_FormatDate(FunUtils.DATE_FORMAT_SHORT, "f.BuildDate")+" as \"cpzRq\",a.unitId as \"unitId\",a.BizNo as \"bizNo\",jsdh as \"jsdh\",kqbm as \"kqbm\",org_name as \"unitName\",a.BuildDate FROM data_crkyw_rmdj_default a inner JOIN  data_crkyw_jsxx_default b on a.BizNo = b.BizNo inner JOIN  data_crkyw_cpz_default f on a.BizNo = f.BizNo inner JOIN  data_crkyw_rkcm_default e on a.BizNo = e.BizNo  INNER JOIN depot_qh"+FunUtils.DataBaseSplitChar+"org_info c on a.UnitID = c.org_id "
                        + " where a.BizNo = '"+bizNo+"'  ";
                List<Map<String, Object>> list = billnonewgjjMapper.findBySql(sql);
                for (Map<String, Object> map : list) {
                    //生成单号
                    unitId = map.get("unitId").toString();
                    unitName = map.get("unitName").toString();
                    String billNo = map.get("bizNo").toString();
                    String cpzRq = map.get("cpzRq").toString();
                    String newValue_rk = billnonewgjjService.createNewNo(prefix, "data_crkyw_rmdj_default".toLowerCase(), unitId, billNo, noLen,cpzRq);
                    System.out.println("入库信息"+newValue_rk);
                    String ret = billnonewgjjService.createRkyw(unitId, billNo,newValue_rk);
                    if (map.get("jsdh") != null) {

                        String jsdh = map.get("jsdh").toString();
                        String kqbm = map.get("kqbm").toString();
                        String newValue_js = billnonewgjjService.createNewNo(kqbm, "data_crkyw_jsxx_default".toLowerCase(), unitId, jsdh, noLen);
                        System.out.println("入库结算信息"+newValue_js);
                        ret = billnonewgjjService.createRkJsyw(unitId, billNo,newValue_js);
                    }

                    if (StringUtils.isNotBlank(billNo)) { //检查是否有从表数据，如果没有则保存
                        list = billnonewgjjMapper.findBySql("SELECT DISTINCT  b.bizno as \"bizno\" FROM data_crkyw_jyxx_flt_001 a  left JOIN data_crkyw_jyxx_default b ON B.DATAID = A.MAINDATAID where b.bizno = '"+billNo+"' ");
                        if (!list.isEmpty()) {
                            System.out.println("检验信息"+newValue_rk);
                            ret = billnonewgjjService.createRkJyyw(unitId, billNo,newValue_rk);
                        }
                    }

                }
        } catch (Exception e) {
            e.printStackTrace();
        }

        }
        if (baseDTO.getBizOperateType() == BizOperateType.DELETE){ //逻辑删除数据
            billnonewgjjService.deleteYwByBizNo(bizNo,"DATA_CRKYW_RKCM_DEFAULT");
        }
        //调用接口装数据保存至指定数据，然后由接口统一报至国家局
        //入库，结算，化验
        JSONArray body = new JSONArray();
        //入库数据
        JSONObject rkJson = new JSONObject();
//        String sql = " SELECT * FROM ods_up_lsrkxxjk_final  where BizNo = '"+bizNo+"'  ";
        String sql = SqpMapUtil.getSql("QUERY_GJJ_RKYW").replace("'BizNo'", "'"+bizNo+"'");
        rkJson.set("ODS_UP_LSRKXXJK",billnonewgjjMapper.findBySql(sql));
        //化验数据
        JSONObject jyJson = new JSONObject();
       // sql = " SELECT * FROM ods_up_lsrkjyxxjk_final  where BizNo = '"+bizNo+"'  ";
        sql = SqpMapUtil.getSql("QUERY_GJJ_RKJYYW").replace("'BizNo'", "'"+bizNo+"'");
        rkJson.set("ODS_UP_LSRKJYXXJK",billnonewgjjMapper.findBySql(sql));
        //结算数据
        JSONObject jsJson = new JSONObject();
//        sql = " SELECT * FROM ods_up_lsrkjsxxjk_final  where BizNo = '"+bizNo+"'  ";
        sql = SqpMapUtil.getSql("QUERY_GJJ_RKJSYW").replace("'BizNo'", "'"+bizNo+"'");
        rkJson.set("ODS_UP_LSRKJSXXJK",billnonewgjjMapper.findBySql(sql));

        body.add(rkJson);
        sendData(unitId, unitName, body);

    }
    /**
     * 原粮出库业务处理
     * @param baseDTO
     */
    private void handleYlck(BaseDTO<com.alibaba.fastjson.JSONObject> baseDTO) {
        com.alibaba.fastjson.JSONObject uploadCountryDTO =baseDTO.getData();
        com.alibaba.fastjson.JSONObject returnJson = uploadCountryDTO.getJSONObject("returnJson");
        String dataId = returnJson.getString("dataId"); //主键id
        String unitId = "";
        String unitName = "";
        String bizNo = returnJson.getString("bizNo"); //业务单据号
        //新增
        if(baseDTO.getBizOperateType() == BizOperateType.INSERT  || baseDTO.getBizOperateType() == BizOperateType.UPDATE) {

            String prefix = "15";
            int noLen = 4;
            String sql = " SELECT DISTINCT a.unitId as \"unitId\",a.BizNo as \"bizNo\",kqbm as \"kqbm\",org_name as \"unitName\",a.BuildDate FROM data_crkyw_ckrmdj_default a INNER JOIN data_crkyw_ckcm_default e on a.bizno = e.bizno  INNER JOIN depot_qh" + FunUtils.DataBaseSplitChar + "org_info c on a.UnitID = c.org_id LEFT JOIN ods_up_lsckxxjk_final ods ON a.BizNo = ods.BizNo  where a.BizNo = '"+bizNo+"' ";
            List<Map<String, Object>> list = billnonewgjjMapper.findBySql(sql);
            int i = 0;
            for (Map<String, Object> map : list) {
                System.out.println(map);
                //生成单号
                 unitId = map.get("unitId").toString();
                unitName = map.get("unitName").toString();
                String billNo = map.get("bizNo").toString();
                String newValue_ck = billnonewgjjService.createNewNo(prefix, "data_crkyw_ckrmdj_default".toLowerCase(), unitId, billNo, noLen);
                System.out.println("出库信息" + newValue_ck);
                String ret = billnonewgjjService.createCkyw(unitId, billNo, newValue_ck);
            }
        }
        if (baseDTO.getBizOperateType() == BizOperateType.DELETE){ //逻辑删除数据
            billnonewgjjService.deleteYwByBizNo(bizNo,"DATA_CRKYW_CKCM_DEFAULT");
        }
        //调用接口装数据保存至指定数据，然后由接口统一报至国家局
        //出库
        JSONArray body = new JSONArray();
        //出库数据
        JSONObject ckJson = new JSONObject();
//        String sql = " SELECT * FROM ods_up_lsckxxjk_final  where BizNo = '"+bizNo+"'  ";
        String sql = SqpMapUtil.getSql("QUERY_GJJ_CKYW").replace("'BizNo'", "'"+bizNo+"'");
        ckJson.set("ODS_UP_LSCKXXJK",billnonewgjjMapper.findBySql(sql));

        body.add(ckJson);
        //发送数据
        sendData(unitId, unitName, body);
    }
    /**
     * 原粮出库业务处理
     * @param baseDTO
     */
    private void handleKcbd(BaseDTO<com.alibaba.fastjson.JSONObject> baseDTO) {
        com.alibaba.fastjson.JSONObject uploadCountryDTO =baseDTO.getData();
        com.alibaba.fastjson.JSONObject returnJson = uploadCountryDTO.getJSONObject("returnJson");
        String dataId = returnJson.getString("dataId"); //主键id
        String unitId = returnJson.getString("unitId");
        String unitName = "";
        String bddh =returnJson.getString("bddh"); //变动单号
        String tableName = "";
        String enumCode = "";
        String bdfs = returnJson.getString("bdfs"); //变动方式
        //新增
        if(baseDTO.getBizOperateType() == BizOperateType.INSERT  || baseDTO.getBizOperateType() == BizOperateType.UPDATE) {

            try {
                String sql = "SELECT DISTINCT	substr(m.enumCode,1,1) as enumCode,a.unitId AS \"unitId\",	a.bddh AS \"bddh\",	ifnull(c.hwdm,'') AS \"hwdm\",kqbm as \"kqbm\",org_name as \"unitName\",	a.BuildDate FROM 	data_kcgl_kcbd_default a left JOIN depot_qh"+FunUtils.DataBaseSplitChar+"basic_warehouse c ON a.hwid = c.warehouse_id  left join  basic_enum m   on a.bdfs=m.enumId   INNER JOIN depot_qh.org_info e on a.UnitID = e.org_id WHERE a.dataId = '"+dataId+"'";
                List<Map<String, Object>> list = billnonewgjjMapper.findBySql(sql);
                if (list.size() == 0){
                    return;
                }
                Map<String,Object> map = list.get(0);
                //生成单号
                unitId = map.get("unitId").toString();
                unitName = map.get("unitName").toString();
                bddh = map.get("bddh").toString();
                enumCode = map.get("enumCode").toString();
                String hwdm = map.get("hwdm").toString(); //货位代码
                String kqbm = map.get("kqbm").toString(); //库区代码
                String prefix = "";
                int noLen = 3;

                    //损益单
                    if (StringUtils.equals("0",enumCode) || StringUtils.equals("1",enumCode)){
                        prefix = hwdm;
                        tableName= "ODS_UP_SYDXXJK_FINAL";
                        String newValue_js = billnonewgjjService.createNewNo(prefix, "data_kcgl_kcbd_default".toLowerCase(), unitId, bddh, noLen);
                        System.out.println("损益单："+newValue_js);
                        String ret = billnonewgjjService.createSydyw(unitId, bddh, newValue_js);
                    }
                    // 倒仓
                    if (StringUtils.equals("2",enumCode) ){
                        noLen = 4;
                        prefix = kqbm;
                        tableName= "ODS_UP_DCXXJK_FINAL";
                        String newValue_js = billnonewgjjService.createNewNo(prefix, "data_kcgl_kcbd_default".toLowerCase(), unitId, bddh, noLen);
                        System.out.println("倒仓信息："+newValue_js);
                        String ret = billnonewgjjService.createDcyw(unitId, bddh,newValue_js,true);
                    }
                    // 性质变化
                    if (StringUtils.equals("3",enumCode) ){
                        prefix = hwdm;
                        tableName= "ODS_UP_LSXZZBDXXJK_FINAL";
                        String newValue_js = billnonewgjjService.createNewNo(prefix, "data_kcgl_kcbd_default".toLowerCase(), unitId, bddh, noLen);
                        System.out.println("性质变动"+newValue_js);
                        String ret = billnonewgjjService.createXzbdyw(unitId, bddh, newValue_js);
                    }
            } catch (Exception e) {
                e.printStackTrace();
            }


        }
        if (baseDTO.getBizOperateType() == BizOperateType.DELETE){ //逻辑删除数据
            BasicEnum basicEnum = basicEnumService.getById(bdfs);
            enumCode = basicEnum.getEnumCode().substring(0,1);
            //删除操作获取表名
            //损益单
            if (StringUtils.equals("0",enumCode) || StringUtils.equals("1",enumCode)){
                tableName= "ODS_UP_SYDXXJK_FINAL";
            }
            // 倒仓
            if (StringUtils.equals("2",enumCode) ){
                tableName= "ODS_UP_DCXXJK_FINAL";
            }
            // 性质变化
            if (StringUtils.equals("3",enumCode) ){
                tableName= "ODS_UP_LSXZZBDXXJK_FINAL";
            }
            billnonewgjjService.deleteYwByBizNo(bddh,tableName);
        }
        //调用接口装数据保存至指定数据，然后由接口统一报至国家局
        //出库
        JSONArray body = new JSONArray();
        //数据
        JSONObject json = new JSONObject();
         String sql = " ";
        if (StringUtils.equals("ODS_UP_SYDXXJK_FINAL",tableName)){ //损益单
            sql = SqpMapUtil.getSql("QUERY_GJJ_SYDYW").replace("'bddh'", "'"+bddh+"'");
        }
        if (StringUtils.equals("ODS_UP_LSXZZBDXXJK_FINAL",tableName)){ //性质变动
            sql = SqpMapUtil.getSql("QUERY_GJJ_XZBDYW").replace("'bddh'", "'"+bddh+"'");
        }
        if (StringUtils.equals("ODS_UP_DCXXJK_FINAL",tableName)){ //倒仓
//            sql = " SELECT * FROM "+tableName+"  where zycx = '"+bddh+"'  ";
            sql = SqpMapUtil.getSql("QUERY_GJJ_DCYW").replace("'zycx'", "'"+bddh+"'");
        }
        json.set(tableName.replaceAll("_FINAL",""),billnonewgjjMapper.findBySql(sql));

        body.add(json);
        //发送数据
        sendData(unitId, unitName, body);
    }

    private void sendData(String unitId, String unitName, JSONArray body) {
        try {
            //获取上报国家局掊地址
            SysParams sysParams = sysParamsService.getById("uploadCountryUtl");
            if (sysParams == null){
                return;
            }
            UploadDTO uploadDTO = new UploadDTO();
            uploadDTO.setId(IdUtil.fastUUID());
            uploadDTO.setVer("1.0");
            uploadDTO.setOrgNo(unitId);
            uploadDTO.setOrgName(unitName);
            uploadDTO.setSendTime(DateUtil.formatDateTime(new Date()));
            String bodyJsonStr = JsonUtils.mqMessageToObj1(JSONUtil.toJsonPrettyStr(body));

            //进行加密
            String bodyStr = SecureMngr.encryptByAES(SecureMngr.AES_KEY, bodyJsonStr);

            uploadDTO.setBody(bodyStr);
            //发送请求

            // 发送post请求，并打印结果，以String类型接收响应结果JSON字符串
            RestTemplate restTemplate = new RestTemplate();
            JSONObject result = restTemplate.postForObject(sysParams.getParamVal(), uploadDTO, JSONObject.class) ;
            System.out.println(result);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
