<template>
  <el-dialog v-model="isShow" width="1100px" :before-close="handleClose">
    <!-- :destroy-on-close="true" -->
    <el-form
      ref="ruleFormRef"
      :model="form"
      :rules="rules"
      label-position="top"
      label-width="200px"
    >
      <el-row type="flex" justify="space-between" align="middle" :gutter="10">
        <el-col :span="15">
          <el-form-item prop="name">
            <el-tag>规则名称</el-tag>
            <el-input v-model="form.name" />
          </el-form-item>
        </el-col>
        <el-col
          :span="9"
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <el-form-item prop="category">
            <el-tag>报警类别</el-tag>
            <el-select v-model="form.category" class="select-mini">
              <el-option key="1" label="风机" value="1" />
              <el-option key="2" label="电气" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item prop="rank">
            <el-tag>报警级别</el-tag>
            <el-select v-model="form.rank" class="select-mini">
              <el-option key="1" label="低" value="1" />
              <el-option key="2" label="中低" value="2" />
              <el-option key="3" label="中" value="3" />
              <el-option key="4" label="中高" value="4" />
              <el-option key="5" label="高" value="5" />
            </el-select>
          </el-form-item>
          <el-form-item prop="enabled">
            <el-tag>是否启用</el-tag>
            <el-switch
              v-model="form.enabled"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item prop="station">
            <el-tag>风场</el-tag>
            <el-select
              v-model="form.station"
              style="width: 100%"
              @change="
                () => {
                  form.modelId = '';
                  stationChange();
                }
              "
            >
              <el-option
                v-for="item in stationList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="modelId">
            <el-tag>风机型号</el-tag>
            <el-select
              v-model="form.modelId"
              style="width: 100%"
              @change="modelIdChange"
            >
              <el-option
                v-for="item in state.modelList"
                :key="item"
                :value="item"
                :label="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="relatedParts">
            <el-tag>所属部件</el-tag>
            <el-select v-model="form.relatedParts" style="width: 100%">
              <el-option
                v-for="i in state.relatePartList"
                :key="i.partCode"
                :value="i.partCode"
                :label="i.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="fault">
            <el-tag>预警类型</el-tag>
            <el-select v-model="form.project" style="width: 100%">
              <el-option
                v-for="i in faultList"
                :key="i.value"
                :value="i.value"
                :label="i.name"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item prop="expressionShow">
            <el-tag>表达式</el-tag>
            <el-input
              type="textarea"
              rows="14"
              v-model="form.expressionShow"
              :value="form.expressionShow"
              id="expressionInput"
            />
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-tabs type="border-card">
            <el-tab-pane label="AI测点">
              <el-input v-model="state.AIPointSearch"> </el-input>
              <el-table
                size="mini"
                fit
                :show-header="false"
                :highlight-current-row="true"
                :stripe="false"
                :border="false"
                height="240"
                :data="filterAIList"
                @row-dblclick="rowDbclick"
              >
                <el-table-column prop="uniformCode" />
                <el-table-column prop="name" />
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="DI测点">
              <el-input v-model="state.DIPointSearch"> </el-input>
              <el-table
                size="mini"
                fit
                :show-header="false"
                :highlight-current-row="true"
                :stripe="false"
                :border="false"
                height="240"
                :data="filterDIList"
                @row-dblclick="rowDbclick"
              >
                <el-table-column prop="uniformCode" />
                <el-table-column prop="name" />
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="函数">
              <el-table
                size="mini"
                fit
                :show-header="false"
                :highlight-current-row="true"
                :stripe="false"
                :border="false"
                :height="270"
                :data="func"
                @row-dblclick="tabFuncRowClickHandle"
              >
                <el-table-column min-width="60%">
                  <template #default="scope">
                    <el-popover trigger="hover" placement="bottom">
                      <p>描述：{{ scope.row.describe }}</p>
                      <p>参数：{{ scope.row.param }}</p>
                      <template #reference>
                        <span size="medium" transition="fade-in-linear">{{
                          scope.row.lab
                        }}</span>
                      </template>
                    </el-popover>
                  </template>
                </el-table-column>
                <el-table-column min-width="40%">
                  <template #default="scope">
                    <el-popover trigger="hover" placement="bottom">
                      <p>描述：{{ scope.row.describe }}</p>
                      <p>参数：{{ scope.row.param }}</p>
                      <template #reference>
                        <span size="medium" transition="fade-in-linear">{{
                          scope.row.name
                        }}</span>
                      </template>
                    </el-popover>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="运算符">
              <el-button-group>
                <el-button
                  v-for="item in operator"
                  :key="item"
                  plain
                  type="primary"
                  @click="elInputSplit(item)"
                  style="width: 60px; margin: 7px 12px; height: 40px"
                >
                  {{ item }}
                </el-button>
              </el-button-group>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="24">
          <el-form-item prop="descriptionShow">
            <el-tag>规则描述</el-tag>
            <el-input type="textarea" rows="4" v-model="form.descriptionShow" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)"
          >确 定</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, onMounted, reactive, computed, watch, nextTick } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import {
  fetchAIPointList,
  fetchDIPointList,
  fetchRelatePart,
  custombj_postSave,
  fetch_electrical_point_ai,
  fetch_electrical_point_di,
  getStationinfo,
} from "/@/api/api.js";
import { useStore } from "vuex";
const store = useStore();
const stationList = computed(() => store.state.stationList);

