package com.changhu.module.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.lang.func.LambdaUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.changhu.common.db.enums.IsEnable;
import com.changhu.common.db.enums.MiniProgramUserIdentity;
import com.changhu.common.db.enums.UserType;
import com.changhu.common.enums.ResultCode;
import com.changhu.common.exception.MessageException;
import com.changhu.common.pojo.vo.SelectNodeVo;
import com.changhu.common.utils.UserUtil;
import com.changhu.module.management.mapper.ManagementSecurityUnitUserMapper;
import com.changhu.module.management.pojo.entity.ManagementSecurityUnitUser;
import com.changhu.module.management.pojo.params.ManagementSecurityUnitUserSaveOrUpdateParams;
import com.changhu.module.management.pojo.queryParams.ManagementSecurityUnitUserPagerQueryParams;
import com.changhu.module.management.pojo.vo.ManagementSecurityUnitUserPagerVo;
import com.changhu.module.management.service.SecurityService;
import com.changhu.module.miniProgram.mapper.MiniProgramUserMapper;
import com.changhu.module.miniProgram.pojo.entity.MiniProgramUser;
import com.changhu.support.mybatisplus.pojo.entity.BaseEntity;
import com.changhu.support.mybatisplus.pojo.params.PageParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 20252
 * @createTime 2024/9/11 上午10:17
 * @desc SecurityServiceImpl...
 */
@Service
public class SecurityServiceImpl implements SecurityService {

    @Autowired
    private ManagementSecurityUnitUserMapper managementSecurityUnitUserMapper;

    @Autowired
    private MiniProgramUserMapper miniProgramUserMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void userSaveOrUpdate(ManagementSecurityUnitUserSaveOrUpdateParams saveOrUpdateParams) {
        //查看手机号是否已存在
        boolean exists = Db.lambdaQuery(ManagementSecurityUnitUser.class)
                .ne(saveOrUpdateParams.getSnowFlakeId() != null, BaseEntity::getSnowFlakeId, saveOrUpdateParams.getSnowFlakeId())
                .eq(ManagementSecurityUnitUser::getTelephone, saveOrUpdateParams.getTelephone())
                .exists();
        if (exists) {
            throw new MessageException("该手机号已存在");
        }

        ManagementSecurityUnitUser managementSecurityUnitUser = BeanUtil.copyProperties(saveOrUpdateParams, ManagementSecurityUnitUser.class);
        //新增 需要补全一些信息
        if (managementSecurityUnitUser.getSnowFlakeId() == null) {
            String account = RandomUtil.randomString(6);
            boolean accExits = Db.lambdaQuery(ManagementSecurityUnitUser.class)
                    .eq(ManagementSecurityUnitUser::getAccount, account)
                    .exists();
            if (accExits) {
                throw new MessageException("生成的账号已存在 请重新提交生成");
            }
            //生成账号
            managementSecurityUnitUser.setAccount(account);
            if (!UserType.MANAGEMENT_SECURITY.equals(UserUtil.getUserType())) {
                throw new MessageException("客户端类型不对");
            }
            //补全单位
            managementSecurityUnitUser.setSecurityUnitId(UserUtil.getUnitId());
            //生成密码
            String passWordEncrypt = UserUtil.passWordEncrypt(UserUtil.DEFAULT_PASSWORD);
            List<String> saltAndPassWord = StrUtil.split(passWordEncrypt, "$$");
            managementSecurityUnitUser.setSalt(saltAndPassWord.get(0));
            managementSecurityUnitUser.setPassword(saltAndPassWord.get(1));
        }
        Db.saveOrUpdate(managementSecurityUnitUser);
    }

    @Override
    public Page<ManagementSecurityUnitUserPagerVo> userPager(PageParams<ManagementSecurityUnitUserPagerQueryParams, ManagementSecurityUnitUserPagerVo> queryParams) {
        return managementSecurityUnitUserMapper.pager(queryParams.getPage(), queryParams.getParams());
    }

    @Override
    public void userDeleteById(Long managementSecurityUnitUserId) {
        Long unitId = UserUtil.getUnitId();
        Long l = Db.lambdaQuery(ManagementSecurityUnitUser.class)
                .eq(BaseEntity::getSnowFlakeId, managementSecurityUnitUserId)
                .oneOpt()
                .map(ManagementSecurityUnitUser::getSecurityUnitId)
                .orElseThrow(() -> new MessageException(ResultCode.USER_NOT_FOUND));
        if (!unitId.equals(l)) {
            throw new MessageException("单位不匹配,无权操作");
        }
        boolean b = Db.removeById(managementSecurityUnitUserId, ManagementSecurityUnitUser.class);
        if (!b) {
            throw new MessageException();
        }
    }

    @Override
    public List<SelectNodeVo<Long>> listProjectManager() {
        String tel = LambdaUtil.getFieldName(MiniProgramUser::getTelephone);
        String sex = LambdaUtil.getFieldName(MiniProgramUser::getSex);
        return miniProgramUserMapper.selectList(Wrappers.<MiniProgramUser>lambdaQuery()
                        .eq(MiniProgramUser::getIsEnable, IsEnable.TRUE)
                        .eq(MiniProgramUser::getIdentity, MiniProgramUserIdentity.PROJECT_MANAGER)
                        .eq(MiniProgramUser::getUnitId, UserUtil.getUnitId()))
                .stream()
                .map(item -> SelectNodeVo.<Long>builder()
                        .value(item.getSnowFlakeId())
                        .label(item.getName())
                        .extData(Dict.of(
                                tel, item.getTelephone(),
                                sex, item.getSex()
                        ))
                        .build())
                .toList();
    }
}
