package com.jeequan.jeepay.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.entity.SysUser;
import com.jeequan.jeepay.db.entity.SysUserEntity;
import com.jeequan.jeepay.db.entity.SysUserEntruleRela;
import com.jeequan.jeepay.service.mapper.SysUserEntruleRelaMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户<->权限规则 关联表  服务实现类
 * </p>
 *
 * @author [mybatis plus generator]
 * @since 2022-11-29
 */
@Service
public class SysUserEntruleRelaService extends ServiceImpl<SysUserEntruleRelaMapper, SysUserEntruleRela> {


    @Autowired SysUserService sysUserService;

    @Transactional(rollbackFor = Exception.class)
    public void userRela(SysUserEntity sysUserEntity, String rules) {
        if (SysUser.UEST_TYPE_DIRECTOR == sysUserEntity.getUserType() || SysUser.UEST_TYPE_CASHIER == sysUserEntity.getUserType()) {

            SysUserEntruleRela dbRecord = getById(sysUserEntity.getSysUserId());

            // 关联参数不为空
            SysUserEntruleRela entruleRela = new SysUserEntruleRela();
            entruleRela.setSysUserId(sysUserEntity.getSysUserId());
            entruleRela.setRules(rules);
            if(dbRecord != null){
                updateById(entruleRela);
            }else{
                save(entruleRela);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateUserEntRoles(Long sysUserId, Byte state, String ruleName) {

        SysUserEntruleRela dbRela = getById(sysUserId);

        List<String> ruleNameList = new ArrayList<>();

        // 格式化
        if (dbRela != null && StringUtils.isNotEmpty(dbRela.getRules())) {
            ruleNameList = JSON.parseArray(dbRela.getRules(), String.class);
        }

        // 插入
        if (state == CS.YES && !ruleNameList.contains(ruleName)) {
            ruleNameList.add(ruleName);
        }

        // 删除
        if (state == CS.NO) {
            List<String> newList = new ArrayList<>();
            for (String s : ruleNameList) {
                if (ruleName.equals(s)) {
                    continue;
                }
                newList.add(s);
            }
            ruleNameList = newList;
        }

        if (dbRela == null) {

            SysUserEntruleRela sysUserEntruleRela = new SysUserEntruleRela();
            sysUserEntruleRela.setSysUserId(sysUserId);
            sysUserEntruleRela.setRules(JSON.toJSONString(ruleNameList));
            this.save(sysUserEntruleRela);

        } else {

            dbRela.setRules(JSON.toJSONString(ruleNameList));
            updateById(dbRela);

        }
    }

}
