<script setup lang="ts" name="AddRules">
import { onMounted, reactive, ref, toRefs, watch } from "vue";
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, ruleexample } =
    form.value;
  const data = {
    dictionaryClass: dictionaryClass,
    discoverway: discoverway,
    matchingway: matchingway,
    regex: regex,
    subRuleidList: subRuleidList.value,
    testString: ruleexample,
  };
  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.type === "add") {
      reset();
    }
    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" :label-position="props.type === 'add'?'left':''">
      <div class="formBox">
        <el-form-item label="数据域" v-if="props.type === 'add'">
          <div style="color: rgba(33, 103, 217, 1);" v-if="!readOnly">{{ form.type }}</div>
        </el-form-item>
        <el-form-item label="发现规则名" prop="name" required>
          <el-input v-model="form.name" :placeholder="!readOnly ? '请输入发现规则名' : ''"></el-input>
        </el-form-item>
        <el-form-item label="数据域" v-if="props.type === 'edit'">
          <div style="margin-left: 10px;" v-if="!readOnly">{{ form.type }}</div>
          <div class="is-disabled" v-if="readOnly" style="width: 100%;height: 100%;">
            <div class="el-input__wrapper" style="height: 100%;color: rgb(53, 64, 79);">{{ form.type }}</div>
          </div>
        </el-form-item>
        <el-form-item label="发现方式" prop="flag" required>
          <div style="width: 100%;background: #F3F5FA;" v-if="!readOnly">
            <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>
          <div class="is-disabled" v-if="readOnly" style="width: 100%;height: 100%;">
            <div class="el-input__wrapper" v-for="(item,index) in discoverTypeList.filter(f => f.value === form.flag)"
              :key="index" style="height: 100%;color: rgb(53, 64, 79);">{{ item.label }}</div>
          </div>
        </el-form-item>
        <el-form-item label="发现规则类型">
          <el-radio-group style="margin-left: 10px;" 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>
          <div class="is-disabled" v-if="readOnly" style="width: 100%;height: 100%;">
            <div class="el-input__wrapper"
              v-for="(item,index) in singleDiscoverRuleType.filter(f => f.value === form.discoverway)" :key="index"
              style="height: 100%;color: rgb(53, 64, 79);">{{ item.label }}</div>
          </div>
        </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" v-if="!readOnly" @click="testRegexFun">测试</el-button>
          </div>
        </el-form-item>
        <el-form-item label="默认规则">
          <div class="is-disabled" v-if="readOnly" style="width: 100%;height: 100%;">
            <div class="el-input__wrapper" style="height: 100%;color: rgb(53, 64, 79);">
              {{ form.defaulttype === '1' ? '是':'否' }}</div>
          </div>
          <el-radio-group v-model="form.defaulttype" v-if="!readOnly" style="margin-left: 10px;">
            <el-radio label="0">否</el-radio>
            <el-radio label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" :placeholder="!readOnly ? '请输入备注' : ''"></el-input>
        </el-form-item>
      </div>
    </el-form>
    <div class="btn">
      <el-button type="primary" style="width: 80px;" @click="readOnly = false" v-if="readOnly">编辑</el-button>
      <el-button type="primary" style="width: 80px;" @click="confirm" v-if="!readOnly">确认</el-button>
      <el-button style="width: 80px;" @click="cancel" 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: 20px;
}
.btn {
  padding: 20px;
  display: flex;
  justify-content: center;
}
:deep(.el-form-item__error) {
  left: auto;
  right: 30px;
  top: 24%;
}
</style>