package com.kxs.product.biz.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kxs.common.core.exception.GlobalCustomerException;
import com.kxs.product.api.model.KxsGdReport;
import com.kxs.product.api.res.gd.GdSimOrderRes;
import com.kxs.product.biz.constant.enums.GdReportEnum;
import com.kxs.product.biz.constant.enums.ProductErrorTypeEnum;
import com.kxs.product.biz.mapper.KxsGdOrderMapper;
import com.kxs.product.api.model.KxsGdOrder;
import com.kxs.product.biz.mapper.KxsGdReportMapper;
import com.kxs.product.biz.service.KxsGdOrderService;
import com.kxs.product.biz.service.KxsGdService;
import com.kxs.product.biz.util.GdRsaUtils;
import com.kxs.system.api.model.SysLog;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 广电推送订单信息表(KxsGdOrder)表服务实现类
 *
 * @author 系统
 * @since 2024-06-19 12:36:35
 */
@Service("kxsGdOrderService")
@RequiredArgsConstructor
public class KxsGdOrderServiceImpl extends ServiceImpl<KxsGdOrderMapper, KxsGdOrder> implements KxsGdOrderService {

    private final KxsGdService kxsGdService;

    private final KxsGdReportMapper kxsGdReportMapper;

    @Override
    public IPage<KxsGdOrder> getByPage(Page<KxsGdOrder> page, KxsGdOrder param) {

        return baseMapper.selectPage(page, Wrappers.query(param));
    }

    @Override
    public Boolean toAct(Integer id) {

        KxsGdOrder order = getById(id);
        Optional.ofNullable(order).orElseThrow(() -> new GlobalCustomerException(ProductErrorTypeEnum.DATA_EMPTY.getDescription()));
        KxsGdReport gdReport = kxsGdReportMapper.selectOne(Wrappers.<KxsGdReport>lambdaQuery()
                .eq(KxsGdReport::getGdMobile, order.getGdMobile())
                .eq(KxsGdReport::getStatus, GdReportEnum.REPORT.getType())
                .eq(KxsGdReport::getIsCheck, GdReportEnum.CHECK_NO.getType()));
        Optional.ofNullable(gdReport).orElseThrow(() -> new GlobalCustomerException("广电报备数据未找到"));

        kxsGdService.toSendMq(order, gdReport.getGdSn());

        gdReport.setIsCheck(GdReportEnum.CHECK_SUC.getType());
        kxsGdReportMapper.updateById(gdReport);

        return Boolean.TRUE;
    }


