package com.pj.task;

import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.pj.api.client.async_server.AsyncServerInterface;
import com.pj.api.client.level_one_server.LevelOneServerInterface;
import com.pj.api.client.transport.TransportInterface;
import com.pj.api.consts.FeignFactory;
import com.pj.api.dto.*;
import com.pj.common.core.exception.ServiceException;
import com.pj.dto.DataDto;
import com.pj.enummj.DataType;
import com.pj.enummj.FinishStatus;
import com.pj.ht_border_buy_goods_list.HtBorderBuyGoodsList;
import com.pj.ht_border_buy_goods_list.HtBorderBuyGoodsListMapper;
import com.pj.ht_borders_list.HtBordersList;
import com.pj.ht_borders_list.HtBordersListMapper;
import com.pj.ht_byte.HtByte;
import com.pj.ht_byte.HtByteMapper;
import com.pj.ht_import_declare_people.HtImportDeclarePeople;
import com.pj.ht_import_declare_people.HtImportDeclarePeopleMapper;
import com.pj.ht_pass_card_record.HtPassCardRecord;
import com.pj.ht_pass_card_record.HtPassCardRecordMapper;
import com.pj.ht_sell_goods_list.HtSellGoodsList;
import com.pj.ht_sell_goods_list.HtSellGoodsListMapper;
import com.pj.ht_trade_settlement.HtTradeSettlement;
import com.pj.ht_trade_settlement.HtTradeSettlementMapper;
import com.pj.project4sp.SP;
import com.pj.rabbitmq.RabbitMQ;
import com.pj.utils.ht.AESUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * @Author Mechrevo
 * @Date 2023 08 27 09 57
 **/
@Configuration
@EnableScheduling
@Transactional(rollbackFor = Exception.class)
public class HtByteTask {

    /**
     * 航通字节mapper
     */
    @Autowired
    private HtByteMapper htByteMapper;

    /**
     * 交易结算信息
     */
    @Autowired
    private HtImportDeclarePeopleMapper htImportDeclarePeopleMapper;
    /**
     * 放行记录（过卡记录）
     */
    @Autowired
    private HtPassCardRecordMapper htPassCardRecordMapper;
    /**
     * 方法抽取
     */
    @Autowired
    private MethodHtByteTask methodHtByteTask;
    /**
     * 交易结算信息
     */
    @Autowired
    private HtTradeSettlementMapper htTradeSettlementMapper;
    /**
     * 边民购买记录(主表:ht_trade_settlement)
     */
    @Autowired
    private HtBordersListMapper htBordersListMapper;
    /**
     * 边民购买商品信息表(主表:ht_trade_settlement)
     */
    @Autowired
    private HtBorderBuyGoodsListMapper htBorderBuyGoodsListMapper;
    /**
     * 商铺卖货物信息表(主表:ht_trade_settlement)
     */
    @Autowired
    private HtSellGoodsListMapper htSellGoodsListMapper;

