package cn.iocoder.yudao.module.pay.controller.admin.notify;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.framework.pay.core.client.PayClient;
import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderRespDTO;
import cn.iocoder.yudao.framework.pay.core.client.dto.refund.PayRefundRespDTO;
import cn.iocoder.yudao.framework.pay.core.enums.divide.PayDivideRefundStatusRespEnum;
import cn.iocoder.yudao.framework.pay.core.enums.refund.PayRefundStatusRespEnum;
import cn.iocoder.yudao.module.member.api.activitypay.ActivityApi;
import cn.iocoder.yudao.module.member.api.activitypay.dto.ActivityPayDTO;
import cn.iocoder.yudao.module.member.api.activitypay.dto.MenuDTO;
import cn.iocoder.yudao.module.member.api.card.CardApi;
import cn.iocoder.yudao.module.pay.controller.admin.notify.vo.PayNotifyTaskDetailRespVO;
import cn.iocoder.yudao.module.pay.controller.admin.notify.vo.PayNotifyTaskPageReqVO;
import cn.iocoder.yudao.module.pay.controller.admin.notify.vo.PayNotifyTaskRespVO;
import cn.iocoder.yudao.module.pay.controller.admin.order.vo.MenuVO;
import cn.iocoder.yudao.module.pay.convert.notify.PayNotifyTaskConvert;
import cn.iocoder.yudao.module.pay.dal.dataobject.app.PayAppDO;
import cn.iocoder.yudao.module.pay.dal.dataobject.notify.PayNotifyLogDO;
import cn.iocoder.yudao.module.pay.dal.dataobject.notify.PayNotifyTaskDO;
import cn.iocoder.yudao.module.pay.dal.dataobject.wxorder.WxOrderDO;
import cn.iocoder.yudao.module.pay.dal.dataobject.wxrefund.WxRefundDO;
import cn.iocoder.yudao.module.pay.dal.mysql.wxorder.WxOrderMapper;
import cn.iocoder.yudao.module.pay.dal.mysql.wxrefund.WxRefundMapper;
import cn.iocoder.yudao.module.pay.service.app.PayAppService;
import cn.iocoder.yudao.module.pay.service.channel.PayChannelService;
import cn.iocoder.yudao.module.pay.service.divide.DivideService;
import cn.iocoder.yudao.module.pay.service.notify.PayNotifyService;
import cn.iocoder.yudao.module.pay.service.order.PayOrderService;
import cn.iocoder.yudao.module.pay.service.refund.PayRefundService;
import cn.iocoder.yudao.module.pay.service.wxprofitsharing.WxProfitsharingService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.module.pay.enums.ErrorCodeConstants.CHANNEL_NOT_FOUND;

@Tag(name = "管理后台 - 回调通知")
@RestController
@RequestMapping("/pay/notify")
@Validated
@Slf4j
public class PayNotifyController {

    @Resource
    private PayOrderService orderService;
    @Resource
    private PayRefundService refundService;
    @Resource
    private WxProfitsharingService wxProfitsharingService;
    @Resource
    private PayNotifyService notifyService;
    @Resource
    private PayAppService appService;
    @Resource
    private PayChannelService channelService;
    @Resource
    private DivideService  divideService;
    @Resource
    private WxRefundMapper wxRefundMapper;
    @Resource
    private WxOrderMapper wxOrderMapper;
    @Resource
    private StringRedisTemplate notifyRedisTemplate;
    @Resource
    private CardApi cardApi;
    @Resource
    private ActivityApi activityApi;

