<script setup lang="ts" name="AddRules">
import { onMounted, reactive, ref, toRefs, watch, computed } from "vue";
import type { FormInstance } from "element-plus";
import { ElMessage } from "element-plus";
import { getRandomValue, testEncryption, saveSecretKey } from '@/api/ruleConfig/encryption'

const props = defineProps<{
  itemData: Object;
  type: string;
  encryptionTypeDict: Array<any>;
  keyNameDict: any;
}>();

const emit = defineEmits(['cancel','confirm']);

const data = reactive({
  form: <any>{
    
  },
  rules: {
    sectet_key_value: [
      {
        required: true,
        message: "密钥值不能为空",
        trigger: ["change"],
      },
    ],
  },
});

const { form, rules } = toRefs(data);

const readOnly = ref(true);
const testParam = ref(""); // 测试参数
const encryptedValue = ref(""); // 加密后的值
const formRef = ref<FormInstance>();
const keyNameList = ref([])

// 取消
const cancel = () => {
  if (props.type === "edit") {
    readOnly.value = true;
    const data = JSON.parse(JSON.stringify(props.itemData));
    form.value = { ...form.value, ...data };
  } else if (props.type === "add") {
    emit("cancel");
  }
};

const confirm = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      saveSecretKeyFun()
    } else {
    }
  });
};

// 添加密钥
const saveSecretKeyFun = () => {
  const { encryption_id, secret_key_name, sectet_key_value, id } = form.value;
  let data = {
    encryption_id: encryption_id,
    secret_key_name: secret_key_name,
    sectet_key_value: sectet_key_value,
  }
  if (props.type === 'edit') { 
    data = {...data,...{id: id}}
  }
  saveSecretKey(data).then(res => {
    const { flag } = res
    if (flag) {
      ElMessage.success((props.type === "add" || !form.value.id) ? "新增成功" : "修改成功");
      if (props.type === 'edit') {
        readOnly.value = true
      } else if (props.type === 'add') { 
        form.value = {}
      }
      testParam.value = ""
      encryptedValue.value = ""
      emit('confirm', props.type)
    }
  })
}

// 密钥生成
const getKeyGeneration = () => {
  const { encryption_type } = form.value;
  getRandomValue({ type: encryption_type}).then((res) => {
    const { flag, data } = res;
    if (flag){
      form.value.sectet_key_value = data;
    }
  });
};

// 测试
const getKeyText = () => {
  const { encryption_type } = form.value;
  if (!encryption_type) {
    return ElMessage.error("密钥值不能为空！");
  }
  const data = {
    param: testParam.value,
    type: encryption_type,
    secret_key: form.value.sectet_key_value,
  }
  testEncryption(data).then((res) => {
    const { flag, data } = res;
    if (flag){
      encryptedValue.value = data;
    }
  });
}

// 分类称验证
const validateRulename = (rule, value, callback) => {
  const state = keyNameList.value.includes(value);
  if (state) {
    callback(new Error('加密名称已存在'));
  } else {
    callback();
  }
};

watch(
  () => props.type,
  (newVal) => {
    readOnly.value = props.type === "edit" ? true : false;
  },
  { deep: true, immediate: true }
);

watch(
  () => props.itemData,
  (newVal) => {
    if (props.type === "add") {
      form.value = {}
    }
    if (props.itemData) {
      const data = JSON.parse(JSON.stringify(props.itemData));
      form.value = { ...form.value, ...data };
      if (props.type === 'edit' && data) {
        keyNameList.value = keyNameList.value.filter(item => item !== data.secret_key_name)
      }
    }
  },
  { deep: true, immediate: true }
);

watch(
  () => props.keyNameDict,
  (newVal) => {
    keyNameList.value = props.keyNameDict
    const data = JSON.parse(JSON.stringify(props.itemData));
    if (props.type === 'edit' && data) {
      keyNameList.value = keyNameList.value.filter(item => item !== data.secret_key_name)
    }
  },
  { deep: true, immediate: true }
);
</script>

<template>
  <div>
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" :disabled="readOnly">
      <el-form-item label="密钥名称" prop="secret_key_name" required :rules="[{ required: true, message: '请输入加密名称', trigger:'blur' },{ required: true, validator: validateRulename, trigger:'blur' }]">
        <el-input v-model="form.secret_key_name"></el-input>
      </el-form-item>
      <el-form-item label="加密算法">
        <el-input v-model="form.encryption_name" disabled></el-input>
      </el-form-item>
      <el-form-item label="密钥值" prop="sectet_key_value" required>
        <div style="width: 100%;display: flex;align-items: center;">
          <el-input v-model="form.sectet_key_value" disabled style="flex: 1;"></el-input>
          <el-button type="primary" style="margin-left: 8px;" @click="getKeyGeneration" v-if="(!form.sectet_key_value) && !readOnly">密钥生成</el-button>
        </div>
      </el-form-item>
      <el-form-item label="测试">
        <div style="width: 100%;display: flex;align-items: center;">
          <el-input v-model="testParam" style="flex: 1;"></el-input>
          <el-button type="primary" style="margin-left: 8px;" @click="getKeyText" v-if="!readOnly">测试</el-button>
        </div>
      </el-form-item>
      <el-form-item label="加密后的值">
        <el-input v-model="encryptedValue" disabled></el-input>
      </el-form-item>
    </el-form>
    <div class="btn">
      <el-button type="primary" style="width: 150px;" @click="readOnly = false" v-if="readOnly">编辑</el-button>
      <el-button type="info" style="width: 150px;" @click="cancel" v-if="!readOnly">取消</el-button>
      <el-button type="primary" style="width: 150px;" @click="confirm" v-if="!readOnly">确认</el-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.el-form-item {
  margin-bottom: 15px;
}
.btn {
  padding: 20px;
  display: flex;
  justify-content: center;
}
</style>