<script setup lang="ts" name="Form">
import { onMounted, reactive, ref, toRefs, watch } from "vue";
import { Switch } from "view-ui-plus";
import type { FormInstance } from "element-plus";
import { ElMessage } from "element-plus";
import { querysec, save } from "@/api/ruleConfig/calculationMethod";

const props = defineProps<{
  itemData: boolean;
  type: string;
  encryptionDict: Array<any>;
}>();

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

const data = reactive({
  form: <any>{
    dataarea_id: "",
    defaulttype: "0",
    enc_name: "",
    encryption_id: "",
    secretkey_id: "",
  },
  rules: {
    enc_name: [
      {
        required: true,
        message: "请输入数据域名称",
        trigger: ["blur"],
      },
    ],
    encryption_id: [
      {
        required: true,
        message: "请选择加密规则",
        trigger: ["change"],
      },
    ],
    secretkey_id: [
      {
        required: true,
        message: "请选择密钥",
        trigger: ["change"],
      },
    ],
  },
});

const { form, rules } = toRefs(data);
const encryptionList = ref<any[]>([]); // 加密规则选项列表
const secretkeyList = ref<any[]>([]); // 密钥选项列表
const readOnly = ref(true);
const formRef = ref<FormInstance>();

// 重置
const reset = () => { 
  form.value = {
    dataarea_id: "",
    defaulttype: "0",
    enc_name: "",
    encryption_id: "",
    secretkey_id: "",
  };
}

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

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

const saveFunc = () => {
  console.log(form.value)
  if (props.type === "edit") {
    form.value = { ...form.value, ...{ id: form.value.id } }
  }
  save(form.value).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") {
        reset()
      }
      emit("confirm");
    }
  });
}

// 查询密钥
const getQuerysec = () => {
  querysec({ encryption_id: form.value.encryption_id }).then((res) => {
    const { data } = res;
    secretkeyList.value = data.map((item) => {
      const { id, secret_key_name } = item;
      return {
        value: id,
        label: secret_key_name,
      };
    });
  });
};

// 加密规则变化
const encryptionChange = () => {
  form.value.secretkey_id = ''
  getQuerysec()
}

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

watch(
  () => props.itemData,
  (newVal) => {
    if (props.itemData) {
      if (!props.itemData.enc_name) {
        reset()
      }
      const data = JSON.parse(JSON.stringify(props.itemData));
      form.value = { ...form.value, ...data };
      if (props.type === "edit" && form.value.secretkey_id) {
        getQuerysec()
      }
    }
  },
  { deep: true, immediate: true }
);

watch(
  () => props.encryptionDict,
  (newVal) => {
    encryptionList.value = props.encryptionDict;
  },
  { 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="enc_name" required>
        <el-input v-model="form.enc_name" placeholder="请输入算法名称"></el-input>
      </el-form-item>
      <el-form-item label="加密规则" prop="encryption_id" required>
        <div style="width: 100%;background: #F3F5FA;">
          <el-select v-model="form.encryption_id" @change="encryptionChange">
            <el-option v-for="item in encryptionList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </div>
      </el-form-item>
      <el-form-item label="密钥" prop="secretkey_id" required>
        <div style="width: 100%;background: #F3F5FA;">
          <el-select v-model="form.secretkey_id">
            <el-option v-for="item in secretkeyList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </div>
      </el-form-item>
      <el-form-item label="默认规则">
        <Switch true-value="1" false-value="0" v-model="form.defaulttype" :disabled="readOnly">
          <template #open>
            <span>是</span>
          </template>
          <template #close>
            <span>否</span>
          </template>
        </Switch>
      </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>
.openEditor {
  position: absolute;
  bottom: 0;
  right: 0;
}
.btn {
  padding: 20px;
  display: flex;
  justify-content: center;
}
</style>