    @Override
    public Boolean onlineSimOrder(List<String> orderNos) {

        List<GdSimOrderRes> list = kxsGdService.onlineSimOrder(orderNos);
        for (GdSimOrderRes res : list) {
            KxsGdOrder kxsGdOrder = this.getOne(Wrappers.<KxsGdOrder>lambdaQuery().eq(KxsGdOrder::getOrderNo, res.getOrderNo()));
            if(kxsGdOrder == null){
                kxsGdOrder = new KxsGdOrder();
            }
            kxsGdOrder.setIccid(res.getIccid());
            kxsGdOrder.setFirstRechargeAmount(new BigDecimal(res.getFirstRechargeAmount()));
            kxsGdOrder.setProductName(res.getProductName());
            kxsGdOrder.setProvince(res.getProvince());
            kxsGdOrder.setCity(res.getCity());
            kxsGdOrder.setUserName(res.getUserName());
            kxsGdOrder.setGdMobile(res.getMobile());
            kxsGdOrder.setOrderNo(res.getOrderNo());
            kxsGdOrder.setStatus(Integer.valueOf(res.getStatus()));
            kxsGdOrder.setIdcardNo(res.getIdcardNo());
            kxsGdOrder.setReceiveName(res.getReceiveName());
            kxsGdOrder.setReceiveMobile(res.getReceiveMobile());
            kxsGdOrder.setAddress(res.getReceiveAddress());
            kxsGdOrder.setAddressDetail(res.getReceiveAddressDetail());
            kxsGdOrder.setCreateTime(LocalDateTimeUtil.parse(res.getCreateTime(), DatePattern.NORM_DATETIME_PATTERN));
            this.saveOrUpdate(kxsGdOrder);
            if("6".equals(res.getStatus())){
                KxsGdReport kxsGdReport = kxsGdReportMapper.selectOne(Wrappers.<KxsGdReport>lambdaQuery()
                        .eq(KxsGdReport::getStatus, GdReportEnum.REPORT.getType())
                        .eq(KxsGdReport::getIsCheck, GdReportEnum.CHECK_NO.getType())
                        .eq(KxsGdReport::getGdMobile, kxsGdOrder.getGdMobile()));
                if (kxsGdReport == null) {
                    continue;
                }
                kxsGdReport.setIsCheck(GdReportEnum.CHECK_SUC.getType());
                kxsGdReportMapper.updateById(kxsGdReport);
                kxsGdService.toSendMq(kxsGdOrder, kxsGdReport.getGdSn());
            }
        }
        return Boolean.TRUE;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void acceptGdActData(Map<String, Object> param) {

        JSONArray dataList = kxsGdService.acceptGdActData(param);

        for (Object obj : dataList) {
            JSONObject orderData = JSON.parseObject(obj.toString());
            //订单信息
            if("1".equals(param.get("type").toString())){

                KxsGdOrder kxsGdOrder = this.getOne(Wrappers.<KxsGdOrder>lambdaQuery().eq(KxsGdOrder::getOrderNo, orderData.getString("orderNo")));
                if(kxsGdOrder == null){
                    kxsGdOrder = new KxsGdOrder();
                }
                kxsGdOrder.setIccid(orderData.getString("iccid"));
                kxsGdOrder.setFirstRechargeAmount(new BigDecimal(orderData.getString("firstRechargeAmount")));
                kxsGdOrder.setProductName(orderData.getString("productName"));
                kxsGdOrder.setProvince(orderData.getString("province"));
                kxsGdOrder.setCity(orderData.getString("city"));
                kxsGdOrder.setUserName(orderData.getString("userName"));
                kxsGdOrder.setGdMobile(orderData.getString("mobile"));
                kxsGdOrder.setOrderNo(orderData.getString("orderNo"));
                kxsGdOrder.setStatus(orderData.getInteger("status"));

                kxsGdOrder.setIdcardNo(orderData.getString("idcardNo"));
                kxsGdOrder.setReceiveName(orderData.getString("receiveName"));
                kxsGdOrder.setReceiveMobile(orderData.getString("receiveMobile"));
                kxsGdOrder.setAddress(orderData.getString("receiveAddress"));
                kxsGdOrder.setAddressDetail(orderData.getString("receiveAddressDetail"));
                kxsGdOrder.setCreateTime(LocalDateTimeUtil.parse(orderData.getString("createTime"), DatePattern.NORM_DATETIME_PATTERN));

                this.saveOrUpdate(kxsGdOrder, Wrappers.<KxsGdOrder>lambdaQuery().eq(KxsGdOrder::getGdMobile, orderData.getString("mobile")));
            }
            //激活状态
            if("2".equals(param.get("type").toString())){
                String orderNo = orderData.getString("orderNo");
                //1 订单生成2 订单正在运行3 待发货4 配送中5 订单成功结束6 已激活成功11 办理失败12 拒签13 订单取消中14 订单取消
                String status = orderData.getString("status");
                if(StrUtil.isBlank(status) || StrUtil.isBlank(orderNo)){
                    continue;
                }
                KxsGdOrder kxsGdOrder = this.getOne(Wrappers.<KxsGdOrder>lambdaQuery().eq(KxsGdOrder::getOrderNo, orderNo));
                if (kxsGdOrder == null) {
                    continue;
                }
                kxsGdOrder.setErpName(orderData.getString("logisticsCompany"));
                kxsGdOrder.setErpNo(orderData.getString("logisticsNo"));
                kxsGdOrder.setStatus(Integer.valueOf(status));
                this.updateById(kxsGdOrder);
                //激活成功
                if("6".equals(status)){
                    KxsGdReport kxsGdReport = kxsGdReportMapper.selectOne(Wrappers.<KxsGdReport>lambdaQuery()
                            .eq(KxsGdReport::getStatus, GdReportEnum.REPORT.getType())
                            .eq(KxsGdReport::getIsCheck, GdReportEnum.CHECK_NO.getType())
                            .eq(KxsGdReport::getPutMobile, kxsGdOrder.getReceiveMobile())
                            .eq(KxsGdReport::getGdMobile, kxsGdOrder.getGdMobile()));
                    if (kxsGdReport == null) {
                        continue;
                    }
                    kxsGdReport.setIsCheck(GdReportEnum.CHECK_SUC.getType());
                    kxsGdReportMapper.updateById(kxsGdReport);
                    kxsGdService.toSendMq(kxsGdOrder, kxsGdReport.getGdSn());
                }

            }
        }
    }

}

