package com.jeequan.jeepay.thirdparty.service.wxchannel;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.db.entity.MchVideoAuthEntity;
import com.jeequan.jeepay.db.entity.MchVideoCacheEntity;
import com.jeequan.jeepay.service.impl.MchVideoAuthService;
import com.jeequan.jeepay.service.impl.MchVideoCacheService;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;

@Slf4j
@Service
public class WechatChannelService {

    private static final String DOMAIN = "http://public.hxjpayment.cn:9996";

    private static final String CREATE_TASK = DOMAIN + "/user/create_import_task";

    private static final String QUERY_TASK_RESULT = DOMAIN + "/user/query_import_task";

    private static final String QUERY_VIDEO_DATA = DOMAIN + "/user/dynamic_data";

    @Autowired
    private MchVideoAuthService mchVideoAuthService;

    @Autowired
    private MchVideoCacheService mchVideoCacheService;

    @Autowired
    private ExecutorService executorService;

    @Autowired
    private TransactionDefinition transactionDefinition;

    @Autowired
    private PlatformTransactionManager transactionManager;

    public JSONObject createTask(String mchNo) {
        String result = HttpUtil.get(CREATE_TASK);
        JSONObject resultJson = JSON.parseObject(result);
        log.info("创建任务返回参数: {}", resultJson);
        int code = resultJson.getIntValue("code");
        if (code == 200) {
            JSONObject bizData = resultJson.getJSONObject("data");
            MchVideoAuthEntity mchVideoAuthEntity = new MchVideoAuthEntity();
            mchVideoAuthEntity.setMchNo(mchNo);
            String taskId = bizData.getString("task_id");
            mchVideoAuthEntity.setTaskId(taskId);
            mchVideoAuthEntity.setUserId(taskId);
            mchVideoAuthEntity.setExtra(bizData.toJSONString());
            mchVideoAuthService.save(mchVideoAuthEntity);

            return bizData;
        } else {
            throw new BizException("视频号请求异常");
        }
    }

    public JSONObject queryTask(String taskId) {
        Assert.notNull(taskId, "[taskId]不能为空");
        String result = HttpUtil.get(QUERY_TASK_RESULT + "?task_id=" + taskId);
        JSONObject resultJson = JSON.parseObject(result);
        int code = resultJson.getIntValue("code");
        if (code == 200) {
            JSONObject bizData = resultJson.getJSONObject("data");
            MchVideoAuthEntity data = mchVideoAuthService.lambdaQuery().eq(MchVideoAuthEntity::getTaskId, taskId)
                    .one();

            String status = bizData.getString("status");

            String userId = null;
            String uniqueId = null;

            if (status.equals("2")) {
                userId = bizData.getString("user_id");
                uniqueId = bizData.getString("unique_id");
                data.setUserId(userId);
                data.setUniqueId(uniqueId);

                // 异步请求
                executorService.execute(() -> {
                    videoDataColl(data);
                });
            }

            data.setExtra(bizData.toJSONString());
            mchVideoAuthService.updateById(data);

            return bizData;
        } else {
            throw new BizException("视频号请求异常");
        }
    }

    public void videoDataColl(MchVideoAuthEntity entity) {
        String extra = entity.getExtra();
        JSONObject param = JSON.parseObject(extra);
        String cookies = param.getString("cookies");

        Date now = new Date();
        DateTime startTime = DateUtil.offsetMonth(now, -6);
        @Cleanup HttpResponse response = HttpRequest.get(QUERY_VIDEO_DATA)
                .form("cookies", cookies)
                .form("user_id", entity.getUserId())
                .form("size", 30)
                .form("current", 1)
                .form("start_date", DateUtil.format(startTime, DatePattern.NORM_DATE_FORMATTER))
                .form("end_date", DateUtil.format(now, DatePattern.NORM_DATE_FORMATTER))
                .execute();

        String respJsonStr = response.body();

        JSONObject respJSON = JSON.parseObject(respJsonStr);
        int code = respJSON.getIntValue("code");
        if (code != 200) {
            throw new BizException("视频号获取动态数据异常");
        }

        JSONArray resultData = respJSON.getJSONObject("data").getJSONArray("records");

        // 保存的数据
        List<MchVideoCacheEntity> dataList = new ArrayList<>();
        resultData.forEach(item -> {
            JSONObject jsonItem = (JSONObject) item;
            MchVideoCacheEntity data = new MchVideoCacheEntity();
            data.setMchNo(entity.getMchNo());
            data.setTaskId(entity.getTaskId());
            data.setUserId(entity.getUserId());
            data.setExportId((jsonItem).getString("exportId"));
            data.setUniqueId(entity.getUniqueId());
            data.setObjectId(jsonItem.getString("objectId"));
            data.setExtra(jsonItem.toJSONString());

            try {
                mchVideoCacheService.save(data);
            } catch (Exception ignored) {
            }
        });

    }
}
