<template>
  <div class="custom-form">
    <el-form :model="state.form" ref="form_ref" :rules="state.rules" label-width="110px">
      <div class="custom-form-item">
        <el-form-item label="预警对象" prop="warn_target">
          <el-input
            v-model="state.form.warn_target"
            placeholder="请输入"
            :disabled="isEdit"
            :maxlength="20"
            show-word-limit
            clearable
            @change="changeWarnCustomTarget"></el-input>
        </el-form-item>
        <el-form-item label="预警分类" prop="warn_type">
          <el-input
            v-model="state.form.warn_type"
            placeholder="请输入"
            :disabled="isEdit"
            clearable
            :maxlength="20"
            show-word-limit
            @change="changeWarnCustomType"></el-input>
        </el-form-item>
        <el-form-item label="预警指标" prop="warn_indicator">
          <el-input
            v-model="state.form.warn_indicator"
            placeholder="请输入"
            :disabled="isEdit"
            :maxlength="30"
            show-word-limit
            clearable
            @change="changeWarnCustomType"></el-input>
        </el-form-item>
      </div>
      <gap-title :hasLine="true" title="指标表达式"> </gap-title>
      <div class="custom-form-item">
        <el-form-item label="" prop="indicator_expression">
          <div class="indicator-expression">
            <bg-code-editor v-model="state.form.indicator_expression"></bg-code-editor>
          </div>
        </el-form-item>
      </div>
      <gap-title :hasLine="true" title="预警规则"></gap-title>
      <div class="add-form-item">
        <el-form-item label="预警规则类型" prop="rule_type">
          <el-select
            style="flex: 1"
            v-model="state.form.rule_type"
            placeholder="请选择"
            filterable
            @change="changeRuleType">
            <el-option v-for="(value, key) in ruleTypeOptions" :key="key" :label="value.label" :value="key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="" v-if="state.form.ruleRows.length > 0 && state.form.rule_type != 'empty'">
          <div class="rule-table" style="width: 100%">
            <el-form
              :model="state.form.ruleRows"
              ref="table_form"
              :rules="state.tableRules"
              label-width="0"
              style="width: 100%">
              <el-table :data="state.form.ruleRows" stripe border>
                <el-table-column
                  v-for="header in ruleHeaders"
                  :prop="header.prop"
                  :key="header.prop"
                  :label="header.label"
                  :width="header.width">
                  <template #default="{ $index }">
                    <div class="warning-threshold" v-if="header.prop == 'warning_threshold'">
                      <el-form-item :prop="`[${$index}].from`" :rules="state.tableRules.from" style="flex: 1">
                        <el-input
                          style="flex: 1"
                          v-model="state.form.ruleRows[$index].from"
                          placeholder="请输入"
                          @input="changeWarningThresholdFrom($index)">
                          <template #append>{{ unitMap }}</template>
                        </el-input>
                      </el-form-item>
                      <span class="to">-</span>
                      <el-form-item label="" :prop="`${$index}.to`" :rules="state.tableRules.to" style="flex: 1">
                        <el-input
                          style="flex: 1"
                          v-model="state.form.ruleRows[$index].to"
                          placeholder="请输入"
                          clearable
                          @input="changeWarningThresholdTo($index)">
                          <template #append>{{ unitMap }}</template>
                        </el-input>
                      </el-form-item>
                    </div>
                    <div v-else-if="header.prop == 'risk_level'">
                      <el-form-item label="" :prop="`[${$index}].risk_level`" :rules="state.tableRules.risk_level">
                        <el-select
                          style="flex: 1"
                          v-model="state.form.ruleRows[$index].risk_level"
                          placeholder="请选择">
                          <el-option
                            v-for="item in riskLevelOptions($index)"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="" label="操作" width="150px">
                  <template #default="{ $index }">
                    <div class="table-operation">
                      <el-button
                        link
                        type="primary"
                        @click="createRule($index)"
                        :disabled="state.form.ruleRows.length >= riskLevels.length">
                        新增
                      </el-button>
                      <span class="line"></span>
                      <el-button
                        link
                        type="primary"
                        @click="removeRule($index)"
                        :disabled="state.form.ruleRows.length == 1">
                        删除
                      </el-button>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
          </div>
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { computed, reactive, ref, watch } from "vue";
import gapTitle from "@/components/gap-title.vue";
import { ElMessage } from "element-plus";
const props = defineProps({
  form: {
    type: Object,
    default: null,
  },
  isEdit: {
    type: Boolean,
    default: false,
  },
});
var validateWarnIndex = (rule, value, callback) => {
  if (value === "") {
    if (state.form.type_key == "static") {
      callback(new Error("请选择"));
    } else {
      callback(new Error("请输入"));
    }
  } else {
    callback();
  }
};