    /**
     * 启动定时任务
     * <p>
     * * 报文类型
     * * 001=边民备案
     * * 002=商铺备案
     * * 003=边民互助组备案
     * * 004=边民合作社备案
     * * 005=商品基础信息
     * * 006=交易结算信息
     * * 007=放行记录（过卡记录）
     */
    @Scheduled(cron = "*/9 * * * * ?")  // 测试阶段,每9秒扫描一次
    private void htByteTask() {
        /*  测试mq */
//        OrderDto orderDtoById = levelOneServerInterface.getOrderDtoById(8833342005355478419L);
//        asyncServerInterface.sendLevelOneOrderDto(orderDtoById, DataType.DATA_TYPE_ONE.getCode());
        /*  测试mq */
        //扫描表内是否有待处理任务
        List<HtByte> byteList = htByteMapper.selectList(new LambdaQueryWrapper<HtByte>().eq(HtByte::getFinishStatus, FinishStatus.FINISH_STATUS_ZERO.getCode()));
        //判断是否有任务,没有则返回
        if (byteList.size() == 0) {
            System.out.println("\n  ---  暂无待处理任务。" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\n");
            return;
        }
        //执行任务处理流程
        byteList.forEach(item -> {
            //对象转换
            DataDto dataDto = JSONObject.parseObject(item.getBody(), DataDto.class);
            //数据解析
            String body = AESUtil.decryptCBC(dataDto.getData(), RabbitMQ.ACC_KEY);
            //数据处理完成状态
            boolean flag = false;
            // 根据类型匹配对象
            switch (dataDto.getDataType()) {
                case "001":
                    //对象转换
                    PeopleDto peopleDto = JSONObject.parseObject(body, PeopleDto.class);

                    //根据其内的身份证,有则新增,无则修改???
                    flag = FeignFactory.levelOneServerInterface.peopleDto(peopleDto);
                    methodHtByteTask.updateHtByteInfo(flag, item, dataDto);
                    if (!flag) {
                        System.out.println("\n边民信息处理失败。 messageId = " + item.getMessageId() + "\n");
                    } else {
                        System.out.println("\n边民信息处理成功。 messageId = " + item.getMessageId() + "\n");
                    }
                    break;
                case "002":
                    //商铺备案
                    ShopDto shopDto = JSONObject.parseObject(body, ShopDto.class);
                    //保存
                    flag = FeignFactory.levelOneServerInterface.shopDto(shopDto);
                    methodHtByteTask.updateHtByteInfo(flag, item, dataDto);
                    if (!flag) {
                        System.out.println("\n店铺信息处理失败。 messageId = " + item.getMessageId() + "\n");
                    } else {
                        System.out.println("\n店铺信息处理完成。 messageId = " + item.getMessageId() + "\n");
                    }
                    break;
                case "003":
                    //边民互助组备案
                    GroupDto groupDto = JSONObject.parseObject(body, GroupDto.class);
                    //保存
                    flag = FeignFactory.levelOneServerInterface.groupDto(groupDto);
                    methodHtByteTask.updateHtByteInfo(flag, item, dataDto);
                    if (!flag) {
                        System.out.println("\n互助组信息处理失败。 messageId = " + item.getMessageId() + "\n");
                    } else {
                        System.out.println("\n互助组信息处理完成。 messageId = " + item.getMessageId() + "\n");
                    }
                    break;
                case "004":
                    //边民合作社备案
                    CooperativeDto cooperativeDto = JSONObject.parseObject(body, CooperativeDto.class);
                    //保存
                    flag = FeignFactory.levelOneServerInterface.cooperativeDto(cooperativeDto);
                    methodHtByteTask.updateHtByteInfo(flag, item, dataDto);
                    if (!flag) {
                        System.out.println("\n边民合作社信息处理失败。 messageId = " + item.getMessageId() + "\n");
                    } else {
                        System.out.println("\n边民合作社信息处理完成。 messageId = " + item.getMessageId() + "\n");
                    }
                    break;
                case "005":
                    //商品基础信息
                    GoodsDto goodsDto = JSONObject.parseObject(body, GoodsDto.class);
                    //保存
                    flag = FeignFactory.levelOneServerInterface.goodsDto(goodsDto);
                    methodHtByteTask.updateHtByteInfo(flag, item, dataDto);
                    if (!flag) {
                        System.out.println("\n海关监管商品信息处理失败。 messageId = " + item.getMessageId() + "\n");
                    } else {
                        System.out.println("\n海关监管商品信息处理完成。 messageId = " + item.getMessageId() + "\n");
                    }
                    break;
                case "006":
                    //交易结算信息
                    HtTradeSettlement importDeclarePeople = JSONObject.parseObject(body, HtTradeSettlement.class);
                    if (importDeclarePeople==null||!importDeclarePeople.getIEFlag().toLowerCase().contains("i")) {
                        StaticLog.info("出口商品，暂时忽略:{}", body);
                        break;
                    }
                    importDeclarePeople.setFinishStatus(FinishStatus.FINISH_STATUS_ZERO.getCode()); // 默认待处理
                    importDeclarePeople.setCreateTime(new Date());
                    //保存
                    int insert = htTradeSettlementMapper.insert(importDeclarePeople);
                    long primarykey = SP.publicMapper.getPrimarykey();
                    if (insert == 1) {
                        //购买边民列表
                        List<HtBordersList> bordersLists = JSON.parseArray(importDeclarePeople.getBordersList(), HtBordersList.class);
                        //边民购买商品列表
                        List<HtBorderBuyGoodsList> buyGoodsList = JSON.parseArray(importDeclarePeople.getBorderBuyGoodsList(), HtBorderBuyGoodsList.class);
                        //商铺卖货物列表
                        List<HtSellGoodsList> htSellGoodsList = JSON.parseArray(importDeclarePeople.getSellGoodsList(), HtSellGoodsList.class);
                        //航通关联主键
                        String platSeqNo = importDeclarePeople.getPlatSeqNo();
                        //保存购买边民
                        List<BordersListDto> bordersListDtoList = new ArrayList<>();
                        if (bordersLists.size() > 0) {
                            bordersLists.forEach(t -> {
//                                t.setCreateTime(new Date());
//                                t.setFinishStatus(FinishStatus.FINISH_STATUS_ZERO.getCode());
//                                htBordersListMapper.insert(t);
                                BordersListDto bordersListDto = new BordersListDto();
                                BeanUtils.copyProperties(t, bordersListDto);
                                bordersListDtoList.add(bordersListDto);
                            });
                            /**
                             * 接收订单推送消息，边民进行交易确认，支付申请，刷脸认证，系统发起进行交易
                             */
                            List<HtBordersList> htBordersLists = htBordersListMapper.selectList(new LambdaQueryWrapper<HtBordersList>().eq(HtBordersList::getPlatSeqNo, platSeqNo));
                            methodHtByteTask.sendMessageToPeople(htBordersLists);
                        }
                        //保存边民购买商品
                        List<BorderBuyGoodsListDto> borderBuyGoodsListDtoList = new ArrayList<>();
                        if (buyGoodsList.size() > 0) {
                            buyGoodsList.forEach(t -> {
//                                t.setCreateTime(new Date());
//                                t.setFinishStatus(FinishStatus.FINISH_STATUS_ZERO.getCode());
//                                htBorderBuyGoodsListMapper.insert(t);
                                BorderBuyGoodsListDto borderBuyGoodsListDto = new BorderBuyGoodsListDto();
                                BeanUtils.copyProperties(t, borderBuyGoodsListDto);
                                borderBuyGoodsListDtoList.add(borderBuyGoodsListDto);
                            });
                            // ???
                        }
                        //保存商铺卖货物
                        List<SellGoodsListDto> sellGoodsListDtoList = new ArrayList<>();
                        if (htSellGoodsList.size() > 0) {
                            htSellGoodsList.forEach(t -> {
//                                t.setCreateTime(new Date());
//                                t.setFinishStatus(FinishStatus.FINISH_STATUS_ZERO.getCode());
//                                htSellGoodsListMapper.insert(t);
                                SellGoodsListDto sellGoodsListDto = new SellGoodsListDto();
                                BeanUtils.copyProperties(t, sellGoodsListDto);
                                sellGoodsListDtoList.add(sellGoodsListDto);
                            });
                            // ???
                        }
                        //保存航通监听记录
                        methodHtByteTask.updateHtByteInfo(true, item, dataDto);
                        TradeSettlementDto tradeSettlementDto = new TradeSettlementDto();
                        BeanUtils.copyProperties(importDeclarePeople, tradeSettlementDto);
                        tradeSettlementDto.setId(primarykey);
                        tradeSettlementDto.setBordersListDtoList(bordersListDtoList);
                        tradeSettlementDto.setBorderBuyGoodsListDtoList(borderBuyGoodsListDtoList);
                        boolean b = FeignFactory.levelOneServerInterface.tradeSettlementDto(tradeSettlementDto);
                        if (!b) throw new ServiceException("添加错误;");
                        System.out.println("\n交易结算信息处理成功。 messageId = " + item.getMessageId() + "\n");
                        break;
                    }
                    //保存航通监听记录
                    methodHtByteTask.updateHtByteInfo(false, item, dataDto);
                    System.out.println("\n交易结算信息处理失败。 messageId = " + item.getMessageId() + "\n");
                    break;
                case "007":
                    //放行记录（过卡记录）
                    HtPassCardRecord htPassCardRecord = JSONObject.parseObject(body, HtPassCardRecord.class);
                    htPassCardRecord.setFinishStatus(FinishStatus.FINISH_STATUS_ZERO.getCode()); // 默认待处理
                    htPassCardRecord.setCreateTime(new Date());
                    //保存
                    int insert1 = htPassCardRecordMapper.insert(htPassCardRecord);
                    methodHtByteTask.updateHtByteInfo(true, item, dataDto);
                    if (insert1 == 1) {
                        System.out.println("\n放行记录（过卡记录）信息处理成功。 messageId = " + item.getMessageId() + "\n");
                    } else {
                        System.out.println("\n放行记录（过卡记录）信息处理失败。 messageId = " + item.getMessageId() + "\n");
                    }

                    //系统接收到航通过卡记录且卡口类型为'3卡'：车辆已出一级市场, 修改相对应的一级市场订单状态
                    if("3卡".equals(htPassCardRecord.getChannelType())) {
                        FeignFactory.levelOneServerInterface.orderFinish(htPassCardRecord.getBillCode());
                    }

                    break;
                case "008":
                    //进口申报单边民确认
                    HtImportDeclarePeople htImportDeclarePeople = JSONObject.parseObject(body, HtImportDeclarePeople.class);
                    htImportDeclarePeople.setFinishStatus(FinishStatus.FINISH_STATUS_ZERO.getCode());
                    htImportDeclarePeople.setCreateTime(new Date());
                    int insert2 = htImportDeclarePeopleMapper.insert(htImportDeclarePeople);
                    methodHtByteTask.updateHtByteInfo(insert2 == 1, item, dataDto);
                    if (insert2 == 1) {
                        System.out.println("\n进口申报单边民确认信息处理成功。 messageId = " + item.getMessageId() + "\n");
                    } else {
                        System.out.println("\n进口申报单边民确认信息处理失败。 messageId = " + item.getMessageId() + "\n");
                    }
                    break;
                default:
                    throw new ServiceException("类型错误。");
            }
        });

    }

}
