package com.ruoyi.app.stall;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.app.utils.RsaMima;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.InfoUser;
import com.ruoyi.system.domain.PosStore;
import com.ruoyi.system.mapper.InfoUserMapper;
import com.ruoyi.system.service.IInfoUserService;
import com.ruoyi.system.service.IPosStoreService;
import com.ruoyi.system.service.IUserWalletService;
import com.ruoyi.system.utils.Auth;
import com.ruoyi.system.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 摊位管理Controller
 */
@RestController
@RequestMapping("/stall")
public class StallController extends BaseController {

    @Autowired
    private IPosStoreService posStoreService;

    @Autowired
    private IInfoUserService infoUserService;

    @Autowired
    private InfoUserMapper infoUserMapper;

    @Autowired
    private IUserWalletService userWalletService;

    /**
     * 获取摊位列表
     * 夜市用户(type=3)：返回自己创建的所有摊位
     * 摊位主(type=4)：返回自己关联的摊位
     */
    @Anonymous
    @Auth
    @GetMapping("/list")
    public AjaxResult getStallList(@RequestHeader String token) {
        JwtUtil jwtUtil = new JwtUtil();
        String userId = jwtUtil.getusid(token);
        InfoUser loginUser = infoUserService.selectInfoUserByUserId(Long.valueOf(userId));

        if ("4".equals(loginUser.getUserType())) {
            // 摊位主：根据 storeId 获取关联的摊位
            if (loginUser.getStoreId() == null) {
                return error("该摊位主未关联摊位");
            }
            PosStore store = posStoreService.selectPosStoreById(loginUser.getStoreId());
            return success(store != null ? java.util.Collections.singletonList(store) : java.util.Collections.emptyList());
        }

        // 夜市用户：获取自己创建的所有摊位
        PosStore query = new PosStore();
        query.setUserId(Long.valueOf(userId));
        List<PosStore> list = posStoreService.selectPosStoreList(query);
        return success(list);
    }

    /**
     * 创建摊位
     */
    @Anonymous
    @Auth
    @PostMapping("/add")
    @Transactional
    public AjaxResult addStall(@RequestHeader String token, @RequestBody PosStore posStore) {
        JwtUtil jwtUtil = new JwtUtil();
        String userId = jwtUtil.getusid(token);
        posStore.setUserId(Long.valueOf(userId));
        posStore.setIsStall(1);
        posStore.setNightMarketId(Long.valueOf(userId));
        posStoreService.insertPosStore(posStore);
        // 创建摊位钱包
        userWalletService.createStallWallet(Long.valueOf(posStore.getId()));
        return success(MessageUtils.message("no.success"), posStore);
    }

    /**
     * 编辑摊位
     */
    @Anonymous
    @Auth
    @PostMapping("/editStall")
    @Transactional
    public AjaxResult editStall(@RequestHeader String token, @RequestBody PosStore posStore) {
        JwtUtil jwtUtil = new JwtUtil();
//        String userId = jwtUtil.getusid(token);
//        posStore.setUserId(Long.valueOf(userId));
//        posStore.setIsStall(1);
//        posStore.setNightMarketId(Long.valueOf(userId));
        posStoreService.saveOrUpdate(posStore);
        return success(MessageUtils.message("no.success"), posStore);
    }



