package com.bomaos.common.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bomaos.common.core.annotation.OperLog;
import com.bomaos.common.core.web.*;
import com.bomaos.common.system.entity.Supplier;
import com.bomaos.common.system.entity.User;
import com.bomaos.common.system.service.SupplierService;
import com.bomaos.common.system.service.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 供应商管理
 */
@Controller
@RequestMapping("/sys/supplier")
public class SupplierController extends BaseController {

    /** 供应商角色ID */
    private static final Integer SUPPLIER_ROLE_ID = 4;

    @Autowired
    private SupplierService supplierService;

    @Autowired
    private UserService userService;

    @RequiresPermissions("sys:supplier:view")
    @RequestMapping()
    public String view() {
        return "system/supplier.html";
    }

    /**
     * 分页查询供应商
     */
    @RequiresPermissions("sys:supplier:list")
    @OperLog(value = "供应商管理", desc = "分页查询")
    @ResponseBody
    @RequestMapping("/page")
    public PageResult<Supplier> page(HttpServletRequest request) {
        PageParam<Supplier> pageParam = new PageParam<>(request);
        pageParam.setDefaultOrder(null, new String[]{"create_time"});
        return supplierService.listPage(pageParam);
    }

    /**
     * 查询全部供应商
     */
    @RequiresPermissions("sys:supplier:list")
    @OperLog(value = "供应商管理", desc = "查询全部")
    @ResponseBody
    @RequestMapping("/list")
    public JsonResult list(HttpServletRequest request) {
        PageParam<Supplier> pageParam = new PageParam<>(request);
        List<Supplier> records = supplierService.listAll(pageParam.getNoPageParam());
        return JsonResult.ok().setData(pageParam.sortRecords(records));
    }

    /**
     * 根据id查询供应商
     */
    @RequiresPermissions("sys:supplier:list")
    @OperLog(value = "供应商管理", desc = "根据id查询")
    @ResponseBody
    @RequestMapping("/get")
    public JsonResult get(Integer id) {
        return JsonResult.ok().setData(supplierService.getById(id));
    }

    /**
     * 添加供应商（同时创建登录账号）
     */
    @Transactional
    @RequiresPermissions("sys:supplier:save")
    @OperLog(value = "供应商管理", desc = "添加", param = false, result = true)
    @ResponseBody
    @RequestMapping("/save")
    public JsonResult save(Supplier supplier) {
        if (supplier.getUsername() == null || supplier.getUsername().trim().isEmpty()) {
            return JsonResult.error("登录账号不能为空");
        }
        if (supplier.getPassword() == null || supplier.getPassword().trim().isEmpty()) {
            return JsonResult.error("登录密码不能为空");
        }
        // 检查账号是否已存在
        User existUser = userService.getByUsername(supplier.getUsername().trim());
        if (existUser != null) {
            return JsonResult.error("登录账号已存在");
        }
        // 创建供应商
        supplier.setCreateTime(new Date());
        supplier.setUpdateTime(new Date());
        if (!supplierService.save(supplier)) {
            return JsonResult.error("添加失败");
        }
        // 创建关联的登录账号
        User user = new User();
        user.setUsername(supplier.getUsername().trim());
        user.setPassword(userService.encodePsw(supplier.getPassword()));
        user.setNickName(supplier.getNickName() != null && !supplier.getNickName().trim().isEmpty()
                ? supplier.getNickName().trim() : supplier.getName());
        user.setSupplierId(supplier.getId());
        user.setState(0);
        user.setRoleIds(Collections.singletonList(SUPPLIER_ROLE_ID));
        if (!userService.saveUser(user)) {
            return JsonResult.error("创建登录账号失败");
        }
        return JsonResult.ok("添加成功");
    }

    /**
     * 修改供应商（同步更新关联用户昵称）
     */
    @Transactional
    @RequiresPermissions("sys:supplier:update")
    @OperLog(value = "供应商管理", desc = "修改", param = false, result = true)
    @ResponseBody
    @RequestMapping("/update")
    public JsonResult update(Supplier supplier) {
        supplier.setUpdateTime(new Date());
        if (!supplierService.updateById(supplier)) {
            return JsonResult.error("修改失败");
        }
        // 同步更新关联用户的昵称
        if (supplier.getNickName() != null && !supplier.getNickName().trim().isEmpty()) {
            User linkedUser = userService.getOne(
                    new QueryWrapper<User>().eq("supplier_id", supplier.getId()));
            if (linkedUser != null) {
                User updateUser = new User();
                updateUser.setUserId(linkedUser.getUserId());
                updateUser.setNickName(supplier.getNickName().trim());
                userService.updateById(updateUser);
            }
        }
        return JsonResult.ok("修改成功");
    }

    /**
     * 删除供应商（同时删除关联用户）
     */
    @Transactional
    @RequiresPermissions("sys:supplier:remove")
    @OperLog(value = "供应商管理", desc = "删除", result = true)
    @ResponseBody
    @RequestMapping("/remove")
    public JsonResult remove(Integer id) {
        // 删除关联用户
        userService.remove(new QueryWrapper<User>().eq("supplier_id", id));
        // 删除供应商
        if (supplierService.removeById(id)) {
            return JsonResult.ok("删除成功");
        }
        return JsonResult.error("删除失败");
    }

    /**
     * 批量删除供应商（同时删除关联用户）
     */
    @Transactional
    @RequiresPermissions("sys:supplier:remove")
    @OperLog(value = "供应商管理", desc = "批量删除", result = true)
    @ResponseBody
    @RequestMapping("/removeBatch")
    public JsonResult removeBatch(@RequestBody List<Integer> ids) {
        // 批量删除关联用户
        userService.remove(new QueryWrapper<User>().in("supplier_id", ids));
        // 批量删除供应商
        if (supplierService.removeByIds(ids)) {
            return JsonResult.ok("删除成功");
        }
        return JsonResult.error("删除失败");
    }

    /**
     * 重置供应商账号密码
     */
    @RequiresPermissions("sys:supplier:update")
    @OperLog(value = "供应商管理", desc = "重置密码", param = false, result = true)
    @ResponseBody
    @RequestMapping("/psw/reset")
    public JsonResult resetPsw(Integer id, String password) {
        if (password == null || password.trim().isEmpty()) {
            return JsonResult.error("密码不能为空");
        }
        User linkedUser = userService.getOne(
                new QueryWrapper<User>().eq("supplier_id", id));
        if (linkedUser == null) {
            return JsonResult.error("该供应商没有关联的登录账号");
        }
        User updateUser = new User();
        updateUser.setUserId(linkedUser.getUserId());
        updateUser.setPassword(userService.encodePsw(password));
        if (userService.updateById(updateUser)) {
            return JsonResult.ok("重置成功");
        }
        return JsonResult.error("重置失败");
    }

}
