package com.ruoyi.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
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.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.lkl.laop.sdk.LKLSDK;
import com.lkl.laop.sdk.request.V2LaepIndustryEwalletWithdrawD1Request;
import com.lkl.laop.sdk.request.V2MmsQueryLedgerMerRequest;
import com.lkl.laop.sdk.request.V3SacsBalanceSeparateQueryRequest;
import com.lkl.laop.sdk.utils.CommonUtil;
import com.ruoyi.code.DictConstant;
import com.ruoyi.code.PublicCommon;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.controller.req.MallOrderConfirmReq;
import com.ruoyi.enums.mallorder.MallOrderStatusEnums;
import com.ruoyi.enums.message.OrderMessageEnums;
import com.ruoyi.enums.order.OrderStatusEnums;
import com.ruoyi.enums.user.UserEnums;
import com.ruoyi.frequency.klkaccount.entity.KlkAccount;
import com.ruoyi.frequency.klkaccount.mapper.KlkAccountMapper;
import com.ruoyi.frequency.klkaccount.service.KlkAccountService;
import com.ruoyi.frequency.klkwithdrawalrecord.entity.KlkWithdrawalRecord;
import com.ruoyi.frequency.klkwithdrawalrecord.mapper.KlkWithdrawalRecordMapper;
import com.ruoyi.frequency.mallorder.entity.MallOrder;
import com.ruoyi.frequency.mallorder.service.MallOrderService;
import com.ruoyi.frequency.order.entity.Order;
import com.ruoyi.frequency.order.service.OrderService;
import com.ruoyi.frequency.ordermessage.service.OrderMessageService;
import com.ruoyi.frequency.withdrawalrecord.entity.WithdrawalRecord;
import com.ruoyi.frequency.withdrawalrecord.mapper.WithdrawalRecordMapper;
import com.ruoyi.klk.constant.KlkConstant;
import com.ruoyi.klk.service.KlkService;
import com.ruoyi.klk.util.InitUtil;
import com.ruoyi.utils.BusinessUtil;
import com.ruoyi.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 定时任务
 *
 * @author liwenlong
 * @date 2023-10-23
 */
@Component("businessTask")
@Slf4j
public class RyTask {

    @Value("${basepath.url}")
    private String urlPrefix;

    @Autowired
    private OrderService orderService;

    @Autowired
    private BusinessUtil businessUtil;

    //商户号
    @Value("${lalkla.merchantNo}")
    private String merchantNo;

    /**
     * 订单定时取消
     */
    public void orderCancelTask() {
        log.info("定时任务【订单定时取消】开始执行，执行时间：{}", DateUtil.formatDateTime(new Date()));

        SysDictData dict = businessUtil.getDict(DictConstant.订单自动取消时间);
        Integer autoOrderCancelTime = 15;
        if (dict != null) {
            //查询订单自动取消时长
            autoOrderCancelTime = Integer.valueOf(dict.getDictValue());
        }

        //查询超出时间未支付的订单
        List<Order> orderList = orderService.list(new QueryWrapper<Order>().lambda()
                .ne(Order::getStatus, OrderStatusEnums.cancel.getCode())
                .eq(Order::getSourceUserType, 1)
                .eq(Order::getFirstStatus, PublicCommon.Pay.未支付)
                .gt(BaseEntity::getCreateTime, DateUtil.offsetMinute(new Date(), autoOrderCancelTime))
        );
        if (orderList.size() > 0) {
            orderList.stream().forEach(s -> {
                orderService.orderCancel(s.getId(), new UserVo(UserEnums.customer.getCode(), s.getCustomerId()));
            });
        }

        log.info("定时任务【订单定时取消】执行结束，执行时间：{}", DateUtil.formatDateTime(new Date()));
    }


    @Autowired
    private OrderMessageService orderMessageService;


    /**
     * 超过对图时间,消息提醒
     */
    public void orderDeliveryTimoutPushTask() {
        log.info("定时任务【超过对图时间第二天,消息提醒】开始执行，执行时间：{}", DateUtil.formatDateTime(new Date()));

        //查询未发送消息的订单
        List<Order> orderList = orderService.list(new QueryWrapper<Order>().lambda()
                .eq(Order::getStatus, OrderStatusEnums.ongoing.getCode())
                .between(Order::getDeliverTime, DateUtil.beginOfDay(DateUtil.offsetDay(new Date(), -1)),
                        DateUtil.endOfDay(DateUtil.offsetDay(new Date(), -1)))
        );
        orderList.stream().forEach(order -> {

            //表现师发送消息
            orderMessageService.addOrderMessage(new UserVo(UserEnums.store.getCode(), order.getStoreId()), order.getId(), order.getOrderNo(), PublicCommon.Order.订单, OrderMessageEnums.ORDER_AUTO_CONFIRM_DELIVER);

            //设计师发送消息
            orderMessageService.addOrderMessage(new UserVo(UserEnums.customer.getCode(), order.getCustomerId()), order.getId(), order.getOrderNo(), PublicCommon.Order.订单, OrderMessageEnums.ORDER_AUTO_CONFIRM_DELIVER);

        });

        log.info("定时任务【超过对图时间第二天,消息提醒】开始执行：{}", DateUtil.formatDateTime(new Date()));
    }