const form = ref({
  id: "",
  name: "",
  descriptionShow: "",
  expressionShow: "",
  tag: "",
  rank: "",
  enabled: "1", // 1可用-0禁用
  modelId: "",
  ednaValue: "",
  category: "",
  range: 0,
  station: "",
  windturbine: "",
  line: "",
  project: "",
  electrical: "",
  taskstart: "",
  relatedParts: "",
  userName: "",
});
onMounted(() => {
  isShow.value = props.isVisible;
  getfetchRelatePart();
});
watch(
  () => props.form,
  (val, old) => {
    nextTick(() => {
      form.value = val;
      // if (val) {
      //     form.value = val;
      // } else {
      //     form.value = form3
      // }
    });
  },
  {
    deep: true,
  }
);
watch(
  () => props.form?.id,
  (val, old) => {
    if (val != "" && val !== undefined) {
      nextTick(async () => {
        debugger;
        getfetchAIPointList();
        getfetchDIPointList();
      });
    }
  },
  {
    deep: true,
  }
);
watch(
  () => props.isVisible,
  (val, old) => {
    nextTick(() => {
      isShow.value = val.value;
      if (val.value) {
        getfetchRelatePart();
        stationChange();
        modelIdChange();
      }
    });
  },
  {
    deep: true,
  }
);
const emits = defineEmits(["close"]);
const props = defineProps({
  isVisible: {
    type: Boolean,
    defaule: false,
  },
  form: {
    type: Object,
  },
});
const toEmits = () => {
  emits("close"); // 向父组件传递数据
};
const isShow = ref(false);
const state = reactive({
  relatePartList: [],
  modelList: [],
  AIPointList: [],
  DIPointList: [],
  AIPointSearch: "",
  DIPointSearch: "",
});
const operator = [
  "+",
  "-",
  "*",
  "/",
  "(",
  ")",
  ">",
  ">=",
  "<",
  "<=",
  "==",
  "!=",
  "&&",
  "||",
  "!",
  "%",
  "true",
  "false",
  ".",
];
const func = [
  {
    lab: "MR",
    name: "移动极差",
    param: "测点名，时间（秒）",
    describe: "是指两个或多个连续样本值中最大值与最小值之差",
    scene: "测点的移动极差超限报警",
  },
  {
    lab: "MAR",
    name: "均值极差",
    param: "测点名，时间（秒）",
    describe: "",
    scene: "测点的均值极差计算",
  },
  {
    lab: "RiseExceed",
    name: "上升趋势",
    param: "测点名，时间（秒），阈值",
    describe: "取测点在给定的时间范围内数据上升的量是否超过阈值",
    scene: "测点值的上升速度过快等",
  },
  {
    lab: "Sustain",
    name: "持续时间",
    param: "表达式，时间（秒）",
    describe:
      "判定状态（表达式成立）持续的时间是否超过给定的时间判断状态持续的时间",
    scene: "",
  },
  {
    lab: "LastUpdateTime",
    name: "最近数据时间",
    param: "测点名",
    describe: "",
    scene: "判定离线，状态持续时间等",
  },
  {
    lab: "abs",
    name: "取绝对值",
    param: "double a",
    describe: "",
    scene: "",
  },
  {
    lab: "acos",
    name: "反余弦",
    param: "double a",
    describe: "",
    scene: "",
  },
  {
    lab: "asin",
    name: "反正弦",
    param: "double a",
    describe: "",
    scene: "",
  },
  {
    lab: "atan",
    name: "反正切",
    param: "double a",
    describe: "",
    scene: "",
  },
  {
    lab: "atan2",
    name: "xy坐标转为极坐标",
    param: "x,y",
    describe: "",
    scene: "",
  },
  {
    lab: "ceiling",
    name: "向上取整",
    param: "double a",
    describe: "",
    scene: "",
  },
  {
    lab: "cos",
    name: "余弦",
    param: "double a",
    describe: "",
    scene: "",
  },
  {
    lab: "cosh",
    name: "双曲线余弦",
    param: "double a",
    describe: "",
    scene: "",
  },
  {
    lab: "exp",
    name: "欧拉数 e 的 double 次幂的值",
    param: "double a",
    describe: "",
    scene: "",
  },
  {
    lab: "floor",
    name: "向下取整",
    param: "double a",
    describe: "",
    scene: "",
  },
  {
    lab: "log",
    name: "自然对数",
    param: "double a",
    describe: "",
    scene: "",
  },
  {
    lab: "log10",
    name: "底数为 10 的对数",
    param: "double a",
    describe: "",
    scene: "",
  },
  {
    lab: "max",
    name: "比较最大值",
    param: "double a, double b",
    describe: "",
    scene: "",
  },
  {
    lab: "min",
    name: "比较最小值",
    param: "double a, double b",
    describe: "",
    scene: "",
  },
  {
    lab: "pow",
    name: "返回第一个参数的第二个参数次幂的值",
    param: "double a, double b",
    describe: "",
    scene: "",
  },
  {
    lab: "round",
    name: "返回最接近参数的 long,或int",
    param: "double a",
    describe: "",
    scene: "",
  },
  {
    lab: "sign",
    name: "负数返回-1.0,整数返回1.0,0返回0.0",
    param: "float f/double a",
    describe: "",
    scene: "",
  },
  {
    lab: "sin",
    name: "三角正弦值",
    param: "double a",
    describe: "",
    scene: "",
  },
  {
    lab: "sinh",
    name: "双曲线正弦",
    param: "double x",
    describe: "",
    scene: "",
  },
  {
    lab: "sqrt",
    name: "正平方根",
    param: "double a",
    describe: "",
    scene: "",
  },
  {
    lab: "tan",
    name: "正切",
    param: "double a",
    describe: "",
    scene: "",
  },
  {
    lab: "tanh",
    name: "双曲线正切",
    param: "double x",
    describe: "",
    scene: "",
  },
  { lab: "PI", name: "圆周率", param: "", describe: "", scene: "" },
  { lab: "E", name: "自然对数", param: "", describe: "", scene: "" },
];
const faultList = [
  {
    value: "sensors",
    name: "传感器异常",
  },
  {
    value: "parts",
    name: "零部件隐患",
  },
  {
    value: "control",
    name: "控制参数优化",
  },
  {
    value: "performance",
    name: "性能下降",
  },
];
const ruleFormRef = ref(null);
const rules = reactive({
  name: [{ required: true, message: "请输入规则名称", trigger: "blur" }],
  category: [{ required: true, message: "请选择报警类别", trigger: "change" }],
  rank: [{ required: true, message: "请选择报警级别", trigger: "change" }],
  station: [{ required: true, message: "请选择风场", trigger: "change" }],
  expressionShow: [
    { required: true, message: "表达式不能为空", trigger: "change" },
  ],
});

