package com.ruoyi.web.bst;

import com.ruoyi.bst.booth.domain.BoothVO;
import com.ruoyi.bst.device.domain.Device;
import com.ruoyi.bst.device.service.DeviceService;
import com.ruoyi.bst.device.service.DeviceValidator;
import com.ruoyi.bst.part.domain.PartQuery;
import com.ruoyi.bst.part.domain.PartVO;
import com.ruoyi.bst.store.domain.Store;
import com.ruoyi.bst.store.domain.StoreQuery;
import com.ruoyi.bst.store.domain.StoreVO;
import com.ruoyi.bst.store.service.StoreAssembler;
import com.ruoyi.bst.store.service.StoreConverter;
import com.ruoyi.bst.store.service.StoreService;
import com.ruoyi.bst.store.service.StoreValidator;
import com.ruoyi.bst.storeStaff.domain.enums.StoreStaffPermission;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.validate.ValidGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.user.service.UserValidator;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.List;

/**
 * 店铺Controller
 *
 * @author ruoyi
 * @date 2025-04-18
 */
@RestController
@RequestMapping("/bst/store")
public class StoreController extends BaseController {
    @Autowired
    private StoreService storeService;

    @Autowired
    private UserValidator userValidator;
    @Autowired
    private StoreValidator storeValidator;
    @Autowired
    private StoreConverter storeConverter;
    @Autowired
    private StoreAssembler storeAssembler;
    @Autowired
    private DeviceValidator deviceValidator;
    @Autowired
    private DeviceService deviceService;

    /**
     * 查询店铺列表
     */
    @PreAuthorize("@ss.hasPermi('bst:store:list')")
    @GetMapping("/list")
    public TableDataInfo list(StoreQuery query) {
        startPage();
        startOrderBy();
        query.setScope(true);
        query.setDeleted(false);
        query.addStorePermission(StoreStaffPermission.STORE_VIEW.getCode());
        List<StoreVO> list = storeService.selectStoreList(query);
        return getDataTable(list);
    }

    /**
     * 导出店铺列表
     */
    @PreAuthorize("@ss.hasPermi('bst:store:export')")
    @Log(title = "店铺", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, StoreQuery query) {
        query.setScope(true);
        List<StoreVO> list = storeService.selectStoreList(query);
        ExcelUtil<StoreVO> util = new ExcelUtil<StoreVO>(StoreVO.class);
        util.exportExcel(response, list, "店铺数据");
    }

    /**
     * 获取店铺详细信息
     */
    @PreAuthorize("@ss.hasPermi('bst:store:query')")
    @GetMapping(value = "/{storeId}")
    public AjaxResult getInfo(@PathVariable("storeId") Long storeId) {
        StoreVO store = storeService.selectStoreById(storeId, true);
        List<StoreVO> list = Collections.singletonList(store);
        storeAssembler.assembleDeviceCount(list);   // 设备数量
        storeAssembler.assembleRevenue(list);       // 经营数据
        return success(store);

    }

    /**
     * 新增店铺
     */
    @PreAuthorize("@ss.hasPermi('bst:store:add')")
    @Log(title = "店铺", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody @Validated(ValidGroup.Create.class) Store store) {
        // 若不能操作他人，则设置为当前用户
        if (!userValidator.canView(store.getUserId())) {
            store.setUserId(getUserId());
        }
        store.setUserId(getUserId());
        storeConverter.toPoByCreate(store);
        return toAjax(storeService.insertStore(store));
    }

    /**
     * 修改店铺
     */
    @PreAuthorize("@ss.hasPermi('bst:store:edit')")
    @Log(title = "店铺", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody @Validated(ValidGroup.Update.class) Store store) {
        if (!storeValidator.canEdit(store.getStoreId())) {
            return AjaxResult.error("您没有权限修改ID为" + store.getStoreId() + "的商铺信息");
        }
        // 若不能操作他人，则不修改用户ID
        if (!userValidator.canView(store.getUserId())) {
            store.setUserId(null);
        }
        storeConverter.toPoByUpdate(store);
        return toAjax(storeService.updateStore(store));
    }

    /**
     * 删除店铺
     */
    @PreAuthorize("@ss.hasPermi('bst:store:remove')")
    @Log(title = "店铺", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        if (!storeValidator.canDeleteAll(ids)) {
            return AjaxResult.error("您没有权限删除ID为" + ids + "的店铺信息");
        }
        return toAjax(storeService.logicDel(ids));
    }

    @ApiOperation("设备解绑店铺")
    @PreAuthorize("@ss.hasPermi('bst:store:unbindStore')")
    @PutMapping("/unbindStore")
    public AjaxResult unbindStore(@RequestBody Device device, @RequestParam Long storeId) {
        if (device.getDeviceId() == null) {
            return AjaxResult.error("设备ID不允许为空");
        }
        if (storeId == null) {
            return AjaxResult.error("店铺ID不能为空");
        }

        // 卡座相关权限校验
        if (!storeValidator.canEdit(storeId)) {
            return AjaxResult.error("您无更改该卡座相关的权限");
        }
        StoreVO store = storeService.selectStoreById(storeId);
        if (store == null) {
            return AjaxResult.error("店铺不存在");
        }

        // 设备权限校验
        if (!deviceValidator.canOperate(device.getDeviceId())){
            return AjaxResult.error("您无权限操作当设备信息");
        }

        deviceService.unbindStore(device.getDeviceId(), store);
        return AjaxResult.success("操作成功");
    }

}