    @Autowired
    private MallOrderService mallOrderService;


    /**
     * 发货时间超过 x天的订单自动确认收货
     */
    public void confirmMallOrder() {
        log.info("定时任务【超过发货时间第X天,消息提醒】开始执行，执行时间：{}", DateUtil.formatDateTime(new Date()));

        SysDictData 平台发货后X天自动确认收货 = businessUtil.getDict(DictConstant.MallOrderDict.平台发货后X天自动确认收货);

        //查询未发送消息的订单
        List<MallOrder> list = mallOrderService.list(new QueryWrapper<MallOrder>().lambda().eq(MallOrder::getOrderStatus, MallOrderStatusEnums.已发货.getCode())
                .le(MallOrder::getSendTime, DateUtil.offsetDay(new Date(), -(Integer.valueOf(平台发货后X天自动确认收货.getDictValue())))));

        list.stream().forEach(order -> {
            MallOrderConfirmReq req = new MallOrderConfirmReq();
            req.setOrderId(order.getId());
            mallOrderService.orderConfirm(req, new UserVo(order.getUserType(), order.getUserId()));
        });

    }

    @Autowired
    private KlkWithdrawalRecordMapper klkWithdrawalRecordMapper;

    @Autowired
    private KlkService klkService;

    @Autowired
    private InitUtil initUtil;

    /**
     * 定时扫描分账记录，对已经分账成功的记录，进行银行卡提现
     */
    public void catDiscountToWithdrawal() {
        log.info("定时任务【扫描分账成功的记录，进行下一步提现】");

        // 1-处理中 2-已受理
        List<KlkWithdrawalRecord> klkWithdrawalRecordList = klkWithdrawalRecordMapper.selectList(new LambdaQueryWrapper<KlkWithdrawalRecord>()
                .eq(KlkWithdrawalRecord::getDelFlag, PublicCommon.启用)
                .in(KlkWithdrawalRecord::getBalanceSplitStatus, 1, 2));
        if (CollectionUtil.isEmpty(klkWithdrawalRecordList)) {
            return;
        }


        klkWithdrawalRecordList.forEach(klkWithdrawalRecord -> {

            try {
                // 根据商户分账指令流水号查询余额分账结果
                String outSeparateNo = klkWithdrawalRecord.getOutSeparateNo();
                initUtil.doInit();
                V3SacsBalanceSeparateQueryRequest request = new V3SacsBalanceSeparateQueryRequest();
                request.setMerchantNo(merchantNo);
                request.setOutSeparateNo(outSeparateNo);
                String response = LKLSDK.httpPost(request);
                JSONObject jsonObject = JSON.parseObject(response);
                if ("SACS0000".equals(jsonObject.getString("code"))) {
                    JSONObject respData = jsonObject.getJSONObject("resp_data");
                    String status = respData.getString("status");
                    klkWithdrawalRecordMapper.update(null, new LambdaUpdateWrapper<KlkWithdrawalRecord>()
                            .eq(KlkWithdrawalRecord::getOutSeparateNo, outSeparateNo)
                            .set(KlkWithdrawalRecord::getBalanceSplitStatus, klkService.getBalanceSplitStatus(status)));
                    if (KlkConstant.SUCCESS.equals(status)) {
                        // 成功后提现
                        withdrawal(klkWithdrawalRecord);
                    }
                }
            } catch (Exception e) {
                log.error("查询余额分账结果出现异常：{}", e.getMessage());
            }
        });
    }


    @Autowired
    private KlkAccountMapper klkAccountMapper;

