package com.cyksj.web.controller.manage;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.constant.Constant;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.GoodsDonSkuMapper;
import com.cyksj.mapper.GroupsRelationMapper;
import com.cyksj.mapper.corp.CorpFollowMapper;
import com.cyksj.model.entity.CorpFollow;
import com.cyksj.model.entity.GoodsDonSku;
import com.cyksj.model.entity.GroupsRelation;
import com.cyksj.model.entity.OrderDon;
import com.cyksj.service.chatgpt.GptUserRechargeRecordService;
import com.cyksj.service.mange.CmsOrderDonService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
 * @author chan
 * @date 2025/1/22 16:23
 */
@Slf4j
@RequestMapping("/manage/order")
@RestController
@RequiredArgsConstructor
public class CmsOrderController {
    private final CmsOrderDonService cmsOrderDonService;

    private final GroupsRelationMapper relationMapper;

    private final HttpServletRequest request;

    private final CorpFollowMapper corpFollowMapper;

    private final GoodsDonSkuMapper skuMapper;

    private final GptUserRechargeRecordService gptUserRechargeRecordService;

    private final static String CORP_UUID = "corp-uuid";

    /**
     * 修改订单状态
     */
    @PutMapping("/put/status/{orderId}")
    public Result<String> updateOrderStatus(@PathVariable Long orderId) {
        String followId = getCorpUuid();
        CorpFollow corpFollow = null;
        if (StrUtil.isNotBlank(followId)) {
            corpFollow = corpFollowMapper.selectOne(Wrappers.lambdaQuery(CorpFollow.class)
                    .eq(CorpFollow::getUserid, followId)
                    .last("limit 1"));
        }
        CorpFollow fcorpFollow = corpFollow;
        OrderDon orderDon = cmsOrderDonService.getById(orderId);
        if (orderDon == null) {
            throw BusinessRuntimeException.getInstance("该订单不存在");
        }
        if (orderDon.getStatus() == OrderDon.Status.complete) {
            throw BusinessRuntimeException.getInstance("该订单已是已完成状态");
        }
        if (orderDon.getStatus() != OrderDon.Status.hasPayment) {
            throw BusinessRuntimeException.getInstance("该订单不是未支付状态");
        }
        orderDon.setStatus(OrderDon.Status.complete);
        cmsOrderDonService.updateById(orderDon);
        Long relationId = orderDon.getRelationId();
        Optional.ofNullable(relationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class)
                .eq(GroupsRelation::getId, relationId)
                .eq(GroupsRelation::getUserId, orderDon.getUserId())
                .last("limit 1"))).ifPresent(relation->{
            GroupsRelation.RechargeStatus rechargeStatus = relation.getRechargeStatus();
            if (rechargeStatus != null && rechargeStatus == GroupsRelation.RechargeStatus.waiting) {
                relation.setRechargeStatus(GroupsRelation.RechargeStatus.complete);
                if (fcorpFollow != null) {
                    relation.setOperator(fcorpFollow.getName());
                }
                relation.setSendTime(DateTime.now());

                if (relation.getStartTime() == null) {
                    relation.setStartTime(DateTime.now());
                    GoodsDonSku sku = skuMapper.selectById(orderDon.getSkuId());
                    DateTime expiryTime;
                    if (sku.getDays() != null && sku.getDays() > 0) {
                        expiryTime = DateUtil.offsetDay(relation.getStartTime(), sku.getDays());
                    } else {
                        expiryTime = DateUtil.offsetMonth(relation.getStartTime(), sku.getMonths());
                    }
                    relation.setExpiryTime(expiryTime);
                }
                relationMapper.updateById(relation);

                //GPT代充
                if (orderDon.getGoodsId() == Constant.GPT_RECHARGE_GOODS_ID) {
                    //扣除次数
                    Integer rechargeRemainNum = relation.getRechargeRemainNum();
                    if (rechargeRemainNum != null && rechargeRemainNum > 0) {
                        int update = relationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
                                .set(GroupsRelation::getRechargeRemainNum, rechargeRemainNum - 1)
                                .eq(GroupsRelation::getId, relationId)
                                .eq(GroupsRelation::getRechargeRemainNum, rechargeRemainNum));
                        if (update == 0) {
                            throw BusinessRuntimeException.getInstance("更新用户代充剩余次数失败，请重试");
                        }
                        //记录gpt代充记录
                        gptUserRechargeRecordService.recordGptUserRechargeNum(relation.getUserId(), relation.getId(), relation.getAccount(), 1, fcorpFollow != null ? fcorpFollow.getName() : null, "客服手动充值");
                    }
                }
            }
        });

        return GatewayResponse.SUCCESS.newBuilder().toResult("修改订单状态成功");
    }

    public String getCorpUuid() {
        Cookie[] cookies = this.request.getCookies();
        if (cookies != null) {
            Cookie[] var3 = cookies;
            int var4 = cookies.length;

            for(int var5 = 0; var5 < var4; ++var5) {
                Cookie cookie = var3[var5];
                if (cookie != null && CORP_UUID.equals(cookie.getName())) {
                    return cookie.getValue();
                }
            }
        }
        return StrUtil.EMPTY;
    }

}
