<script setup lang="ts" name="AddRules">
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 { getDictinaryTypes } from "@/api/ruleConfig/discover";
import { addRule, testRegex } from "@/api/ruleConfig/discover";
import {
  discoverTypeList,
  singleDiscoverRuleType,
  matchingList,
} from "@/api/ruleConfig/dict/discover";

const props = defineProps<{
  itemData?: Object;
  type: string;
}>();

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

const subRuleidList = ref([]);
const data = reactive({
  form: <any>{
    dataarea_id: "",
    id: "",
    name: "",
    type: "",
    flag: "",
    discoverway: "01",
    regex: "",
    icon: "",
    ruleexample: "",
    ruleargument: "",
    rulegroupname: "",
    dictionaryClass: "",
    matchingway: "",
    defaulttype: "0",
    remark: "",
    testString: "",
  },
  rules: {
    name: [
      {
        required: true,
        message: "请输入发现规则名称",
        trigger: ["blur"],
      },
    ],
    flag: [
      {
        required: true,
        message: "请选择发现方式",
        trigger: ["change"],
      },
    ],
    dictionaryClass: [
      {
        required: true,
        message: "请选择字典分类",
        trigger: ["change"],
      },
    ],
    matchingway: [
      {
        required: true,
        message: "请输入数据域名称",
        trigger: ["change"],
      },
    ],
    ruleexample: [
      {
        required: true,
        message: "请输入样例",
        trigger: ["blur"],
      },
    ],
  },
});

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

const readOnly = ref(true);
const dictinaryTypeList = ref([]); // 字典分类列表
const formRef = ref<FormInstance>();
const modalData = reactive({
  show: false,
  text: "",
  icon: "",
  type: "",
});

// 重置
const reset = () => {
  form.value = {
    dataarea_id: "",
    id: "",
    name: "",
    type: "",
    flag: "",
    discoverway: "01",
    regex: "",
    icon: "",
    ruleexample: "",
    ruleargument: "",
    rulegroupname: "",
    dictionaryClass: "",
    matchingway: "",
    defaulttype: "0",
    remark: "",
    testString: "",
  };
};

// 取消
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) {
      addDataFun();
    } else {
    }
  });
};

// 添加规则
const addDataFun = () => {
  const searchRegex = {
    searchRegex: form.value,
    subRuleidList: subRuleidList.value,
  };
  if (props.type === "edit") {
    searchRegex.searchRegex = {
      ...searchRegex.searchRegex,
      ...{ id: form.value.ruleid },
    };
  }
  addRule(searchRegex).then((res) => {
    const { flag } = res;
    if (flag) {
      ElMessage.success(props.type === "add" ? "新增成功" : "修改成功");
      if (props.type === "edit") {
        readOnly.value = true;
      } else if (props.type === "add") {
        reset();
      }
      emit("confirm");
    }
  });
};

// 字典分类
const getDictionaryTypesFunc = () => {
  getDictinaryTypes({}).then((res) => {
    const { data } = res;
    dictinaryTypeList.value = data;
  });
};

// 规则测试
const testRegexFun = () => {
  const { dictionaryClass, discoverway, matchingway, regex, testString } =
    form.value;
  const data = {
    dictionaryClass: dictionaryClass,
    discoverway: discoverway,
    matchingway: matchingway,
    regex: regex,
    subRuleidList: subRuleidList.value,
    testString: testString,
  };
  formRef.value?.validate((valid) => {
    if (valid) {
      testRegex(data).then((res) => {
        const { flag, msg } = res;
        if (flag) {
          modalData.icon = "success";
          modalData.text = "恭喜您，测试通过！";
          modalData.show = true;
        } else {
          modalData.icon = "error";
          modalData.text = msg;
          modalData.show = true;
        }
      });
    } else {
    }
  });
};

// 成功回调
const modalConfirm = () => {
  modalData.type = "";
  modalData.show = false;
};

// 关闭回调
const modalCancel = () => {
  modalData.type = "";
  modalData.show = false;
};

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

