package com.starry.admin.modules.personnel.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.starry.admin.common.exception.CustomException;
import com.starry.admin.modules.clerk.module.entity.PlayClerkUserInfoEntity;
import com.starry.admin.modules.clerk.service.IPlayClerkUserInfoService;
import com.starry.admin.modules.personnel.module.entity.PlayPersonnelGroupInfoEntity;
import com.starry.admin.modules.personnel.module.vo.PlayPersonnelGroupInfoEditAddInfoVo;
import com.starry.admin.modules.personnel.module.vo.PlayPersonnelGroupInfoEditBaseInfoVo;
import com.starry.admin.modules.personnel.module.vo.PlayPersonnelGroupInfoQueryVo;
import com.starry.admin.modules.personnel.module.vo.PlayPersonnelGroupInfoReturnVo;
import com.starry.admin.modules.personnel.service.IPlayPersonnelGroupInfoService;
import com.starry.admin.modules.system.entity.SysUserEntity;
import com.starry.admin.modules.system.service.SysRoleService;
import com.starry.admin.modules.system.service.SysUserRoleService;
import com.starry.admin.modules.system.service.SysUserService;
import com.starry.common.annotation.Log;
import com.starry.common.enums.BusinessType;
import com.starry.common.result.R;
import com.starry.common.utils.ConvertUtil;
import com.starry.common.utils.IdUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 店员分组信息Controller
 *
 * @author admin
 * @since 2024-05-31
 */
@RestController
@RequestMapping("/personnel/group")
public class PlayPersonnelGroupInfoController {

    @Resource
    private IPlayPersonnelGroupInfoService playClerkGroupInfoService;


    @Resource
    private IPlayClerkUserInfoService playClerkUserInfoService;

    @Resource
    private SysUserService sysUserService;


    @Resource
    private SysRoleService sysRoleService;

    @Resource
    private SysUserRoleService userRoleService;


    /**
     * 查询店员分类信息列表
     */
    @PostMapping("/listByPage")
    public R listByPage(@Validated @RequestBody PlayPersonnelGroupInfoQueryVo vo) {
        IPage<PlayPersonnelGroupInfoReturnVo> list = playClerkGroupInfoService.selectByPage(vo);
        for (PlayPersonnelGroupInfoReturnVo record : list.getRecords()) {
            List<PlayClerkUserInfoEntity> clerkUserInfoEntities = playClerkUserInfoService.listAllByGroupId(record.getId());
            record.setTotalEmployeesNumber(clerkUserInfoEntities.size());
            Integer listingEmployeesNumber = 0;
            for (PlayClerkUserInfoEntity clerkUserInfoEntity : clerkUserInfoEntities) {
                if ("1".equals(clerkUserInfoEntity.getListingState())) {
                    listingEmployeesNumber++;
                }
            }
            record.setListingEmployeesNumber(listingEmployeesNumber);
        }
        return R.ok(list);
    }


    /**
     * 新增店员分组信息
     */
    @Log(title = "店员分组信息", businessType = BusinessType.INSERT)
    @PostMapping("/createBaseInfo")
    public R createBaseInfo(@Validated @RequestBody PlayPersonnelGroupInfoEditAddInfoVo vo) {
        //校验对应用户是否存在
        SysUserEntity sysUserEntity = sysUserService.selectUserById(vo.getSysUserId());
        //校验当前用户是否已经是组长
        PlayPersonnelGroupInfoEntity groupInfoEntity = playClerkGroupInfoService.selectByUserId(vo.getSysUserId());
        if (groupInfoEntity != null) {
            throw new CustomException("当前账号已经是组长,无法重复添加");
        }
        //添加组长配置
        PlayPersonnelGroupInfoEntity entity = ConvertUtil.entityToVo(vo, PlayPersonnelGroupInfoEntity.class);
        entity.setId(IdUtils.getUuid());
        entity.setSysUserCode(sysUserEntity.getUserCode());
        entity.setAddTime(LocalDateTime.now());
        boolean success = playClerkGroupInfoService.create(entity);
        if (success) {
            //新建组长后，添加对应的用户角色权限
            userRoleService.addUserRole(vo.getSysUserId(), sysRoleService.selectByRoleKey("leader").getRoleId());
            return R.ok("成功");
        }
        return R.error("添加失败");
    }

    /**
     * 修改店员分组信息
     */
    @Log(title = "店员分组信息", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/updateBaseInfo")
    public R updateBaseInfo(@Validated @RequestBody PlayPersonnelGroupInfoEditBaseInfoVo vo) {
        SysUserEntity sysUserEntity = sysUserService.selectUserById(vo.getSysUserId());
        //校验当前用户是否已经是组长
        PlayPersonnelGroupInfoEntity groupInfoEntity = playClerkGroupInfoService.selectByUserId(vo.getSysUserId());
        //校验当前用户是否已经是组长，只有当前用户不为组长时
        if (groupInfoEntity != null && !groupInfoEntity.getId().equals(vo.getId())) {
            throw new CustomException("当前账号已经是组长,无法重复添加");
        }
        PlayPersonnelGroupInfoEntity entity = ConvertUtil.entityToVo(vo, PlayPersonnelGroupInfoEntity.class);
        entity.setSysUserCode(sysUserEntity.getUserCode());
        boolean success = playClerkGroupInfoService.update(entity);
        if (success) {
            //新建组长后，添加对应的用户角色权限
            userRoleService.addUserRole(vo.getSysUserId(), sysRoleService.selectByRoleKey("leader").getRoleId());
            return R.ok("成功");
        }
        return R.error("修改失败");
    }


    /**
     * 删除店员分组信息
     */
    @Log(title = "店员分组信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R remove(@PathVariable String[] ids) {
        for (String id : ids) {
            List<PlayClerkUserInfoEntity> clerkUserInfoEntities = playClerkUserInfoService.listAllByGroupId(id);
            if (!clerkUserInfoEntities.isEmpty()) {
                throw new CustomException("分组中存在店员,禁止删除");
            }
        }
        Long ruleId = sysRoleService.selectByRoleKey("leader").getRoleId();
        for (String id : ids) {
            // 判断数据是否存在
            PlayPersonnelGroupInfoEntity entity = playClerkGroupInfoService.selectPlayClerkGroupInfoById(id);
            //删除组长
            playClerkGroupInfoService.deletePlayClerkGroupInfoById(id);
            //删除对应的权限信息
            userRoleService.delUserRole(entity.getSysUserId(), ruleId);

        }
        return R.ok();
    }
}
