package cn.gintone.service;

import cn.gintone.ErrorInfo;
import cn.gintone.config.AesKeyConfig;
import cn.gintone.controller.vo.UserDesRulePageReqVO;
import cn.gintone.controller.vo.UserDesRuleSaveReqVO;
import cn.gintone.dal.UserDesRuleMapper;
import cn.gintone.encryptionUtils.DataDesensitizationUtils;
import cn.gintone.entity.UserDesRuleDO;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;


import java.util.*;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 人员脱敏规则 Service 实现类
 *
 * @author 胡懿
 */
@Service
@Validated
public class UserDesRuleServiceImpl implements UserDesRuleService {

    @Resource
    private UserDesRuleMapper userDesRuleMapper;
    @Resource
    private AesKeyConfig aesKeyConfig;

    @Override
    public Long createUserDesRule(UserDesRuleSaveReqVO createReqVO) {
        // 插入
        UserDesRuleDO userDesRule = BeanUtils.toBean(createReqVO, UserDesRuleDO.class);
        userDesRuleMapper.insert(userDesRule);
        // 返回
        return userDesRule.getId();
    }

    @Override
    public void updateUserDesRule(UserDesRuleSaveReqVO updateReqVO) {
        // 校验存在
        validateUserDesRuleExists(updateReqVO.getId());
        // 更新
        UserDesRuleDO updateObj = BeanUtils.toBean(updateReqVO, UserDesRuleDO.class);
        userDesRuleMapper.updateById(updateObj);
    }

    @Override
    public void deleteUserDesRule(Long id) {
        // 校验存在
        validateUserDesRuleExists(id);
        // 删除
        userDesRuleMapper.deleteById(id);
    }

    private void validateUserDesRuleExists(Long id) {
        if (userDesRuleMapper.selectById(id) == null) {
            throw exception(ErrorInfo.USER_DES_RULE_NOT_EXISTS);
        }
    }

    @Override
    public UserDesRuleDO getUserDesRule(Long id) {
        return userDesRuleMapper.selectById(id);
    }

    @Override
    public PageResult<UserDesRuleDO> getUserDesRulePage(UserDesRulePageReqVO pageReqVO) {
        return userDesRuleMapper.selectPage(pageReqVO);
    }

