package com.tashow.cloud.trade.controller.admin.aftersale;

import cn.hutool.core.collection.CollUtil;
import com.tashow.cloud.common.pojo.CommonResult;
import com.tashow.cloud.common.pojo.PageResult;
import com.tashow.cloud.userapi.api.user.UserMemberApi;
import com.tashow.cloud.payapi.api.notify.dto.PayRefundNotifyReqDTO;
import com.tashow.cloud.trade.controller.admin.aftersale.vo.*;
import com.tashow.cloud.trade.convert.aftersale.AfterSaleConvert;
import com.tashow.cloud.trade.dal.dataobject.aftersale.AfterSaleDO;
import com.tashow.cloud.trade.dal.dataobject.aftersale.AfterSaleLogDO;
import com.tashow.cloud.trade.dal.dataobject.order.TradeOrderDO;
import com.tashow.cloud.trade.dal.dataobject.order.TradeOrderItemDO;
import com.tashow.cloud.trade.service.aftersale.AfterSaleLogService;
import com.tashow.cloud.trade.service.aftersale.AfterSaleService;
import com.tashow.cloud.trade.service.order.TradeOrderQueryService;
import jakarta.annotation.Resource;
import jakarta.annotation.security.PermitAll;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static com.tashow.cloud.common.pojo.CommonResult.success;
import static com.tashow.cloud.common.util.servlet.ServletUtils.getClientIP;
import static com.tashow.cloud.security.security.core.util.SecurityFrameworkUtils.getLoginUserId;


// 管理后台 - 售后订单
@RestController
@RequestMapping("/trade/after-sale")
@Validated
@Slf4j
public class AfterSaleController {

    @Resource
    private AfterSaleService afterSaleService;
    @Resource
    private TradeOrderQueryService tradeOrderQueryService;
    @Resource
    private AfterSaleLogService afterSaleLogService;
    @Resource
    private UserMemberApi memberUserApi;

    // 获得售后订单分页
    @GetMapping("/page")
    @PreAuthorize("@ss.hasPermission('trade:after-sale:query')")
    public CommonResult<PageResult<AfterSaleRespPageItemVO>> getAfterSalePage(@Valid AfterSalePageReqVO pageVO) {
        // 查询售后
        PageResult<AfterSaleDO> pageResult = afterSaleService.getAfterSalePage(pageVO);
        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(PageResult.empty());
        }

        // 查询会员
//        Map<Long, MemberUserRespDTO> memberUsers = memberUserApi.getUserMap(
//                convertSet(pageResult.getList(), AfterSaleDO::getUserId));
        return success(AfterSaleConvert.INSTANCE.convertPage(pageResult, null));
    }

    // 获得售后订单详情
    // 售后编号 - 必填 - 示例: 1
    @GetMapping("/get-detail")
    @PreAuthorize("@ss.hasPermission('trade:after-sale:query')")
    public CommonResult<AfterSaleDetailRespVO> getOrderDetail(@RequestParam("id") Long id) {
        // 查询订单
        AfterSaleDO afterSale = afterSaleService.getAfterSale(id);
        if (afterSale == null) {
            return success(null);
        }

        // 查询订单
        TradeOrderDO order = tradeOrderQueryService.getOrder(afterSale.getOrderId());
        // 查询订单项
        TradeOrderItemDO orderItem = tradeOrderQueryService.getOrderItem(afterSale.getOrderItemId());
        // 拼接数据
//        MemberUserRespDTO user = memberUserApi.getUser(afterSale.getUserId()).getCheckedData();
        List<AfterSaleLogDO> logs = afterSaleLogService.getAfterSaleLogList(afterSale.getId());
        return success(AfterSaleConvert.INSTANCE.convert(afterSale, order, orderItem, null, logs));
    }


    /**
     * 同意售后
     * @param id 售后编号
     * @return
     */
    @PutMapping("/agree")
    @PreAuthorize("@ss.hasPermission('trade:after-sale:agree')")
    public CommonResult<Boolean> agreeAfterSale(@RequestParam("id") Long id) {
        afterSaleService.agreeAfterSale(getLoginUserId(), id);
        return success(true);
    }

    /**
     * 拒绝售后
     * @param confirmReqVO
     * @return
     */
    @PutMapping("/disagree")
    @PreAuthorize("@ss.hasPermission('trade:after-sale:disagree')")
    public CommonResult<Boolean> disagreeAfterSale(@RequestBody AfterSaleDisagreeReqVO confirmReqVO) {
        afterSaleService.disagreeAfterSale(getLoginUserId(), confirmReqVO);
        return success(true);
    }

    /**
     * 确认收货
     * @param id 售后编号
     * @return
     */
    @PutMapping("/receive")
    @PreAuthorize("@ss.hasPermission('trade:after-sale:receive')")
    public CommonResult<Boolean> receiveAfterSale(@RequestParam("id") Long id) {
        afterSaleService.receiveAfterSale(getLoginUserId(), id);
        return success(true);
    }

    /**
     * 拒绝收货
     * @param refuseReqVO 售后编号
     * @return
     */
    @PutMapping("/refuse")
    @PreAuthorize("@ss.hasPermission('trade:after-sale:receive')")
    public CommonResult<Boolean> refuseAfterSale(AfterSaleRefuseReqVO refuseReqVO) {
        afterSaleService.refuseAfterSale(getLoginUserId(), refuseReqVO);
        return success(true);
    }

    /**
     * 确认退款
     * @param id 售后编号
     * @return
     */
    @PutMapping("/refund")
    @PreAuthorize("@ss.hasPermission('trade:after-sale:refund')")
    public CommonResult<Boolean> refundAfterSale(@RequestParam("id") Long id) {
        afterSaleService.refundAfterSale(getLoginUserId(), getClientIP(), id);
        return success(true);
    }

    /**
     * 更新售后订单为已退款
     * @param notifyReqDTO
     * @return
     */
    @PostMapping("/update-refunded")
    @PermitAll // 无需登录，安全由 PayDemoOrderService 内部校验实现
    public CommonResult<Boolean> updateAfterRefund(@RequestBody PayRefundNotifyReqDTO notifyReqDTO) {
        // 目前业务逻辑，不需要做任何事情
        // 当然，退款会有小概率会失败的情况，可以监控失败状态，进行告警
        log.info("[updateAfterRefund][notifyReqDTO({})]", notifyReqDTO);
        return success(true);
    }

}