    /**
     * 提现
     *
     * @param klkWithdrawalRecord
     */
    private void withdrawal(KlkWithdrawalRecord klkWithdrawalRecord) {
        try {
            // 查询用户卡拉卡账号
            KlkAccount klkAccount = klkAccountMapper.selectOne(new LambdaUpdateWrapper<KlkAccount>()
                    .eq(KlkAccount::getDelFlag, PublicCommon.启用)
                    .eq(KlkAccount::getUserType, klkWithdrawalRecord.getUserType())
                    .eq(KlkAccount::getUserId, klkWithdrawalRecord.getUserId()));
            initUtil.doInit();
            V2LaepIndustryEwalletWithdrawD1Request request = new V2LaepIndustryEwalletWithdrawD1Request();
            request.setOrgNo(KlkConstant.ORG_NO);
            request.setMerchantNo(klkAccount.getReceiverNo());
            request.setDrawAmt(getDrawAmt(klkWithdrawalRecord.getTotalAmt()));
            request.setNotifyUrl(urlPrefix + KlkConstant.WITHDRAWAL);
            //账号类型（01：收款账户，04：分账接收方账户）未上送则默认为01 分账接收方提现时需填04
            request.setPayType("04");
            String response = LKLSDK.httpPost(request);
            JSONObject jsonObject = JSON.parseObject(response);
            if ("000000".equals(jsonObject.getString("retCode"))) {
                JSONObject respData = jsonObject.getJSONObject("respData");
                klkWithdrawalRecordMapper.update(null, new LambdaUpdateWrapper<KlkWithdrawalRecord>()
                        .eq(KlkWithdrawalRecord::getDelFlag, PublicCommon.启用)
                        .eq(KlkWithdrawalRecord::getId, klkWithdrawalRecord.getId())
                        .set(KlkWithdrawalRecord::getWithdrawalStatus, 1)
                        .set(KlkWithdrawalRecord::getDrawJnl, respData.getString("drawJnl")));
            } else {
                klkWithdrawalRecordMapper.update(null, new LambdaUpdateWrapper<KlkWithdrawalRecord>()
                        .eq(KlkWithdrawalRecord::getDelFlag, PublicCommon.启用)
                        .eq(KlkWithdrawalRecord::getId, klkWithdrawalRecord.getId())
                        .set(KlkWithdrawalRecord::getWithdrawalStatus, 4)
                        .set(KlkWithdrawalRecord::getWithdrawalRemark, jsonObject.getString("retMsg")));

                withdrawalRecordMapper.update(null, new LambdaUpdateWrapper<WithdrawalRecord>()
                        .eq(WithdrawalRecord::getId, klkWithdrawalRecord.getWithdrawalRecordId())
                        .set(WithdrawalRecord::getRefuseReason, jsonObject.getString("retMsg")));
            }
        } catch (Exception e) {

            log.error("提现出现异常：{}", e.getMessage());

        }
    }

    @Autowired
    private WithdrawalRecordMapper withdrawalRecordMapper;

    /**
     * 将分转换为元
     *
     * @param totalAmt
     * @return
     */
    private String getDrawAmt(String totalAmt) {
        return new BigDecimal(totalAmt).divide(new BigDecimal("100"), 2, RoundingMode.DOWN).toString();
    }

    @Autowired
    private KlkAccountService klkAccountService;


    /**
     * 定时更新拉卡拉账号状态
     */
    public void updateTimeAccountStatus() {
        log.info("定时更新拉卡拉账号状态...");
        // 查询所有账号为2的账号
        List<KlkAccount> klkAccountList = klkAccountMapper.selectList(new LambdaQueryWrapper<KlkAccount>()
                .eq(KlkAccount::getDelFlag, PublicCommon.启用)
                .eq(KlkAccount::getBindStatus, 2));
        if (CollectionUtil.isEmpty(klkAccountList)) {
            return;
        }

        // 调用三方接口，获取已经开通的账号
        List<String> receiverNoList = getAlreadyOpenedAccount();
        if (CollectionUtil.isEmpty(receiverNoList)) {
            return;
        }

        // 如果查询的账号在三方存在，表示开通成功，直接修改账号状态
        updateAccStatus(receiverNoList, klkAccountList);
    }

    /**
     * 如果查询的账号在三方存在，表示开通成功，直接修改账号状态
     * @param receiverNoList
     */
    private void updateAccStatus(List<String> receiverNoList, List<KlkAccount> klkAccountList) {
        if (CollectionUtil.isEmpty(receiverNoList) || CollectionUtil.isEmpty(klkAccountList)) {
            return;
        }

        for (KlkAccount klkAccount : klkAccountList) {
            if (receiverNoList.contains(klkAccount.getReceiverNo())) {
                klkAccount.setBindStatus(3);
            }
        }

        // 过滤只要3的
        klkAccountList = klkAccountList.stream().filter(s -> s.getBindStatus() == 3).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(klkAccountList)) {
            return;
        }

        klkAccountService.updateBatchById(klkAccountList);
    }

    /**
     * 调用三方接口，获取已经开通的账号
     * @return
     */
    private List<String> getAlreadyOpenedAccount() {
        try {
            initUtil.doInit();
            V2MmsQueryLedgerMerRequest request = new V2MmsQueryLedgerMerRequest();
            request.setOrgCode(KlkConstant.ORG_CODE);
            request.setOrderNo(CommonUtil.getOrderNo());
            request.setMerCupNo(merchantNo);
            String response = LKLSDK.httpPost(request);
            JSONObject jsonObject = JSON.parseObject(response);
            if ("000000".equals(jsonObject.getString("retCode"))) {
                JSONObject innerJsonObj = jsonObject.getJSONObject("respData");
                JSONArray jsonArray = innerJsonObj.getJSONArray("bindRelations");
                return jsonArray.stream().map(s -> {
                    JSONObject obj = (JSONObject) s;
                    return obj.getString("receiverNo");
                }).collect(Collectors.toList());
            }
            return null;
        } catch (Exception e) {
            log.error("查询商户分账信息出现异常：{}", e.getMessage());
            return null;
        }
    }
}