//stationChange
const stationChange = async () => {
  getequipmentmodel_list();
};
//modelIdChange
const modelIdChange = async () => {
  getfetchAIPointList();
  getfetchDIPointList();
  getEditAiList(form.value.station, form.value.modelId);
  getEditDiList(form.value.station, form.value.modelId);
};
//机型
const getequipmentmodel_list = async () => {
  const { data } = await getStationinfo(form.value.station);
  //风场form.value.station
  //风机型号form.value.modelId

  state.modelList = data[0].modelList;
};
//所属部件
const getfetchRelatePart = async () => {
  const res = await fetchRelatePart();
  state.relatePartList = res;
};
// 查询风场AI、DI测点
const getfetchAIPointList = async () => {
  const res = await fetchAIPointList(props.form.station, props.form.modelId);
  state.AIPointList = res.sort(function (a, b) {
    return a.uniformCode - b.uniformCode;
  });
};

// 根据stationid和modelid获取ai测点显示数据
const getEditAiList = (stationId, modelId) => {
  const p = fetchAIPointList(stationId, modelId);

  p.then((res) => {
    state.AIPointList = res.sort(function (a, b) {
      return a.uniformCode - b.uniformCode;
    });
  });

  // state.AIPointList = res.sort(function (a, b) {
  //   return a.uniformCode - b.uniformCode;
  // });
};

