package cn.gintone.service;

import cn.gintone.ErrorInfo;
import cn.gintone.config.AesKeyConfig;
import cn.gintone.controller.vo.DesCorporationPageReqVO;
import cn.gintone.controller.vo.DesCorporationSaveReqVO;
import cn.gintone.dal.DesCorporationMapper;
import cn.gintone.encryptionUtils.DataDesensitizationUtils;
import cn.gintone.entity.DesCorporationDO;
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 DesCorporationServiceImpl implements DesCorporationService {

    @Resource
    private DesCorporationMapper desCorporationMapper;
    @Resource
    private AesKeyConfig aesKeyConfig;

    @Override
    public Long createDesCorporation(DesCorporationSaveReqVO createReqVO) {
        // 插入
        DesCorporationDO desCorporation = BeanUtils.toBean(createReqVO, DesCorporationDO.class);
        desCorporationMapper.insert(desCorporation);
        // 返回
        return desCorporation.getId();
    }

    @Override
    public void updateDesCorporation(DesCorporationSaveReqVO updateReqVO) {
        // 校验存在
        validateDesCorporationExists(updateReqVO.getId());
        // 更新
        DesCorporationDO updateObj = BeanUtils.toBean(updateReqVO, DesCorporationDO.class);
        desCorporationMapper.updateById(updateObj);
    }

    @Override
    public void deleteDesCorporation(Long id) {
        // 校验存在
        validateDesCorporationExists(id);
        // 删除
        desCorporationMapper.deleteById(id);
    }

    private void validateDesCorporationExists(Long id) {
        if (desCorporationMapper.selectById(id) == null) {
            throw exception(ErrorInfo.DES_CORPORATION_NOT_EXISTS);
        }
    }

    @Override
    public DesCorporationDO getDesCorporation(Long id) {
        return desCorporationMapper.selectById(id);
    }

    @Override
    public PageResult<DesCorporationDO> getDesCorporationPage(DesCorporationPageReqVO pageReqVO) {
        return desCorporationMapper.selectPage(pageReqVO);
    }

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

        return false;
    }

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

    @Override
    public String corporationRuleDesArr(String jsonArrStr) {
        List<DesCorporationDO> desCorporationDOS = desCorporationMapper.selectList();
        Map<String, DesCorporationDO> ruleDOMap = new HashMap<>();
        for (DesCorporationDO desCorporationDO : desCorporationDOS) {
            ruleDOMap.put(desCorporationDO.getName(), desCorporationDO);
        }
        JSONArray resultJsonArr = new JSONArray();
        JSONArray jsonArray = new JSONArray(jsonArrStr);
        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) {
                    DesCorporationDO desCorporationDO = ruleDOMap.get(key);
                    if (null != desCorporationDO) {
                        if (1 == desCorporationDO.getRule()) {
                            String value = jsonObject.getStr(key);
                            String v = DataDesensitizationUtils.invalidatePhone(value, Integer.parseInt(desCorporationDO.getValueOne()), Integer.parseInt(desCorporationDO.getValueTwo()));
                            resultJson.put(key, v);
                        } else if (2 == desCorporationDO.getRule()) {
                            String value = jsonObject.getStr(key);
                            String v = DataDesensitizationUtils.randomPhone(value);
                            resultJson.put(key, v);
                        } else if (3 == desCorporationDO.getRule()) {
                            String value = jsonObject.getStr(key);
                            String v = DataDesensitizationUtils.replaceRange(value, desCorporationDO.getValueOne(), Integer.parseInt(desCorporationDO.getValueTwo()), Integer.parseInt(desCorporationDO.getValueThree()));
                            resultJson.put(key, v);
                        } else if (4 == desCorporationDO.getRule()) {
                            String value = jsonObject.getStr(key);
                            String v = DataDesensitizationUtils.encryptAES(value, aesKeyConfig.getKey());
                            resultJson.put(key, v);
                        } else if (5 == desCorporationDO.getRule()) {
                            String value = jsonObject.getStr(key);
                            String v = DataDesensitizationUtils.shiftString(value, Integer.parseInt(desCorporationDO.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 Map<String, Object> corporationRuleDesMap(Map<String, Object> map) {
        List<DesCorporationDO> desCorporationDOS = desCorporationMapper.selectList();
        Map<String, DesCorporationDO> ruleDOMap = new HashMap<>();
        for (DesCorporationDO desCorporationDO : desCorporationDOS) {
            ruleDOMap.put(desCorporationDO.getName(), desCorporationDO);
        }
        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();
                DesCorporationDO desCorporationDO = ruleDOMap.get(key);
                if (null != desCorporationDO) {
                    if (1 == desCorporationDO.getRule()) {
                        String value = entry.getValue().toString();
                        String v = DataDesensitizationUtils.invalidatePhone(value, Integer.parseInt(desCorporationDO.getValueOne()), Integer.parseInt(desCorporationDO.getValueTwo()));
                        resultMap.put(key, v);
                    } else if (2 == desCorporationDO.getRule()) {
                        String value = entry.getValue().toString();
                        String v = DataDesensitizationUtils.randomPhone(value);
                        resultMap.put(key, v);
                    } else if (3 == desCorporationDO.getRule()) {
                        String value = entry.getValue().toString();
                        String v = DataDesensitizationUtils.replaceRange(value, desCorporationDO.getValueOne(), Integer.parseInt(desCorporationDO.getValueTwo()), Integer.parseInt(desCorporationDO.getValueThree()));
                        resultMap.put(key, v);
                    } else if (4 == desCorporationDO.getRule()) {
                        String value = entry.getValue().toString();
                        String v = DataDesensitizationUtils.encryptAES(value, aesKeyConfig.getKey());
                        resultMap.put(key, v);
                    } else if (5 == desCorporationDO.getRule()) {
                        String value = entry.getValue().toString();
                        String v = DataDesensitizationUtils.shiftString(value, Integer.parseInt(desCorporationDO.getValueOne()));
                        resultMap.put(key, v);
                    } else {
                        resultMap.put(key, entry.getValue());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultMap;
    }

    @Override
    public List<Map<String, Object>> corporationRuleDesListMap(List<Map<String, Object>> lisetMap) {
        List<DesCorporationDO> desCorporationDOS = desCorporationMapper.selectList();
        Map<String, DesCorporationDO> ruleDOMap = new HashMap<>();
        for (DesCorporationDO desCorporationDO : desCorporationDOS) {
            ruleDOMap.put(desCorporationDO.getName(), desCorporationDO);
        }
        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();
                    DesCorporationDO desCorporationDO = ruleDOMap.get(key);
                    if (null != desCorporationDO) {
                        if (1 == desCorporationDO.getRule()) {
                            String value = entry.getValue().toString();
                            String v = DataDesensitizationUtils.invalidatePhone(value, Integer.parseInt(desCorporationDO.getValueOne()), Integer.parseInt(desCorporationDO.getValueTwo()));
                            resultMap.put(key, v);
                        } else if (2 == desCorporationDO.getRule()) {
                            String value = entry.getValue().toString();
                            String v = DataDesensitizationUtils.randomPhone(value);
                            resultMap.put(key, v);
                        } else if (3 == desCorporationDO.getRule()) {
                            String value = entry.getValue().toString();
                            String v = DataDesensitizationUtils.replaceRange(value, desCorporationDO.getValueOne(), Integer.parseInt(desCorporationDO.getValueTwo()), Integer.parseInt(desCorporationDO.getValueThree()));
                            resultMap.put(key, v);
                        } else if (4 == desCorporationDO.getRule()) {
                            String value = entry.getValue().toString();
                            String v = DataDesensitizationUtils.encryptAES(value, aesKeyConfig.getKey());
                            resultMap.put(key, v);
                        } else if (5 == desCorporationDO.getRule()) {
                            String value = entry.getValue().toString();
                            String v = DataDesensitizationUtils.shiftString(value, Integer.parseInt(desCorporationDO.getValueOne()));
                            resultMap.put(key, v);
                        } else {
                            resultMap.put(key, entry.getValue());
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            resultList.add(resultMap);
        }
        return resultList;
    }

}