    @Override
    public String userRuleDes(String userJsonStr) {
        List<UserDesRuleDO> userDesRuleDOS = userDesRuleMapper.selectList();
        Map<String, UserDesRuleDO> ruleDOMap = new HashMap<>();
        for (UserDesRuleDO userDesRuleDO : userDesRuleDOS) {
            ruleDOMap.put(userDesRuleDO.getName(), userDesRuleDO);
        }
        JSONObject resultJson = new JSONObject();
        try {
            // 将 JSON 字符串转为 JSONObject
            JSONObject jsonObject = new JSONObject(userJsonStr);
            // 遍历所有属性
            Set<String> keySet = jsonObject.keySet();
            for (String key : keySet) {
                UserDesRuleDO userDesRuleDO = ruleDOMap.get(key);
                if (null != userDesRuleDO) {
                    if (1 == userDesRuleDO.getRule()) {
                        String value = jsonObject.getStr(key);
                        String v = DataDesensitizationUtils.invalidatePhone(value, Integer.parseInt(userDesRuleDO.getValueOne()), Integer.parseInt(userDesRuleDO.getValueTwo()));
                        resultJson.put(key, v);
                    } else if (2 == userDesRuleDO.getRule()) {
                        String value = jsonObject.getStr(key);
                        String v = DataDesensitizationUtils.randomPhone(value);
                        resultJson.put(key, v);
                    } else if (3 == userDesRuleDO.getRule()) {
                        String value = jsonObject.getStr(key);
                        String v = DataDesensitizationUtils.replaceRange(value, userDesRuleDO.getValueOne(), Integer.parseInt(userDesRuleDO.getValueTwo()), Integer.parseInt(userDesRuleDO.getValueThree()));
                        resultJson.put(key, v);
                    } else if (4 == userDesRuleDO.getRule()) {
                        String value = jsonObject.getStr(key);
                        String v = DataDesensitizationUtils.encryptAES(value, aesKeyConfig.getKey());
                        resultJson.put(key, v);
                    } else if (5 == userDesRuleDO.getRule()) {
                        String value = jsonObject.getStr(key);
                        String v = DataDesensitizationUtils.shiftString(value, Integer.parseInt(userDesRuleDO.getValueOne()));
                        resultJson.put(key, v);
                    } else {
                        resultJson.put(key, jsonObject.get(key));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultJson.toString();
    }

    @Override
    public String userRuleDesArr(String userJsonArrStr) {
        List<UserDesRuleDO> userDesRuleDOS = userDesRuleMapper.selectList();
        Map<String, UserDesRuleDO> ruleDOMap = new HashMap<>();
        for (UserDesRuleDO userDesRuleDO : userDesRuleDOS) {
            ruleDOMap.put(userDesRuleDO.getName(), userDesRuleDO);
        }
        JSONArray resultJsonArr = new JSONArray();
        JSONArray jsonArray = new JSONArray(userJsonArrStr);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Set<String> keySet = jsonObject.keySet();
            JSONObject resultJson = new JSONObject();
            try {
                for (String key : keySet) {
                    UserDesRuleDO userDesRuleDO = ruleDOMap.get(key);
                    if (null != userDesRuleDO) {
                        if (1 == userDesRuleDO.getRule()) {
                            String value = jsonObject.getStr(key);
                            String v = DataDesensitizationUtils.invalidatePhone(value, Integer.parseInt(userDesRuleDO.getValueOne()), Integer.parseInt(userDesRuleDO.getValueTwo()));
                            resultJson.put(key, v);
                        } else if (2 == userDesRuleDO.getRule()) {
                            String value = jsonObject.getStr(key);
                            String v = DataDesensitizationUtils.randomPhone(value);
                            resultJson.put(key, v);
                        } else if (3 == userDesRuleDO.getRule()) {
                            String value = jsonObject.getStr(key);
                            String v = DataDesensitizationUtils.replaceRange(value, userDesRuleDO.getValueOne(), Integer.parseInt(userDesRuleDO.getValueTwo()), Integer.parseInt(userDesRuleDO.getValueThree()));
                            resultJson.put(key, v);
                        } else if (4 == userDesRuleDO.getRule()) {
                            String value = jsonObject.getStr(key);
                            String v = DataDesensitizationUtils.encryptAES(value, aesKeyConfig.getKey());
                            resultJson.put(key, v);
                        } else if (5 == userDesRuleDO.getRule()) {
                            String value = jsonObject.getStr(key);
                            String v = DataDesensitizationUtils.shiftString(value, Integer.parseInt(userDesRuleDO.getValueOne()));
                            resultJson.put(key, v);
                        } else {
                            resultJson.put(key, jsonObject.get(key));
                        }
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            resultJsonArr.add(resultJson);
        }
        return resultJsonArr.toString();
    }

    @Override
    public Boolean checkName(String name, Long id) {
        if (null != id && id != 0) {
            List<UserDesRuleDO> userDesRuleDOS = userDesRuleMapper.selectList(new LambdaQueryWrapper<UserDesRuleDO>()
                    .eq(UserDesRuleDO::getName, name)
                    .eq(UserDesRuleDO::getId, id)
            );
            if (null != userDesRuleDOS && userDesRuleDOS.size() > 0) {
                return true;
            }
        } else {
            List<UserDesRuleDO> userDesRuleDOS = userDesRuleMapper.selectList(new LambdaQueryWrapper<UserDesRuleDO>()
                    .eq(UserDesRuleDO::getName, name)
            );
            if (null != userDesRuleDOS && userDesRuleDOS.size() > 0) {
                return true;
            }
        }

        return false;
    }

    @Override
    public Map<String, Object> userRuleDesMap(Map<String, Object> map) {
        List<UserDesRuleDO> userDesRuleDOS = userDesRuleMapper.selectList();
        Map<String, UserDesRuleDO> ruleDOMap = new HashMap<>();
        for (UserDesRuleDO userDesRuleDO : userDesRuleDOS) {
            ruleDOMap.put(userDesRuleDO.getName(), userDesRuleDO);
        }
        Map<String, Object> resultMap = new HashMap<>();
        try {
            // 将 JSON 字符串转为 JSONObject
            // 遍历所有属性
            Set<Map.Entry<String, Object>> entries = map.entrySet();
            for (Map.Entry<String, Object> entry : entries) {
                String key = entry.getKey();
                UserDesRuleDO userDesRuleDO = ruleDOMap.get(key);
                if (null != userDesRuleDO) {
                    if (1 == userDesRuleDO.getRule()) {
                        String value = entry.getValue().toString();
                        String v = DataDesensitizationUtils.invalidatePhone(value, Integer.parseInt(userDesRuleDO.getValueOne()), Integer.parseInt(userDesRuleDO.getValueTwo()));
                        resultMap.put(key, v);
                    } else if (2 == userDesRuleDO.getRule()) {
                        String value = entry.getValue().toString();
                        String v = DataDesensitizationUtils.randomPhone(value);
                        resultMap.put(key, v);
                    } else if (3 == userDesRuleDO.getRule()) {
                        String value = entry.getValue().toString();
                        String v = DataDesensitizationUtils.replaceRange(value, userDesRuleDO.getValueOne(), Integer.parseInt(userDesRuleDO.getValueTwo()), Integer.parseInt(userDesRuleDO.getValueThree()));
                        resultMap.put(key, v);
                    } else if (4 == userDesRuleDO.getRule()) {
                        String value = entry.getValue().toString();
                        String v = DataDesensitizationUtils.encryptAES(value, aesKeyConfig.getKey());
                        resultMap.put(key, v);
                    } else if (5 == userDesRuleDO.getRule()) {
                        String value = entry.getValue().toString();
                        String v = DataDesensitizationUtils.shiftString(value, Integer.parseInt(userDesRuleDO.getValueOne()));
                        resultMap.put(key, v);
                    } else {
                        resultMap.put(key, entry.getValue());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultMap;
    }

    @Override
    public List<Map<String, Object>> userRuleDesListMap(List<Map<String, Object>> lisetMap) {
        List<UserDesRuleDO> userDesRuleDOS = userDesRuleMapper.selectList();
        Map<String, UserDesRuleDO> ruleDOMap = new HashMap<>();
        for (UserDesRuleDO userDesRuleDO : userDesRuleDOS) {
            ruleDOMap.put(userDesRuleDO.getName(), userDesRuleDO);
        }
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (int i = 0; i < lisetMap.size(); i++) {
            Map<String, Object> map = lisetMap.get(i);
            Map<String, Object> resultMap = new HashMap<>();
            try {
                // 将 JSON 字符串转为 JSONObject
                // 遍历所有属性
                Set<Map.Entry<String, Object>> entries = map.entrySet();
                for (Map.Entry<String, Object> entry : entries) {
                    String key = entry.getKey();
                    UserDesRuleDO userDesRuleDO = ruleDOMap.get(key);
                    if (null != userDesRuleDO) {
                        if (1 == userDesRuleDO.getRule()) {
                            String value = entry.getValue().toString();
                            String v = DataDesensitizationUtils.invalidatePhone(value, Integer.parseInt(userDesRuleDO.getValueOne()), Integer.parseInt(userDesRuleDO.getValueTwo()));
                            resultMap.put(key, v);
                        } else if (2 == userDesRuleDO.getRule()) {
                            String value = entry.getValue().toString();
                            String v = DataDesensitizationUtils.randomPhone(value);
                            resultMap.put(key, v);
                        } else if (3 == userDesRuleDO.getRule()) {
                            String value = entry.getValue().toString();
                            String v = DataDesensitizationUtils.replaceRange(value, userDesRuleDO.getValueOne(), Integer.parseInt(userDesRuleDO.getValueTwo()), Integer.parseInt(userDesRuleDO.getValueThree()));
                            resultMap.put(key, v);
                        } else if (4 == userDesRuleDO.getRule()) {
                            String value = entry.getValue().toString();
                            String v = DataDesensitizationUtils.encryptAES(value, aesKeyConfig.getKey());
                            resultMap.put(key, v);
                        } else if (5 == userDesRuleDO.getRule()) {
                            String value = entry.getValue().toString();
                            String v = DataDesensitizationUtils.shiftString(value, Integer.parseInt(userDesRuleDO.getValueOne()));
                            resultMap.put(key, v);
                        } else {
                            resultMap.put(key, entry.getValue());
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            resultList.add(resultMap);
        }
        return resultList;
    }

}