package com.ruoyi.web.controller.app;

import com.fasterxml.jackson.annotation.JsonView;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.annotation.Anonymous;
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.domain.ValidGroup;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.common.utils.collection.CollectionUtils;
import com.ruoyi.ss.store.domain.*;
import com.ruoyi.ss.store.service.StoreService;
import com.ruoyi.ss.store.service.StoreAssembler;
import com.ruoyi.ss.store.service.StoreValidator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

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

/**
 * 店铺Controller
 * @author 辉
 * 2024/3/5
 */
@Api(tags = "店铺")
@RestController
@RequestMapping("/app/store")
public class AppStoreController extends BaseController {

    @Autowired
    private StoreService storeService;

    @Autowired
    private StoreValidator storeValidator;

    @Autowired
    private StoreAssembler storeAssembler;

    /**
     * 查询本人店铺列表
     */
//    @MchRequired
    @ApiOperation("查询本人店铺列表")
    @GetMapping("/list")
    public TableDataInfo list(@Validated(ValidGroup.Query.class) StoreQuery store) {
        startPage();
        PageHelper.orderBy("ss.group_sort asc, ss.create_time asc");
        store.setUserId(getUserId());
        List<StoreVo> list = storeService.selectSmStoreList(store);
        // 拼接设备数量
        storeAssembler.assembleDeviceCount(list);
        // 拼接营收数据
        storeAssembler.assembleRevenue(list);
        return getDataTable(list);
    }

    /**
     * 申请修改店铺信息
     * @param data
     * @return
     */
    @ApiOperation("申请修改店铺信息")
    @PutMapping
    public AjaxResult edit(@RequestBody @Validated(ValidGroup.FrontUpdate.class) StoreBO data) {
        StoreVo store = storeService.selectSmStoreById(data.getStoreId());
        if (!storeValidator.canOperaStore(store, getUserId())) {
            return error("您无权修改该店铺");
        }
        data = data.filterUpdateByApp();
        ServiceUtil.assertion(storeValidator.preUpdateByApp(data));
        return toAjax(storeService.updateApply(data));
    }

    @ApiOperation("修改店铺配置")
    @PutMapping("/config")
    public AjaxResult configStore(@RequestBody @Validated(ValidGroup.FrontUpdate.class) StoreBO data) {
        StoreVo store = storeService.selectSmStoreById(data.getStoreId());
        if (!storeValidator.canOperaStore(store, getUserId())) {
            return error("这不是您的店铺，无法修改");
        }
        data = data.filterConfigByApp();
        return toAjax(storeService.updateSmStore(data));
    }

    /**
     * 删除店铺信息
     * @param storeId
     * @return
     */
//    @MchRequired
    @ApiOperation("删除店铺信息")
    @DeleteMapping("/{storeId}")
    public AjaxResult delete(@PathVariable Long storeId) {
        if (storeValidator.canOperaStore(storeId, getUserId())) {
            return error("您无权删除该店铺");
        }

        List<Long> storeIds = Collections.singletonList(storeId);
        ServiceUtil.assertion(storeValidator.preLogicDelByApp(storeIds));
        return AjaxResult.success(storeService.logicDel(storeIds));
    }

//    @MchRequired
    @ApiOperation("申请新增店铺")
    @PostMapping
    public AjaxResult add(@RequestBody @Validated(ValidGroup.FrontCreate.class) StoreBO store) {
        store = store.filterCreateByApp();
        store.setUserId(getUserId());
        ServiceUtil.assertion(storeValidator.preCreateByApp(store));
        return toAjax(storeService.insertAndApply(store));
    }


//    @MchRequired
    @ApiOperation("调整店铺排序")
    @PutMapping("/changeSort")
    public AjaxResult changeSort(@RequestBody List<Store> list) {
        if (!storeValidator.canOperaAllStore(CollectionUtils.map(list, Store::getStoreId), getUserId())) {
            return error("您无权操作这些店铺");
        }
        ServiceUtil.assertion(storeValidator.preChangeSortByApp(list));
        return AjaxResult.success(storeService.changeSort(list));
    }

    @ApiOperation("获取当前用户店铺列表及其数量")
    @GetMapping("/listCount")
    @JsonView(StoreView.ListCount.class)
    public AjaxResult listCount() {
        StoreQuery query = new StoreQuery();
        query.setUserId(getUserId());
        return AjaxResult.success(storeService.listCount(query));
    }

    @ApiOperation("获取附近的店铺")
    @GetMapping("/listNearBy")
    @JsonView(JsonViewProfile.App.class)
    @Anonymous
    public AjaxResult listNearBy(@Validated(ValidGroup.Query.class) StoreQuery query) {
        query.setShow(true);
        query.setEnabled(true);
        List<StoreVo> list = storeService.listNearBy(query);
        storeAssembler.assembleDeviceCount(list);
        return success(list);
    }

    @ApiOperation("获取店铺信息")
    @GetMapping("/{storeId}")
    @JsonView(JsonViewProfile.App.class)
    @Anonymous
    public AjaxResult getDetail(@PathVariable @ApiParam("店铺ID") Long storeId) {
        StoreVo store = storeService.selectSmStoreById(storeId);
        List<StoreVo> list = Collections.singletonList(store);
        storeAssembler.assembleDeviceCount(list);           // 总设备数量
        storeAssembler.assembleAvailableDeviceCount(list);  // 可共享设备数量
        return success(store);
    }

//    @MchRequired
    @ApiOperation("商户获取店铺信息")
    @GetMapping("/mch/{storeId}")
    public AjaxResult getMchDetail(@PathVariable @ApiParam("店铺ID") Long storeId) {
        ServiceUtil.assertion(!storeValidator.canViewStore(storeId, getUserId()), "您无权查看该店铺");
        StoreVo store = storeService.selectSmStoreById(storeId);
        List<StoreVo> storeList = Collections.singletonList(store);
        storeAssembler.assembleDeviceCount(storeList);  // 总设备数量
        storeAssembler.assembleRevenue(storeList);      // 经营信息
        storeAssembler.assembleOperator(storeList, getUserId());
        return success(store);
    }

//    @MchRequired
    @ApiOperation("切换默认店铺")
    @PutMapping("/{storeId}/setDefault")
    public AjaxResult setDefaultStore(@PathVariable Long storeId) {
        Long userId = getUserId();
        if (!storeValidator.canOperaStore(storeId, userId)) {
            return error("您无权操作该店铺");
        }
        ServiceUtil.assertion(storeValidator.preSetDefaultByApp(userId, storeId));
        return success(storeService.setDefault(userId, storeId));
    }

}
