package com.ruoyi.web.controller.mch;

import com.fasterxml.jackson.annotation.JsonView;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.JsonViewProfile;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.ss.store.service.StoreValidator;
import com.ruoyi.ss.storeApply.domain.StoreApplyQuery;
import com.ruoyi.ss.storeApply.domain.StoreApplyVO;
import com.ruoyi.ss.storeApply.service.StoreApplyService;
import com.ruoyi.ss.storeApply.service.StoreApplyValidator;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;

/**
 * @author wjh
 * 2024/8/5
 */
@RestController
@RequestMapping("/mch/storeApply")
public class MchStoreApplyController extends BaseController {

    @Autowired
    private StoreApplyService storeApplyService;

    @Autowired
    private StoreValidator storeValidator;

    @Autowired
    private StoreApplyValidator storeApplyValidator;

    @ApiOperation("查询店铺最后一条申请信息")
    @JsonView(JsonViewProfile.AppMch.class)
    @GetMapping("/getLastByStore/{storeId}")
    public AjaxResult getLastByStore(@PathVariable Long storeId) {
        if (!storeValidator.canViewStore(storeId, getUserId())) {
            return error("您无权查看该店铺信息");
        }
        PageHelper.orderBy(" create_time desc ");
        PageHelper.startPage(1, 1);
        StoreApplyQuery query = new StoreApplyQuery();
        query.setStoreId(storeId);
        List<StoreApplyVO> list = storeApplyService.selectStoreApplyList(query);
        if (CollectionUtils.isEmpty(list)) {
            return success();
        }
        return success(list.get(0));
    }

    @ApiOperation("取消申请")
    @PutMapping("/{id}/cancel")
    public AjaxResult cancel(@PathVariable @ApiParam("申请ID") Long id) {
        StoreApplyVO apply = storeApplyService.selectStoreApplyById(id);
        if (!storeApplyValidator.isBelong(apply, getUserId())) {
            return error("这不是您的申请，无权取消");
        }
        return toAjax(storeApplyService.cancel(id));
    }

    @ApiOperation("查询本人提交的店铺申请")
    @GetMapping("/list")
    public TableDataInfo list(StoreApplyQuery query) {
        startPage();
        query.setUserId(getUserId());
        return getDataTable(storeApplyService.selectStoreApplyList(query));
    }

    @ApiOperation("查询本人提交的店铺申请详情")
    @GetMapping("/{id}")
    public AjaxResult detail(@PathVariable Long id) {
        StoreApplyVO apply = storeApplyService.selectStoreApplyById(id);
        if (!storeApplyValidator.isBelong(apply, getUserId())) {
            return success();
        }
        return success(apply);
    }

}
