<template>
  <!-- 编辑弹出框 -->
  <el-dialog
    :visible="visible"
    width="1100px"
    :before-close="dialogBeforeClose"
    @open="dialogOpenHandle"
    @close="dialogCloseHandle"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-position="top"
      label-width="200px"
      :disabled="dialogStatus == 2"
    >
      <el-row type="flex" justify="space-between" align="middle" :gutter="10">
        <el-col :span="15">
          <el-form-item prop="name">
            <el-tag slot="label">规则名称</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="part">
            <el-tag slot="label">工艺环节</el-tag>
            <el-select v-model="form.part" class="select-mini">
              <el-option key="1" label="预处理" value="pretreatment" />
              <el-option key="2" label="干燥塔" value="drying" />
              <el-option key="3" label="蒸发车间" value="evaporation" />
            </el-select>
          </el-form-item>
          <el-form-item prop="rank">
            <el-tag slot="label">报警级别</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 slot="label">是否启用</el-tag>
            <el-switch
              v-model="form.enabled"
              :active-value="true"
              :inactive-value="false"
              active-color="#13ce66"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item prop="expression">
            <el-tag slot="label">表达式</el-tag>
            <el-input
              type="textarea"
              rows="11"
              v-model="form.expression"
              :value="form.expression"
              id="expressionInput"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-tabs type="border-card">
            <el-tab-pane label="AI测点">
              <el-input v-model="AIPointSearch" @input="AIInputChange">
                <el-button slot="append" icon="el-icon-search" />
              </el-input>
              <el-table
                size="mini"
                fit
                :show-header="false"
                :highlight-current-row="true"
                :stripe="false"
                :border="false"
                height="200"
                :data="AIPointList"
                @row-dblclick="tbAI_DBClickHandle"
              >
                <el-table-column prop="point" />
                <el-table-column prop="name" />
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="DI测点">
              <el-input v-model="DIPointSearch" @input="DIInputChange">
                <el-button slot="append" icon="el-icon-search" />
              </el-input>
              <el-table
                size="mini"
                fit
                :show-header="false"
                :highlight-current-row="true"
                :stripe="false"
                :border="false"
                height="200"
                :data="DIPointList"
                @row-dblclick="tbDI_DBClickHandle"
              >
                <el-table-column prop="point" />
                <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="230"
                :data="func"
                @row-dblclick="tabFuncRowClickHandle"
              >
                <el-table-column min-width="60%">
                  <template slot-scope="scope">
                    <el-popover trigger="hover" placement="bottom">
                      <p>描述：{{ scope.row.describe }}</p>
                      <p>参数：{{ scope.row.param }}</p>
                      <div slot="reference">
                        <span size="medium" transition="fade-in-linear">{{ scope.row.lab }}</span>
                      </div>
                    </el-popover>
                  </template>
                </el-table-column>
                <el-table-column min-width="40%">
                  <template slot-scope="scope">
                    <el-popover trigger="hover" placement="bottom">
                      <p>描述：{{ scope.row.describe }}</p>
                      <p>参数：{{ scope.row.param }}</p>
                      <div slot="reference">
                        <span size="medium" transition="fade-in-linear">{{ scope.row.name }}</span>
                      </div>
                    </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="btnOperatorClickHandle(item)"
                  style="width:60px;margin:8px;height:40px"
                >{{item}}</el-button>
              </el-button-group>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
      <el-row>
        <el-form-item prop="description">
          <el-tag slot="label">规则描述</el-tag>
          <el-input type="textarea" rows="2" v-model="form.description" />
        </el-form-item>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="btnCancelClickHandle">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { fetcPointList, alert_rule_postSave } from "../../api/requestAPI";