// 根据stationid和modelid获取di测点显示数据
const getEditDiList = (stationId, modelId) => {
  const p = fetchDIPointList(stationId, modelId);
  p.then((res) => {
    state.DIPointList = res.sort(function (a, b) {
      return a.uniformCode - b.uniformCode;
    });
  });
};
const filterAIList = computed(() =>
  state.AIPointList?.filter(
    (data) =>
      !state.AIPointSearch ||
      data.uniformCode.includes(state.AIPointSearch) ||
      data.name.includes(state.AIPointSearch)
  )
);
const filterDIList = computed(() =>
  state.DIPointList?.filter(
    (data) =>
      !state.DIPointSearch ||
      data.uniformCode.includes(state.DIPointSearch) ||
      data.name.includes(state.DIPointSearch)
  )
);
const getfetchDIPointList = async () => {
  const res = await fetchDIPointList(props.form.station, props.form.modelId);
  state.DIPointList = res.sort(function (a, b) {
    return a.uniformCode - b.uniformCode;
  });
};
// 函数点击事件
const tabFuncRowClickHandle = (row) => {
  let elInput = document.getElementById("expressionInput");
  let startPos = elInput.selectionStart; //第0个字符到选中的字符
  let endPos = elInput.selectionEnd; //选中字符到末尾字符
  if (startPos === undefined || endPos === undefined) return;
  let txt = elInput.value;
  let func;
  if (
    row.lab === "MR" ||
    row.lab === "MAR" ||
    row.lab === "RiseExceed" ||
    row.lab === "Sustain" ||
    row.lab === "LastUpdateTime"
  ) {
    func = row.lab + "()";
  } else if (row.lab === "PI" || row.lab === "E") {
    func = "Math." + row.lab;
  } else {
    func = "Math." + row.lab + "()";
  }
  // 将插值添加到选中光标位置
  let result = txt.substring(0, startPos) + func + txt.substring(endPos);
  elInput.value = result;
  // 重新定义光标位置
  elInput.focus();
  if (row.lab === "PI" || row.lab === "E") {
    elInput.selectionStart = startPos + func.length;
    elInput.selectionEnd = startPos + func.length;
  } else {
    elInput.selectionStart = startPos + func.length - 1;
    elInput.selectionEnd = startPos + func.length - 1;
  }
  form.value.expressionShow = result; // 赋值给表单中的的字段
};
//rowDbclick
const rowDbclick = (row) => {
  elInputSplit(row.uniformCode);
};
// 表达式字符串拼接
const elInputSplit = async (val) => {
  let elInput = document.getElementById("expressionInput");
  let startPos = elInput.selectionStart;
  let endPos = elInput.selectionEnd;
  if (startPos === undefined || endPos === undefined) return;
  let txt = elInput.value;
  let txtSplit = val;
  let result = txt.substring(0, startPos) + txtSplit + txt.substring(endPos);
  elInput.value = result;
  elInput.focus();
  elInput.selectionStart = startPos + txtSplit.length;
  elInput.selectionEnd = startPos + txtSplit.length;
};
//保存
const save = async () => {
  const res = await custombj_postSave(form.value);
  console.warn(res);
  if (!res.success) {
    ElMessage.error(res.msg);
  } else {
    ElMessage.success(`保存成功!`);
    closeDialog();
  }
};
//提交
const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      save();
    } else {
      console.log("error submit!", fields);
    }
  });
};
//reset
const resetForm = (formEl) => {
  formEl.resetFields();
};
//confirm关闭
const handleClose = () => {
  ElMessageBox.confirm("确认关闭？")
    .then(() => {
      closeDialog();
    })
    .catch(() => {
      // catch error
    });
};
//关闭触发事件
const closeDialog = () => {
  resetForm(ruleFormRef.value);
  state.AIPointList = [];
  state.DIPointList = [];
  toEmits();
};
</script>
<style lang="less" scoped>
.col-box {
  display: flex;
  flex-direction: column;
}

.select-mini {
  width: 120px;
}

.el-tabs__content {
  padding: 0 !important;
}

.el-tabs--border-card {
  -webkit-box-shadow: none;
  box-shadow: none;
}

.border {
  border: solid red 1px;
}

.el-table--mini td {
  padding: 3px 0;
}

.el-button-group .el-button--primary {
  border: none;
}

.el-form--label-top .el-form-item__label {
  padding: 0;
}
</style>