    @PostMapping(value = "/order/{channelId}")
    @Operation(summary = "支付渠道的统一【支付】回调")
    @PermitAll
    @OperateLog(enable = false) // 回调地址，无需记录操作日志
    public String notifyOrder(@PathVariable("channelId") Long channelId,
                              @RequestParam(required = false) Map<String, String> params,
                              @RequestBody(required = false) String body) {
        log.info("[notifyOrder][channelId({}) 回调数据({}/{})]", channelId, params, body);
        // 1. 校验支付渠道是否存在
        PayClient payClient = channelService.getPayClient(channelId);
        if (payClient == null) {
            log.error("[notifyCallback][渠道编号({}) 找不到对应的支付客户端]", channelId);
            throw exception(CHANNEL_NOT_FOUND);
        }

        // 2. 解析通知数据
        PayOrderRespDTO notify = payClient.parseOrderNotify(params, body);
        orderService.notifyOrder(channelId, notify);
        String re = notifyRedisTemplate.opsForValue().get("ADD" + notify.getOutTradeNo());
        if(StringUtils.isNotBlank(re)){
            log.info("开始进行余额增加，获取的金额："+re);
            int index = re.indexOf("-");
            String userId = re.substring(index + 1);
            cardApi.recharge(new BigDecimal(re.substring(0,index)),Long.valueOf(userId));
            notifyRedisTemplate.delete("ADD" + notify.getOutTradeNo());
        }
        return "success";
    }

    @PostMapping(value = "/reserved/{channelId}")
    @Operation(summary = "支付渠道的统一【支付】回调")
    @PermitAll
    @OperateLog(enable = false) // 回调地址，无需记录操作日志
    public String reservedNotifyOrder(@PathVariable("channelId") Long channelId,
                              @RequestParam(required = false) Map<String, String> params,
                              @RequestBody(required = false) String body) {
        log.info("[notifyOrder][channelId({}) 回调数据({}/{})]", channelId, params, body);
        // 1. 校验支付渠道是否存在
        PayClient payClient = channelService.getPayClient(channelId);
        if (payClient == null) {
            log.error("[notifyCallback][渠道编号({}) 找不到对应的支付客户端]", channelId);
            throw exception(CHANNEL_NOT_FOUND);
        }

        // 2. 解析通知数据
        PayOrderRespDTO notify = payClient.parseOrderNotify(params, body);
        orderService.notifyOrder(channelId, notify);
        String re = notifyRedisTemplate.opsForValue().get("RESERVED" + notify.getOutTradeNo());
        if(StringUtils.isNotBlank(re) ){
            log.info("开始进行订单记录增加，获取的数据：{}", re);
            HashMap<String, String> deserializedMap = JSONUtil.toBean(re, HashMap.class);

            ActivityPayDTO activityPayDTO = new ActivityPayDTO();
            activityPayDTO.setActivityId(Long.valueOf(deserializedMap.get("activityId")));
//            activityPayDTO.setSerialNumbers(deserializedMap.get("serialNumbers"));
            activityPayDTO.setPrice(new BigDecimal(deserializedMap.get("price")).divide(new BigDecimal("100"),  2, RoundingMode.HALF_UP));
            activityPayDTO.setUserId(Long.valueOf(deserializedMap.get("userId")));
            activityPayDTO.setStatus(deserializedMap.get("status"));
            activityPayDTO.setReserveTime(deserializedMap.get("reserveTime"));
            activityPayDTO.setDish( deserializedMap.get("dish"));
            activityPayDTO.setDiningPeriod( deserializedMap.get("diningPeriod"));
            activityPayDTO.setVoucherId( deserializedMap.get("voucherId"));
            activityPayDTO.setTransactionId( notify.getChannelOrderNo());
            activityPayDTO.setOpenid(deserializedMap.get("openid"));

            String s = deserializedMap.get("menuList");
            if(StringUtils.isNotBlank(s)){
                List<MenuVO> menuVOS = JSON.parseArray(s, MenuVO.class);
                List<MenuDTO> bean = BeanUtils.toBean(menuVOS, MenuDTO.class);
                activityPayDTO.setMenu(bean);
            }

            activityApi.createActivityPay(activityPayDTO);
            notifyRedisTemplate.delete("RESERVED" + notify.getOutTradeNo());
        }
        return "success";
    }