import axios from "axios";
export default {
  data() {
    return {
      visible: this.isVisible,
      isWindturbine: true,
      form: {
        id: "",
        name: "",
        description: "",
        expression: "",
        rank: 1,
        enabled: true, // 1可用-0禁用
        part: "",
      },
      AIDataSource: [],
      DIDataSource: [],
      AIPointList: [],
      DIPointList: [],
      AIPointSearch: "",
      DIPointSearch: "",
      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: "" },
      ],
      operator: [
        "+",
        "-",
        "*",
        "/",
        "(",
        ")",
        ">",
        ">=",
        "<",
        "<=",
        "==",
        "!=",
        "&&",
        "||",
        "!",
        "%",
        "true",
        "false",
        ".",
      ],
      rules: {
        name: [{ required: true, message: "请输入规则名称", trigger: "blur" }],
        part: [
          { required: true, message: "请选择工艺环节", trigger: "change" },
        ],
        rank: [
          { required: true, message: "请选择报警级别", trigger: "change" },
        ],
        expression: [
          { required: true, message: "表达式不能为空", trigger: "change" },
        ],
      },
    };
  },
  props: {
    isVisible: Boolean,
    dialogStatus: Number, //窗口状态：0-新增；1-修改；2-查看
    rowData: Object,
  },
  watch: {
    isVisible(val) {
      this.visible = val;
      if (val == true) {
        this.query_AI_DI_Point();
      }
    },
    rowData(val) {
      this.form = JSON.parse(JSON.stringify(val));
    },
  },
  methods: {
    // 点击取消事件
    btnCancelClickHandle() {
      this.visible = false;
      this.$emit("cbFunc", this.visible);
    },
    // 窗口关闭前的回调
    dialogBeforeClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
          this.visible = false;
          this.$emit("cbFunc", this.visible);
        })
        .catch((_) => {});
    },
    // 查询风场AI、DI测点
    query_AI_DI_Point() {
      // 获取AI测点
      fetcPointList({ type: "AI" }).then((res) => {
        if (res.status == 20000) {
          this.AIPointList = res.data;
          this.AIDataSource = res.data;
        }
      });
      // 获取DI测点
      fetcPointList({ type: "DI" }).then((res) => {
        if (res.status == 20000) {
          this.DIPointList = res.data;
          this.DIDataSource = res.data;
        }
      });
    },

    // 函数点击事件
    tabFuncRowClickHandle(row) {
      let _row = this.deepClone(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;
      }
      this.form.expression = result; // 赋值给表单中的的字段
    },
    // 运算符点击事件
    btnOperatorClickHandle(row) {
      this.elInputSplit(row);
    },
    //提交表单
    submit() {
      this.form.expression = document.getElementById("expressionInput").value;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.$confirm("确认关闭？")
            .then(() => {
              console.log(this.form);
              console.log(this.dialogStatus);
              switch (this.dialogStatus) {
                //窗口状态：0-新增；1-修改；2-查看
                case 0:
                  alert_rule_postSave(this.form)
                    .then((response) => {
                      console.log(response.data.status);
                      if (response.data.status == 20000) {
                        this.$message.success("保存成功");
                        // 关闭窗口
                        this.visible = false;
                        this.$emit("cbFunc", this.visible);
                      } else if (
                        response.data.status == 5000 ||
                        response.data.status == 5001
                      ) {
                        this.$message.error("未登陆,或登陆失效");
                        this.$router.push("/login");
                      } else if (response.data.status == 5002) {
                        this.$message.error(response.data.msg);
                      }
                    })
                    .catch((err) => {
                      console.log(err);
                    });
                  break;
                case 1:
                  alert_rule_postSave(this.form)
                    .then((response) => {
                      if (response.data.success) {
                        this.$message.success("保存成功");
                        // 关闭窗口
                        this.visible = false;
                        this.$emit("cbFunc", this.visible);
                      } else if (
                        response.data.status != null &&
                        response.data.status == 521
                      ) {
                        this.$message.error("登陆过期");
                        this.$router.push("/login");
                        return;
                      } else {
                        this.$message.error(response.data.msg);
                      }
                    })
                    .catch((err) => {
                      console.log(err);
                    });
                  break;
                default:
                  // 关闭窗口
                  this.visible = false;
                  this.$emit("cbFunc", this.visible);
                  break;
              }
            })
            .catch((err) => {
              console.log(err);
            });
        }
      });
    },
    // 窗口打开事件 - 做重置表单操作
    dialogOpenHandle() {
      // 重置表单
      if (this.dialogStatus === 0) {
        this.isWindturbine = true;
        (this.AIDataSource = []),
          (this.DIDataSource = []),
          (this.AIPointList = []),
          (this.DIPointList = []),
          (this.AIPointSearch = ""),
          (this.DIPointSearch = ""),
          (this.form = { enabled: "1" });
        if (this.$refs["form"] != undefined) {
          this.$refs["form"].resetFields();
        }
      } else {
        this.AIPointSearch = "";
        this.DIPointSearch = "";
      }
    },
    // 窗口关闭事件 - 做重置表单操作
    dialogCloseHandle() {
      // 重置表单
      if (this.dialogStatus === 0) {
        this.isWindturbine = true;
        (this.AIDataSource = []),
          (this.DIDataSource = []),
          (this.AIPointList = []),
          (this.DIPointList = []),
          (this.AIPointSearch = ""),
          (this.DIPointSearch = ""),
          (this.form = { enabled: "1" });
        if (this.$refs["form"] != undefined) {
          this.$refs["form"].resetFields();
        }
      } else {
        this.AIPointSearch = "";
        this.DIPointSearch = "";
      }
    },
    // AI测点模糊查询
    AIInputChange() {
      this.AIPointList = this.AIDataSource.filter((i) => {
        return i.name.indexOf(this.AIPointSearch) != -1;
      });
    },
    // DI测点模糊查询
    DIInputChange() {
      this.DIPointList = this.DIDataSource.filter((i) => {
        return i.name.indexOf(this.DIPointSearch) != -1;
      });
    },
    tbAI_DBClickHandle(row) {
      this.elInputSplit(row.point);
    },
    tbDI_DBClickHandle(row) {
      this.elInputSplit(row.point);
    },
    deepClone(obj) {
      let _obj = JSON.stringify(obj),
        objClone = JSON.parse(_obj);
      return objClone;
    },
    // 表达式字符串拼接
    elInputSplit(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;
      // this.form.expression = result;
    },
  },
};
</script>
<style>
.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>