package com.ktg.iscs.service.impl;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktg.common.constant.Constants;
import com.ktg.common.core.domain.AjaxResult;
import com.ktg.common.core.domain.entity.SysRole;
import com.ktg.common.core.domain.entity.SysUser;
import com.ktg.common.core.domain.model.LoginUser;
import com.ktg.common.core.text.Convert;
import com.ktg.common.utils.DateUtils;
import com.ktg.common.utils.StringUtils;
import com.ktg.common.utils.bean.BeanUtils;
import com.ktg.framework.web.service.SysLoginService;
import com.ktg.framework.web.service.TokenService;
import com.ktg.iscs.domain.IsJobCard;
import com.ktg.iscs.domain.vo.card.IsJobCardInfoRespVO;
import com.ktg.iscs.domain.vo.card.IsJobCardLoginReqVO;
import com.ktg.iscs.mapper.IsJobCardMapper;
import com.ktg.iscs.service.IIsJobCardService;
import com.ktg.system.mapper.SysUserMapper;
import com.ktg.system.service.ISysRoleService;
import com.ktg.system.service.ISysUserService;
import com.ktg.system.strategy.AutoCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 工作卡Service业务层处理
 *
 * @author cgj
 * @date 2024-11-12
 */
@Service
public class IsJobCardServiceImpl extends ServiceImpl<IsJobCardMapper, IsJobCard> implements IIsJobCardService
{
    @Autowired
    private IsJobCardMapper isJobCardMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysLoginService sysLoginService;
    @Resource
    private ISysUserService sysUserService;
    @Resource
    private TokenService tokenService;
    @Resource
    private ISysRoleService iSysRoleService;
    @Autowired
    private AutoCodeUtil autoCodeUtil;

    /**
     * 查询工作卡
     *
     * @param cardId 工作卡主键
     * @return 工作卡
     */
    @Override
    public IsJobCard selectIsJobCardByCardId(Long cardId)
    {
        return isJobCardMapper.selectIsJobCardByCardId(cardId);
    }

    /**
     * 查询工作卡列表
     *
     * @param isJobCard 工作卡
     * @return 工作卡
     */
    @Override
    public List<IsJobCard> selectIsJobCardList(IsJobCard isJobCard)
    {
        return isJobCardMapper.selectIsJobCardList(isJobCard);
    }

    /**
     * 新增工作卡
     *
     * @param isJobCard 工作卡
     * @return 结果
     */
    @Override
    public int insertIsJobCard(IsJobCard isJobCard)
    {
        isJobCard.setCreateTime(DateUtils.getNowDate());
        return isJobCardMapper.insertIsJobCard(isJobCard);
    }

    /**
     * 修改工作卡
     *
     * @param isJobCard 工作卡
     * @return 结果
     */
    @Override
    public int updateIsJobCard(IsJobCard isJobCard)
    {
        isJobCard.setUpdateTime(DateUtils.getNowDate());
        return isJobCardMapper.updateIsJobCard(isJobCard);
    }

    /**
     * 批量删除工作卡
     *
     * @param cardIds 需要删除的工作卡主键
     * @return 结果
     */
    @Override
    public int deleteIsJobCardByCardIds(String cardIds)
    {
        Assert.notBlank(cardIds, "请选择需要删除的数据!");
        Long[] longIds = Convert.toLongArray(cardIds);
        return isJobCardMapper.deleteIsJobCardByCardIds(longIds);
    }

    /**
     * 删除工作卡信息
     *
     * @param cardId 工作卡主键
     * @return 结果
     */
    @Override
    public int deleteIsJobCardByCardId(Long cardId)
    {
        return isJobCardMapper.deleteIsJobCardByCardId(cardId);
    }

    @Override
    public String loginByCard(IsJobCardLoginReqVO reqVO) {
        Assert.notBlank(reqVO.cardNfc, "请输入卡号!");
        IsJobCard isJobCard = isJobCardMapper.selectByNfc(reqVO.cardNfc);
        Assert.notNull(isJobCard, "卡不存在!");
        Long userId = isJobCard.getUserId();
        SysUser sysUser = sysUserMapper.selectUserById(userId);
        Assert.notNull(sysUser, "没有关联用户!");
        String token = sysLoginService.loginWithoutPassword(sysUser);
        return token;
    }

