<template>
  <el-dialog
    :title="alertTitle"
    :visible.sync="visible"
    width="55%"
    @close="handleClose"
    :close-on-click-modal="false"
    append-to-body
  >
    <el-row class="card-page">
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        label-width="75px"
      >
        <el-form-item label="算法类型" prop="taskType">
          <el-select
            style="width: 150px"
            v-model="queryParams.taskType"
            placeholder="全部"
            filterable
            clearable
            popper-class="card-select-dropdown"
          >
            <el-option
              v-for="item in listPatroltype"
              :key="item.algId"
              :label="item.algName"
              :value="item.algName"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="算法名称" prop="devType">
          <el-select
            style="width: 150px"
            v-model="queryParams.devType"
            placeholder="全部"
            filterable
            clearable
            popper-class="card-select-dropdown"
          >
            <el-option label="表记识别算法" value="0" />
            <el-option label="机器人" value="1" />
            <el-option label="视频" value="2" />
          </el-select>
        </el-form-item>

        <el-form-item label="算法状态" prop="fileStatus">
          <el-select
            style="width: 150px"
            v-model="queryParams.fileStatus"
            placeholder="全部"
            filterable
            clearable
            popper-class="card-select-dropdown"
          >
            <el-option label="未归档" value="0" />
            <el-option label="已归档" value="1" />
          </el-select>
        </el-form-item>

        <el-form-item label="时间">
          <el-date-picker
            style="width: 200px; border-radius: 5px; border: 1px"
            v-model="timeValue"
            type="date"
            clearable
            placeholder="选择时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="pickerOptions0"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >查询</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <el-form label-width="0px" :model="form" ref="ruleForm">
        <el-col :span="24">
          <el-table
            v-loading="loading"
            :data="algList"
            row-key="id"
            border
            default-expand-all
            height="400px"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          >
            <el-table-column
              type="selection"
              align="center"
              width="50"
              v-if="!disableCheck"
            >
              <template #header>
                <span></span>
              </template>
              <template slot-scope="scope">
                <el-checkbox
                  :indeterminate="scope.row.isIndeterminate"
                  v-model="scope.row.checked"
                  @change="handleRowCheckedChange(scope.row)"
                ></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column
              type="index"
              align="center"
              label="序号"
              width="50"
            />
            <el-table-column
              prop="name"
              header-align="center"
              label="算法名称"
              min-width="180"
            >
            </el-table-column>
            <el-table-column label="算法类型" align="center" prop="name" />
            <el-table-column label="时间" align="center" prop="name" />
            <el-table-column prop="upperValue" align="center" width="180">
              <template #header>
                <div>阈值上限 <span style="color: red">*</span></div>
              </template>
              <template slot-scope="scope">
                <el-form-item
                  style="margin-top: 0; margin-bottom: 0"
                  v-if="scope.row.upperFlag"
                  :prop="'algList[' + scope.$index + '].upperValue'"
                  :rules="{
                    required:
                      scope.row.upperFlag && scope.row.checked ? true : false,
                    message: '必填',
                    trigger: 'blur',
                  }"
                >
                  <el-input
                    v-model="scope.row.upperValue"
                    :disabled="!scope.row.checked"
                  ></el-input>
                  <span slot="error"> </span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="lowerValue" align="center" width="180">
              <template #header>
                <div>阈值下限 <span style="color: red">*</span></div>
              </template>
              <template slot-scope="scope">
                <el-form-item
                  style="margin-top: 0; margin-bottom: 0"
                  v-if="scope.row.lowerFlag"
                  :prop="'algList[' + scope.$index + '].lowerValue'"
                  :rules="{
                    required:
                      scope.row.lowerFlag && scope.row.checked ? true : false,
                    message: '必填',
                    trigger: 'blur',
                  }"
                >
                  <el-input
                    v-model="scope.row.lowerValue"
                    :disabled="!scope.row.checked"
                  ></el-input>
                  <span slot="error"> </span>
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-form>
    </el-row>
    <span slot="footer" class="dialog-footer card-page">
      <el-button @click="eventOk" :disabled="loading" type="primary"
        >确定</el-button
      >
      <el-button @click="visible = false">取消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getAlgList, getAlgPartType } from "@/api/basedata/area/area";