    @PostMapping(value = "/refund/{channelId}")
    @Operation(summary = "支付渠道的统一【退款】回调")
    @PermitAll
    @OperateLog(enable = false) // 回调地址，无需记录操作日志
    public String notifyRefund(@PathVariable("channelId") Long channelId,
                              @RequestParam(required = false) Map<String, String> params,
                              @RequestBody(required = false) String body) {
        log.info("[notifyRefund][channelId({}) 回调数据({}/{})]", channelId, params, body);
        // 1. 校验支付渠道是否存在
        PayClient payClient = channelService.getPayClient(channelId);
        if (payClient == null) {
            log.error("[notifyCallback][渠道编号({}) 找不到对应的支付客户端]", channelId);
            throw exception(CHANNEL_NOT_FOUND);
        }
        // 2. 解析通知数据
        PayRefundRespDTO notify = payClient.parseRefundNotify(params, body);
        WxRefundDO refundRecordDO = wxRefundMapper.selectOne(Wrappers.<WxRefundDO>lambdaUpdate()
                .eq(WxRefundDO::getOutRefundNo, notify.getOutRefundNo())
                .last("limit 1"));
        String status = "";
        if(PayRefundStatusRespEnum.SUCCESS.getStatus().equals(notify.getStatus())){
            status = PayDivideRefundStatusRespEnum.SUCCESS.getStatus();
        }else{
            status = PayDivideRefundStatusRespEnum.ABNORMAL.getStatus();
        }
        refundRecordDO.setStatus(status);
        if("0".equals(refundRecordDO.getNotifyStatus()) && "20".equals(refundRecordDO.getStatus())){
            //扣除积分
            divideService.subtractWx(refundRecordDO.getTotalPrice(),Long.valueOf(refundRecordDO.getUserId()));
            //更改订单
            String jsonString = notifyRedisTemplate.opsForValue().get("R" + refundRecordDO.getPayWxOrderId());
            WxOrderDO orderDO = JsonUtils.parseObject(jsonString, WxOrderDO.class);
            wxOrderMapper.updateById(orderDO);
            notifyRedisTemplate.delete("R" + refundRecordDO.getPayWxOrderId());
            //分账回退
            String returnPrice = notifyRedisTemplate.opsForValue().get("R" + refundRecordDO.getOutRefundNo());
            if (StringUtils.isNotEmpty(returnPrice)){
                wxProfitsharingService.returnMoney(refundRecordDO.getPayWxOrderId(),Integer.parseInt(returnPrice));
            }

        }
        refundRecordDO.setNotifyStatus("1");
        wxRefundMapper.updateById(refundRecordDO);
        return "success";
    }

    @GetMapping("/get-detail")
    @Operation(summary = "获得回调通知的明细")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('pay:notify:query')")
    public CommonResult<PayNotifyTaskDetailRespVO> getNotifyTaskDetail(@RequestParam("id") Long id) {
        PayNotifyTaskDO task = notifyService.getNotifyTask(id);
        if (task == null) {
            return success(null);
        }
        // 拼接返回
        PayAppDO app = appService.getApp(task.getAppId());
        List<PayNotifyLogDO> logs = notifyService.getNotifyLogList(id);
        return success(PayNotifyTaskConvert.INSTANCE.convert(task, app, logs));
    }

    @GetMapping("/page")
    @Operation(summary = "获得回调通知分页")
    @PreAuthorize("@ss.hasPermission('pay:notify:query')")
    public CommonResult<PageResult<PayNotifyTaskRespVO>> getNotifyTaskPage(@Valid PayNotifyTaskPageReqVO pageVO) {
        PageResult<PayNotifyTaskDO> pageResult = notifyService.getNotifyTaskPage(pageVO);
        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(PageResult.empty());
        }
        // 拼接返回
        Map<Long, PayAppDO> appMap = appService.getAppMap(convertList(pageResult.getList(), PayNotifyTaskDO::getAppId));
        return success(PayNotifyTaskConvert.INSTANCE.convertPage(pageResult, appMap));
    }

}
