package com.ylx.order.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ylx.common.core.domain.R;
import com.ylx.common.core.domain.entity.SysDictData;
import com.ylx.common.utils.DictUtils;
import com.ylx.order.domain.dto.AfterSalesServiceDTO;
import com.ylx.order.domain.vo.AfterSalesServiceApplyVO;
import com.ylx.order.domain.vo.AfterSalesServiceDetailVO;
import com.ylx.order.enums.AfterSaleServiceDictTypeEnum;
import com.ylx.order.service.IAfterSalesServiceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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 javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/order/after/sale")
@Api(tags = {"订单售后模块"})
@Slf4j
public class AfterSalesServiceController {

    @Resource
    private IAfterSalesServiceService afterSalesServiceService;

    @ApiOperation("获取售后原因接口：客户端退款=1, 客户端取消订单=2, 商户端取消订单=3")
    @GetMapping("/dict/{type}/reason")
    public R<List<String>> getReasonList(@PathVariable("type") Integer type) {

        String dictType = AfterSaleServiceDictTypeEnum.getDictTypeByCode(type);

        if (ObjectUtil.isNull(dictType)) {
            return R.fail("无效的type类型参数");
        }

        List<SysDictData> reasonDictDataList = DictUtils.getSortedDictCache(dictType);

        if (CollUtil.isEmpty(reasonDictDataList)) {
            return R.ok(Collections.emptyList());
        }

        List<String> list = new ArrayList<>(reasonDictDataList.size());
        for (SysDictData data : reasonDictDataList) {
            list.add(data.getDictValue());
        }
        return R.ok(list);
    }

    @PreAuthorize("@customerAuth.isCustomer()")
    @ApiOperation("客户端用户申请退款页面数据接口")
    @PostMapping("/apply")
    public R<AfterSalesServiceApplyVO> applyAfterSale(@Validated @RequestBody AfterSalesServiceDTO dto) {
        AfterSalesServiceApplyVO vo = this.afterSalesServiceService.applyAfterSale(dto);
        return R.ok(vo);
    }

    @PreAuthorize("@customerAuth.isCustomer()")
    @ApiOperation("客户端用户提交退款")
    @PostMapping("/submit")
    public R<?> submitAfterSale(@Validated @RequestBody AfterSalesServiceDTO dto) {
        this.afterSalesServiceService.submitAfterSale(dto);
        return R.ok();
    }

    @ApiOperation("客户端、商户端查看售后单详情")
    @GetMapping("/detail/{id}")
    public R<AfterSalesServiceDetailVO> getDetailById(@PathVariable("id") Long id) {
        AfterSalesServiceDetailVO vo = this.afterSalesServiceService.getDetailById(id);
        return R.ok(vo);
    }

}