import linq from "linq";
export default {
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    // 数据源json格式
    alarmThreshold: {
      type: String,
      default: "",
    },
    // 引用选择框
    disableCheck: {
      type: Boolean,
      default: false,
    },
    // 列表只展示已选算法
    filterCheckedAlgs: {
      type: Boolean,
      default: false,
    },
  },
  watch: {
    show(newVal) {
      this.visible = newVal;
      if (newVal === true) {
        this.loadData();
      }
    },
  },
  data() {
    return {
      loading: false,
      form: {
        algList: [],
      },
      visible: false,
      algList: [] /* 算法类型 */,
      alertTitle: "设置智能识别类型" /* 弹窗标题 */,
      rules: {
        algId: [{ required: true, message: "必选", trigger: "blur" }],
        algSubtypeId: [{ required: true, message: "必选", trigger: "blur" }],
        upperValue: [{ required: true, message: "必选", trigger: "blur" }],
        lowerValue: [{ required: true, message: "必选", trigger: "blur" }],
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskType: null,
        devType: null,
        fileStatus: null,
      },
    };
  },
  created() {},
  computed: {},
  methods: {
    loadData() {
      this.loading = true;
      //算法小类
      getAlgPartType()
        .then((res) => {
          // 如果开启了已选过滤
          if (this.filterCheckedAlgs) {
            //筛选数据
            if (this.alarmThreshold.length > 0) {
              const alarmThreshold = JSON.parse(this.alarmThreshold);
              const chooseIds = linq
                .from(alarmThreshold)
                .select((x) => x.id.replace("sub_", ""))
                .toArray();
              res.rows = res.rows.filter((x) =>
                chooseIds.includes(x.algSubtypeId.toString())
              );
            }
          }
          res.rows.forEach((x) => {
            x.hasChildren = false;
            x.children = [];
          });
          this.loading = false;
          this.loading = true;
          //算法大类
          getAlgList()
            .then((res1) => {
              const treeData = [];
              res1.rows.forEach((row) => {
                const tmp = {
                  id: "alg_" + row.algId,
                  name: row.algName,
                  sourceId: row.algId,
                  checked: false,
                  isIndeterminate: false,
                  upperValue: "",
                  lowerValue: "",
                  lowerFlag: row.lowerFlag,
                  upperFlag: row.upperFlag,
                  code: "",
                  parent: null,
                  children: null,
                };
                tmp.children = linq
                  .from(res.rows)
                  .where((x) => x.algId === row.algId)
                  .select((alg) => {
                    return {
                      sourceId: alg.algSubtypeId,
                      id: "sub_" + alg.algSubtypeId,
                      name: alg.algSubtypeName,
                      checked: false,
                      isIndeterminate: false,
                      code: alg.algSubtypeCode,
                      upperValue: "",
                      lowerValue: "",
                      lowerFlag: alg.lowerFlag,
                      upperFlag: alg.upperFlag,
                      parent: tmp,
                    };
                  })
                  .toArray();
                //如果开启了过滤 需要排除 没有子类的大类
                if (!(this.filterCheckedAlgs && tmp.children.length === 0)) {
                  treeData.push(tmp);
                }
              });
              this.algList = treeData;
              this.form.algList = this.treeToList(treeData);
              this.loading = false;
              this.renderData();
            })
            .catch(() => {
              this.loading = false;
            });
        })
        .catch(() => {
          this.loading = false;
        });
    },
    //回显勾选框
    renderData() {
      if (this.alarmThreshold.length > 0) {
        const alarmThreshold = JSON.parse(this.alarmThreshold);
        alarmThreshold.forEach((subAlg) => {
          const tmpAlg = this.form.algList.find((c) => c.id === subAlg.id);
          if (tmpAlg) {
            tmpAlg.checked = true;
            tmpAlg.lowerValue = subAlg.lowerValue;
            tmpAlg.upperValue = subAlg.upperValue;
            if (tmpAlg.parent) {
              tmpAlg.parent.checked = linq
                .from(tmpAlg.parent.children)
                .all((x) => x.checked);
              if (!tmpAlg.parent.checked) {
                tmpAlg.parent.isIndeterminate = linq
                  .from(tmpAlg.parent.children)
                  .any((x) => x.checked);
              }
            }
          }
        });
      }
    },
    treeToList(nodes) {
      let result = [];
      nodes.forEach((node) => {
        result.push(node);
        if (node.children && node.children.length > 0) {
          result = result.concat(this.treeToList(node.children));
        }
      });
      return result;
    },
    handleRowCheckedChange(row) {
      //我的子类的状态都跟我的状态相同，相当于全选
      row.children && row.children.forEach((x) => (x.checked = row.checked));
      if (row.parent) {
        row.parent.checked = linq
          .from(row.parent.children)
          .all((x) => x.checked);
        if (!row.parent.checked) {
          row.parent.isIndeterminate = linq
            .from(row.parent.children)
            .any((x) => x.checked);
        }
      } else {
        if (row.checked) {
          row.isIndeterminate = false;
        }
      }
    },
    //弹窗关闭事件
    handleClose() {
      // 重置表单
      this.resetForm("ruleForm");
      this.visible = false;
      this.$emit("update:show", false);
    },
    //选择好智能识别类型后的事件
    eventOk() {
      const me = this;
      this.$refs.ruleForm.validate((ok) => {
        if (ok) {
          me.visible = false;
          this.$emit(
            "confirm",
            this.form.algList.filter((x) => x.checked)
          );
        }
      });
    },
  },
};
</script>
