package com.ruoyi.web.bst;

import com.ruoyi.bst.booth.domain.Booth;
import com.ruoyi.bst.booth.domain.BoothQuery;
import com.ruoyi.bst.booth.domain.BoothVO;
import com.ruoyi.bst.booth.service.BoothService;
import com.ruoyi.bst.booth.service.BoothValidator;
import com.ruoyi.bst.device.domain.Device;
import com.ruoyi.bst.device.domain.DeviceQuery;
import com.ruoyi.bst.device.domain.DeviceVO;
import com.ruoyi.bst.device.service.DeviceService;
import com.ruoyi.bst.device.service.DeviceValidator;
import com.ruoyi.bst.part.service.PartValidator;
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.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.parameters.P;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

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

/**
 * 卡座Controller
 *
 * @author ruoyi
 * @date 2025-04-18
 */
@RestController
@RequestMapping("/bst/booth")
public class BoothController extends BaseController {
    @Autowired
    private BoothService boothService;
    @Autowired
    private PartValidator partValidator;
    @Autowired
    private BoothValidator boothValidator;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private UserService userService;
    @Autowired
    private StoreValidator storeValidator;
    @Autowired
    private DeviceValidator deviceValidator;

    /**
     * 查询卡座列表
     */
    @PreAuthorize("@ss.hasPermi('bst:booth:list')")
    @GetMapping("/list")
    public TableDataInfo list(BoothQuery query) {
        startPage();
        startOrderBy();
        query.setScope(true);
        query.setDeleted(false);
        query.addStorePermission(StoreStaffPermission.BOOTH_VIEW.getCode());
        List<BoothVO> list = boothService.selectBoothList(query);
        return getDataTable(list);
    }

    /**
     * 导出卡座列表
     */
    @PreAuthorize("@ss.hasPermi('bst:booth:export')")
    @Log(title = "卡座", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BoothQuery query) {
        query.setScope(true);
        List<BoothVO> list = boothService.selectBoothList(query);
        ExcelUtil<BoothVO> util = new ExcelUtil<BoothVO>(BoothVO.class);
        util.exportExcel(response, list, "卡座数据");
    }

    /**
     * 获取卡座详细信息
     */
    @PreAuthorize("@ss.hasPermi('bst:booth:query')")
    @GetMapping(value = "/{boothId}")
    public AjaxResult getInfo(@PathVariable("boothId") Long boothId ,boolean needDevices) {
        BoothVO booth = boothService.selectBoothByBoothId(boothId, true);
        // 查询卡座下的设备信息
        DeviceQuery deviceQuery = new DeviceQuery();
        deviceQuery.setBoothId(boothId);
        if (needDevices) {
            List<DeviceVO> devices = deviceService.selectDeviceList(deviceQuery);
            if (devices != null && !devices.isEmpty()) {
                booth.setDevices(devices);
            }
        }
        return success(booth);
    }

    /**
     * 新增卡座
     */
    @PreAuthorize("@ss.hasPermi('bst:booth:add')")
    @Log(title = "卡座", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody @Validated(ValidGroup.Create.class) Booth booth) {
        // 判断用户能否选择分区
        if (!partValidator.canCheckForPart(booth.getPartId())) {
            return AjaxResult.error("您无权选择ID为" + booth.getPartId() + "的分区");
        }
        // 卡座编号唯一性校验
        return toAjax(boothService.insertBooth(booth));
    }

    /**
     * 修改卡座
     */
    @PreAuthorize("@ss.hasPermi('bst:booth:edit')")
    @Log(title = "卡座", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody @Validated(ValidGroup.Update.class) Booth booth) {
        if (!boothValidator.canEdit(booth.getBoothId())) {
            return AjaxResult.error("您没有权限修改ID为" + booth.getBoothId() + "的卡座");
        }
        return toAjax(boothService.updateBooth(booth));
    }

    /**
     * 删除卡座
     */
    @PreAuthorize("@ss.hasPermi('bst:booth:remove')")
    @Log(title = "卡座", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        if (!boothValidator.canDeleteAll(ids)) {
            return AjaxResult.error("您没有权限删除ID为" + ids + "的卡座");
        }
        return toAjax(boothService.deleteBoothByBoothIds(ids));
    }

    @ApiOperation("设备绑定卡座")
    @PreAuthorize("@ss.hasPermi('bst:booth:bindBooth')")
    @PutMapping("/bindBooth")
    public AjaxResult bindBooth(@RequestBody Device device, @RequestParam Long boothId) {
        if (device.getDeviceId() == null && device.getDeviceNo() == null) {
            return AjaxResult.error("设备ID和SN不能同时为空");
        }
        if (boothId == null) {
            return AjaxResult.error("卡座ID不能为空");
        }

        if (!boothValidator.canEdit(boothId)) {
            return AjaxResult.error("您无更改该卡座相关的权限");
        }
        BoothVO booth = boothService.selectBoothByBoothId(boothId);
        if (booth == null) {
            return AjaxResult.error("卡座不存在");
        }
        if (!storeValidator.canEdit(booth.getStoreId())) {
            return AjaxResult.error("您无权限操作当前店铺信息");
        }

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

        // 绑定设备
        if (device.getDeviceId() != null) {
            return AjaxResult.success("操作成功", deviceService.bindBoothById(device.getDeviceId(), booth));
        } else {
            return AjaxResult.success("操作成功", deviceService.bindBoothBySN(device.getDeviceNo(), booth));
        }
    }

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

        // 卡座相关权限校验
        if (!boothValidator.canEdit(boothId)) {
            return AjaxResult.error("您无更改该卡座相关的权限");
        }
        BoothVO booth = boothService.selectBoothByBoothId(boothId);
        if (booth == null) {
            return AjaxResult.error("卡座不存在");
        }

        // 店铺相关权限校验
        if (!storeValidator.canEdit(booth.getStoreId())) {
            return AjaxResult.error("您无权限操作当前店铺信息");
        }

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

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