    /**
     * 为摊位创建摊位主账号
     */
    @Anonymous
    @Auth
    @PostMapping("/addOwner")
    @Transactional
    public AjaxResult addStallOwner(@RequestHeader String token, @RequestBody InfoUser stallOwner) throws Exception {
        JwtUtil jwtUtil = new JwtUtil();
        String userId = jwtUtil.getusid(token);
        // 校验摊位属于当前夜市用户
        if (stallOwner.getStoreId() == null) {
            return error("请指定摊位ID");
        }
        PosStore store = posStoreService.selectPosStoreById(stallOwner.getStoreId());
        if (store == null || !store.getIsStall().equals(1)) {
            return error("摊位不存在");
        }
        if (!store.getUserId().equals(Long.valueOf(userId))) {
            return error("无权操作此摊位");
        }

        // 校验必填字段
        if (stallOwner.getUserName() == null || stallOwner.getUserName().isEmpty()) {
            return error("用户名不能为空");
        }
        if (stallOwner.getPhone() == null || stallOwner.getPhone().isEmpty()) {
            return error("手机号不能为空");
        }
        if (stallOwner.getPassword() == null || stallOwner.getPassword().isEmpty()) {
            return error("密码不能为空");
        }

        // 检查用户名是否已存在
        InfoUser existName = infoUserService.lambdaQuery()
                .eq(InfoUser::getUserName, stallOwner.getUserName())
                .eq(InfoUser::getDelFlag, "0")
                .one();
        if (existName != null) {
            return error("用户名已存在");
        }

        // 检查手机号是否已注册
        InfoUser existUser = infoUserService.lambdaQuery()
                .eq(InfoUser::getPhone, stallOwner.getPhone())
                .eq(InfoUser::getDelFlag, "0")
                .one();
        if (existUser != null) {
            return error("该手机号已注册");
        }

        // 设置摊位主属性
        stallOwner.setUserType("4");
        stallOwner.setStatus("0");
        stallOwner.setDelFlag("0");
        stallOwner.setAuditStatus("1");

        infoUserService.insertInfoUser(stallOwner);
        return success(MessageUtils.message("no.success"), stallOwner);
    }

    /**
     * 获取摊位下的摊位主列表
     */
    @Anonymous
    @Auth
    @GetMapping("/owners")
    public AjaxResult getStallOwners(@RequestParam Long storeId) {
        List<InfoUser> list = infoUserMapper.selectStallOwnersByStoreId(storeId);
        return success(list);
    }

    /**
     * 禁用摊位主
     */
    @Anonymous
    @Auth
    @PutMapping("/disableOwner")
    public AjaxResult disableStallOwner(@RequestParam Long userId) {
        InfoUser user = infoUserService.selectInfoUserByUserId(userId);
        if (user == null || !"4".equals(user.getUserType())) {
            return error("摊位主不存在");
        }
        user.setStatus("1");
        infoUserService.updateInfoUser(user);
        return success();
    }

    /**
     * 启用摊位主
     */
    @Anonymous
    @Auth
    @PutMapping("/enableOwner")
    public AjaxResult enableStallOwner(@RequestParam Long userId) {
        InfoUser user = infoUserService.selectInfoUserByUserId(userId);
        if (user == null || !"4".equals(user.getUserType())) {
            return error("摊位主不存在");
        }
        user.setStatus("0");
        infoUserService.updateInfoUser(user);
        return success();
    }

    /**
     * 删除摊位主（逻辑删除）
     */
    @Anonymous
    @Auth
    @DeleteMapping("/deleteOwner")
    public AjaxResult deleteStallOwner(@RequestParam Long userId) {
        InfoUser user = infoUserService.selectInfoUserByUserId(userId);
        if (user == null || !"4".equals(user.getUserType())) {
            return error("摊位主不存在");
        }
        infoUserService.deleteInfoUserByUserId(userId);
        return success();
    }

    /**
     * C端扫码：获取夜市下所有摊位列表（公用码扫码入口）
     */
    @Anonymous
    @GetMapping("/market/stores")
    public AjaxResult marketStores(@RequestParam Long nightMarketId,
                                   @RequestParam(required = false) Long tableId) {
        QueryWrapper<PosStore> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("night_market_id", nightMarketId);
        queryWrapper.eq("is_stall", 1);
        queryWrapper.eq("off_shelf", "0");
        queryWrapper.select("id", "pos_name", "image", "logo", "brief_introduction");
        List<PosStore> list = posStoreService.list(queryWrapper);
        return success(list);
    }
}