    @Override
    public AjaxResult loginByCard1(IsJobCardLoginReqVO reqVO) {
        Assert.notBlank(reqVO.cardNfc, "请输入卡号!");
        IsJobCard isJobCard = isJobCardMapper.selectByNfc(reqVO.cardNfc);
        Assert.notNull(isJobCard, "卡不存在!");
        Long userId = isJobCard.getUserId();
        SysUser sysUser = sysUserMapper.selectUserById(userId);
        Assert.notNull(sysUser, "没有关联用户!");
        String token = sysLoginService.loginWithoutPassword(sysUser);
        // 生成令牌
        AjaxResult ajax = AjaxResult.success();
        ajax.put(Constants.TOKEN, token);
        ajax.put("nickName", sysUser.getNickName());
        ajax.put("userName", sysUser.getUserName());
        ajax.put("userId", sysUser.getUserId());
        return ajax;
    }

    @Override
    public IsJobCardInfoRespVO getCardInfoByLoginUser(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        Assert.notNull(loginUser, "请先登录!");
        SysUser user = sysUserService.selectUserById(loginUser.getUser().getUserId());
        Assert.notNull(user, "用户不存在!");
        IsJobCard isJobCard = isJobCardMapper.selectByUserId(user.getUserId());
        Assert.notNull(isJobCard, "用户未绑定卡!");

        List<SysRole> roleList = iSysRoleService.getRolesByUserId(user.getUserId());

        IsJobCardInfoRespVO respVO = BeanUtils.toBean(isJobCard, IsJobCardInfoRespVO.class);
        respVO.roleKeyList = roleList.stream().map(SysRole::getRoleKey).collect(Collectors.toList());
        return respVO;
    }

    @Override
    public IsJobCard getCardInfoByCardNfc(String cardNfc) {
        Assert.notBlank(cardNfc, "请输入卡号!");
        IsJobCard isJobCard = isJobCardMapper.selectByNfc(cardNfc);
        Assert.notNull(isJobCard, "该卡无效!");
        SysUser user = sysUserService.selectUserById(isJobCard.getUserId());
        isJobCard.setNickName(user.getNickName());
        isJobCard.setUserName(user.getUserName());
        return isJobCard;
    }

    @Override
    public Page<IsJobCard> getIsJobCardPage(Page<IsJobCard> page, IsJobCard isJobCard) {
        Page<IsJobCard> result = page(page, Wrappers.<IsJobCard>lambdaQuery()
                .like(StringUtils.isNotBlank(isJobCard.getCardCode()), IsJobCard::getCardCode, isJobCard.getCardCode())
                .eq(isJobCard.getCardType() != null, IsJobCard::getCardType, isJobCard.getCardType())
                .eq(isJobCard.getUserName() != null, IsJobCard::getUserName, isJobCard.getUserName())
                .orderByDesc(IsJobCard::getCardId));
        return result;
    }

    @Override
    public Boolean insertIsJobCardByCabinet(IsJobCard isJobCard) {
        Assert.isFalse(StringUtils.isBlank(isJobCard.getCardNfc()), "请给我工卡的nfc！");
        // 0.检查挂锁的nfc是否存在，存在就不允许添加
        List<IsJobCard> list = list(Wrappers.<IsJobCard>lambdaQuery()
                .eq(IsJobCard::getCardNfc, isJobCard.getCardNfc()));
        Assert.isTrue(list.isEmpty(), "该nfc的工卡已存在！");
        // 2.自动生成编码
        String cardCode = autoCodeUtil.genSerialCode("CARD_CODE", null);
        isJobCard.setCardCode(cardCode);
        isJobCard.setCardType(isJobCard.getCardType() != null ? isJobCard.getCardType() : 2);
        isJobCard.setCreateTime(DateUtils.getNowDate());
        return save(isJobCard);
    }
}
