package com.xy.job;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xy.annotate.RestMappingController;
import com.xy.collections.map.JHashMap;
import com.xy.collections.map.JMap;
import com.xy.device.EnumSimConfig;
import com.xy.dto.MercMsgInfoDto;
import com.xy.dto.be.MercDto;
import com.xy.entity.DeviceSim;
import com.xy.enums.MsgConfigId;
import com.xy.mapper.DeviceSimMapper;
import com.xy.service.MercMsgInfoService;
import com.xy.service.be.MercFeignService;
import com.xy.sys.EnumMercCostMsgConfig;
import com.xy.utils.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 设备流量卡job
 */
@Slf4j
@Component
@AllArgsConstructor
@RestMappingController("test")
public class DeviceSimJob {

    private DeviceSimMapper deviceSimMapper;

    private MercMsgInfoService mercMsgInfoService;

    private MercFeignService mercFeignService;


    /**
     * 设备流量卡过期消息
     *
     * @return
     */
    @XxlJob("deviceSimTimeout")
    public ReturnT<String> deviceSimTimeout() {
        String now = DataTime.getSring();
        String tel = SysDictUtils.getValue(EnumMercCostMsgConfig.Code.CODE.getCode(), EnumMercCostMsgConfig.CUSTOM_TEL.getCode(), String.class);
        String mmiTime = DataTime.getStringAround(0, -1, 0, 0, 0, 0, now);
        //数据逻辑
        FunctionUtils.ParamsResult<Tuple.Tuple4<Integer, JMap<String, Object>, JMap<String, Object>, Integer>, Boolean> datas = tuple -> {
            Integer current = tuple.getV1();
            JMap<String, Object> params = tuple.getV2();
            JMap<String, Object> msg = tuple.getV3();
            Integer workType = tuple.getV4();
            //查询数据
            IPage<Long> longIPage = deviceSimMapper.deviceSimTimeout(Page.of(current, 100), params);
            List<Long> mercIds = longIPage.getRecords();
            if (!Emptys.check(mercIds)) {
                return false;
            }
            List<MercDto.Vo> mercList = R.feignCheckData(mercFeignService.listMerc(new MercDto.ListDTO().setIds(mercIds)));
            Map<Long, MercDto.Vo> mercMap = mercList.stream().collect(Collectors.toMap(MercDto.Vo::getId, m -> m));
            List<Long> cmMercIds = new ArrayList<>();
            List<Long> mxrMercIds = new ArrayList<>();
            //遍历mercMap 区分喵星人、创米商户
            for (Map.Entry<Long, MercDto.Vo> entry : mercMap.entrySet()) {
                Long mercId = entry.getKey();
                String mercCode = entry.getValue().getMercCode();
                if (MercAuthUtils.sendMsgToCM(mercCode)) {
                    cmMercIds.add(mercId);
                } else {
                    mxrMercIds.add(mercId);
                }
            }
            //发送消息
            if (CollUtil.isNotEmpty(mxrMercIds)) {
                MsgUtils.sendMsg(MsgConfigId.FEE_NOTIFY.getId(), mercIds)
                        .official(userInfo -> new MsgUtils.MsgInfo(userInfo.getMpOpenid(), msg))
                        .mxr(userInfo -> new MsgUtils.MsgInfo(String.valueOf(userInfo.getAuthorizeUserId()), msg))
                        .builder();
            }
            //创米商户
            if (CollUtil.isNotEmpty(cmMercIds)) {
                MsgUtils.sendMsg(MsgConfigId.CM_FEE_NOTIFY.getId(), mercIds)
                        .official(userInfo -> new MsgUtils.MsgInfo(userInfo.getMpOpenid(), msg))
                        .mxr(userInfo -> new MsgUtils.MsgInfo(String.valueOf(userInfo.getAuthorizeUserId()), msg))
                        .builder();
            }

            //写入记录
            mercMsgInfoService.save(new MercMsgInfoDto.Save()
                    .setMercId(mercIds)
                    .setType(2)
                    .setWorkType(workType)
            );
            return true;
        };
        //即将过期
        FunctionUtils.NoParamsNoResult timeout1 = () -> {
            int day = SysDictUtils.getValue(EnumSimConfig.Code.CODE.getCode(), EnumSimConfig.N_200.getCode(), Integer.class);
            String end = DataTime.getStringAround(0, 0, day, 0, 0, 0, now);
            JMap<String, Object> map = new JHashMap<String, Object>()
                    .set("mmiTime", mmiTime)
                    .set("workType", 1)
                    .set("begin", now)
                    .set("end", end);
            JMap<String, Object> sendParams = new JHashMap<String, Object>()
                    .set("content", String.format("尊敬的客户，您有%s即将到期，为避免设备停机，请及时续费，客服电话%s", "设备流量卡", tel));
            RecursionUtils.recursion(current -> datas.run(new Tuple.Tuple4<>(current, map, sendParams, 1)));
        };
        //欠费
        FunctionUtils.NoParamsNoResult timeout2 = () -> {
            JMap<String, Object> map = new JHashMap<String, Object>()
                    .set("mmiTime", mmiTime)
                    .set("workType", 2)
                    .set("end", now);
            JMap<String, Object> sendParams = new JHashMap<String, Object>()
                    .set("content", String.format("尊敬的客户，截止%s您的%s已欠费，您的设备将停止交易，客服电话%s", now, "设备流量卡", tel));
            RecursionUtils.recursion(current -> datas.run(new Tuple.Tuple4<>(current, map, sendParams, 2)));
        };
        timeout1.run();
        timeout2.run();
        return ReturnT.SUCCESS;
    }

    /**
     * 流量卡待缴费消息
     *
     * @return
     */
    @GetMapping("test")
    @XxlJob("deviceSimWaitHandle")
    public ReturnT<String> deviceSimWaitHandle() {
        Long count = deviceSimMapper.selectCount(new LambdaQueryWrapper<DeviceSim>().eq(DeviceSim::getWaitHandle, true));
        if (count > 0) {
            MsgUtils.sendMsg(MsgConfigId.SIM_CARD_TO_PAY_NOTIFY.getId())
                    .official(() -> {
                        JMap<String, Object> map = new JHashMap<String, Object>()
                                .set("thing1", "有需要缴费的流量卡")
                                .set("thing5", "有需要缴费的流量卡");
                        return Arrays.asList(new MsgUtils.MsgInfo("oIJ5O5jnmMXg0vRBM3WuASPHJGbE", map));
                    })
                    .builder();
        }
        return ReturnT.SUCCESS;
    }
}