watch(
  () => props.itemData,
  (newVal) => {
    if (props.itemData) {
      const data = JSON.parse(JSON.stringify(props.itemData));
      form.value = { ...form.value, ...data };
    }
  },
  { deep: true, immediate: true }
);

onMounted(() => {
  getDictionaryTypesFunc();
});
</script>

<template>
  <div>
    <el-form ref="formRef" :model="form" :rules="rules" label-width="110px" :disabled="readOnly">
      <el-form-item label="发现规则名" prop="name" required>
        <el-input v-model="form.name" :placeholder="!readOnly ? '请输入发现规则名' : ''"></el-input>
      </el-form-item>
      <el-form-item label="数据域">
        <div>{{ form.type }}</div>
      </el-form-item>
      <el-form-item label="发现方式" prop="flag" required>
        <div style="width: 100%;background: #F3F5FA;">
          <el-select v-model="form.flag">
            <el-option v-for="item in discoverTypeList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </div>
      </el-form-item>
      <el-form-item label="发现规则类型">
        <el-radio-group v-model="form.discoverway" v-if="!readOnly">
          <el-radio :label="item.value"
            v-for="(item,index) in form.flag !== '1' ? singleDiscoverRuleType : singleDiscoverRuleType.slice(0,1)"
            :key="index">{{ item.label }}</el-radio>
        </el-radio-group>
        <el-radio-group v-model="form.discoverway" v-if="readOnly">
          <el-radio :label="item.value"
            v-for="(item,index) in singleDiscoverRuleType.filter(f => f.value=== form.discoverway)"
            :key="index">{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="正则表达式" prop="regex" required
        :rules="[{ required: true, message: '请输入正则表达式', trigger:'blur' }]" v-if="form.discoverway === '01'">
        <el-input v-model="form.regex" :placeholder="!readOnly ? '请输入正则表达式' : ''"></el-input>
      </el-form-item>
      <el-form-item label="JAVA方法" prop="regex" required
        :rules="[{ required: true, message: '请输入JAVA方法', trigger:'blur' }]" v-if="form.discoverway === '04'">
        <el-input v-model="form.regex" :placeholder="!readOnly ? '请输入JAVA方法' : ''"></el-input>
      </el-form-item>
      <el-form-item label="字典分类" prop="dictionaryClass" required v-if="form.discoverway === '03'">
        <div style="width: 100%;background: #F3F5FA;">
          <el-select v-model="form.dictionaryClass">
            <el-option v-for="item in dictinaryTypeList" :key="item.value" :label="item.text" :value="item.value">
            </el-option>
          </el-select>
        </div>
      </el-form-item>
      <el-form-item label="匹配方式" prop="matchingway" required v-if="form.discoverway === '03'">
        <div style="width: 100%;background: #F3F5FA;">
          <el-select v-model="form.matchingway">
            <el-option v-for="item in matchingList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </div>
      </el-form-item>
      <el-form-item label="样例" prop="ruleexample" required>
        <el-input v-model="form.ruleexample" :placeholder="!readOnly ? '请输入样例' : ''"></el-input>
      </el-form-item>
      <el-form-item label="测试">
        <div style="width: 100%;display: flex;align-items: center;">
          <el-input v-model="form.testString" style="flex: 1;" :placeholder="!readOnly ? '请输入测试' : ''"></el-input>
          <el-button type="primary" @click="testRegexFun">测试</el-button>
        </div>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="form.remark" :placeholder="!readOnly ? '请输入备注' : ''"></el-input>
      </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>

    <Modal v-model="modalData.show" :icon="modalData.icon" :cancel="false" :text="modalData.text"
      @confirm="modalConfirm" @cancel="modalCancel" />
  </div>
</template>

<style lang="scss" scoped>
.el-form-item {
  margin-bottom: 8px;
}
.btn {
  padding: 20px;
  display: flex;
  justify-content: center;
}
:deep(.el-form-item__error) {
  left: auto;
  right: 30px;
  top: 24%;
}
</style>