const state = reactive({
  form: {
    warn_target: "",
    warn_type: "",
    warn_indicator: "",
    indicator_expression: "",
    rule_type: "empty",
    ruleRows: [],
  },
  rules: {
    warn_target: [{ required: true, message: "请输入", trigger: "blur" }],
    warn_type: [{ required: true, message: "请输入", trigger: "blur" }],
    warn_indicator: [{ validator: validateWarnIndex, trigger: "blur" }],
    indicator_expression: [{ required: true, message: "请输入", trigger: "blur" }],
    rule_type: [{ required: true, message: "请选择", trigger: "change" }],
  },
  tableRules: {
    from: [{ required: true, message: "请输入", trigger: "blur" }],
    to: [{ required: true, message: "请输入", trigger: "blur" }],
    risk_level: [{ required: true, message: "请选择", trigger: "change" }],
  },
});
const changeWarnCustomTarget = () => {};
const changeWarnCustomType = () => {};
const setLimits = (index) => {
  let rows = [...state.form.ruleRows];
  rows.splice(index, 1);
  return (
    rows.map((e) => {
      return {
        down: +e.from,
        up: +e.to,
      };
    }) || []
  );
};
const changeWarningThresholdFrom = (index) => {
  let { down, up } = limit.value;
  if (down === "") return;
  let { from, to } = state.form.ruleRows[index];
  if (+from > +up || (index == 0 && +from < +down) || +from > +to) {
    state.form.ruleRows[index].from = "";
    return;
  }
  let rows = setLimits(index);
  if (rows.length == 0) return;
  try {
    rows.forEach((e) => {
      if (+e.up >= +from > +e.down) {
        throw "";
      }
    });
  } catch (e) {
    state.form.ruleRows[index].from = "";
  }
};
const changeWarningThresholdTo = (index) => {
  let { down, up } = limit.value;
  if (up === "") return;
  let { from, to } = state.form.ruleRows[index];
  if ((index == 0 && +to > +up) || +to < +down || +from > +to) {
    state.form.ruleRows[index].to = "";
    return;
  }
  let rows = setLimits(index);
  if (rows.length == 0) return;
  try {
    rows.forEach((e) => {
      if (+e.up > +to > +e.down) {
        throw "";
      }
    });
  } catch (e) {
    state.form.ruleRows[index].to = "";
  }
};
const changeRuleType = () => {};
const form_ref = ref(null);
const table_form = ref(null);
const Submit = async () => {
  let form_valid = await new Promise((resolve, reject) => {
    form_ref.value.validate((res) => resolve(res));
  });
  let table_form_valid = await new Promise((resolve, reject) => {
    table_form.value.validate((res) => resolve(res));
  });
  return form_valid && table_form_valid;
};
const riskLevels = ref([
  {
    id: 1,
    name: "重大风险",
  },
  {
    id: 2,
    name: "较大风险",
  },
  {
    id: 3,
    name: "一般风险",
  },
  {
    id: 4,
    name: "低风险",
  },
]);
const riskLevelOptions = computed(() => {
  return (index) => {
    let risk_level = state.form.ruleRows[index].risk_level;
    let rows = state.form.ruleRows.map((e) => e.risk_level);
    if (risk_level) {
      let i = rows.findIndex((e) => e == risk_level);
      rows.splice(i, 1);
    }
    return riskLevels.value.filter((e) => !rows.includes(e.id));
  };
});
const unitMap = computed(() => {
  return ruleTypeOptions[state.form.rule_type].unit || "";
});
const limit = computed(() => {
  return (
    ruleTypeOptions[state.form.rule_type].limit || {
      down: "",
      up: "",
    }
  );
});
const ruleTypeOptions = {
  empty: {
    label: "空",
  },
  1: {
    label: "百分比范围",
    unit: "%",
    limit: {
      down: 0,
      up: 100,
    },
  },
  2: {
    label: "毫秒范围",
    unit: "ms",
    limit: {
      down: 0,
      up: "",
    },
  },
  3: {
    label: "秒范围",
    unit: "s",
    limit: {
      down: 0,
      up: "",
    },
  },
  4: {
    label: "个范围",
    unit: "个",
    limit: {
      down: 0,
      up: "",
    },
  },
  5: {
    label: "温度范围",
    unit: "℃",
    limit: {
      down: "",
      up: "",
    },
  },
};
const ruleHeaders = [
  {
    prop: "warning_threshold",
    label: "预警阈值",
    width: "500px",
  },
  {
    prop: "risk_level",
    label: "风险程度",
  },
];
const createRule = (index = -1) => {
  state.form.ruleRows.splice(index + 1, 0, {
    from: "",
    to: "",
    risk_level: "",
  });
};
const removeRule = (index) => {
  state.form.ruleRows.splice(index, 1);
};
watch(
  () => props.form,
  (f) => {
    if (!f) {
      createRule();
      return;
    }
    state.form.warn_target = f.warn_target;
    state.form.warn_type = f.warn_type;
    state.form.warn_indicator = f.warn_indicator;
    state.form.indicator_expression = f.indicator_expression;
    state.form.rule_type = f.rule_type;
    state.form.ruleRows =
      f.ruleRows.map((e) => {
        return {
          from: e.from,
          to: e.to,
          risk_level: e.risk_level,
        };
      }) || [];
    if (state.form.ruleRows.length == 0) {
      createRule();
    }
  },
  {
    deep: true,
    immediate: true,
  }
);
defineExpose({
  Submit,
  form: state.form,
  form_ref,
});
</script>

<style lang="scss" scoped>
.custom-form {
  :deep(.gap-title) {
    margin-bottom: 16px;
  }
  &-item {
    max-width: 1080px;
    width: 100%;
    padding-left: 8px;
    .indicator-expression {
      height: 300px;
      width: 100%;
      :deep(.vue-ace-editor) {
        margin-top: 0;
      }
    }
  }
}
.warning-threshold {
  display: flex;
  align-items: center;
  :deep(.el-input-group__append, .el-input-group__prepend) {
    border-radius: 4px;
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
  }
}
.to {
  margin: 0 16px;
}
.line {
  width: 1px;
  height: 14px;
  background-color: #c1c7d7;
  margin: 0 16px;
  display: inline-block;
}
.rule-table {
  :deep(.el-table thead th) {
    background-color: #f5f6f9;
  }
}
</style>
