<template>
  <div class="app-container point-mang-page">
    <div class="point-mang-layout">
      <section class="point-mang-left">
        <div class="qurey">
          <el-input
            :placeholder="$t('point_mang.PleaseEnterTheContent')"
            v-model="filterText"
            class="input-with-select"
          >
          </el-input>
        </div>
        <el-tree
          :data="treeData"
          :props="defaultProps"
          @node-click="handleNodeClick"
          node-key="devicetypeId"
          ref="tree"
          :filter-node-method="filterNode"
          class="point-mang-tree"
        ></el-tree>
      </section>
      <section class="point-mang-right" v-if="devicetypeId">
        <div class="point-mang-toolbar">
          <el-button type="primary" @click="addBtn">{{
            $t("share.addTo")
          }}</el-button>
          <span>（0/200）{{ $t("point_mang.tableHeadMsg") }}</span>
        </div>
        <div class="point-mang-table-wrap">
        <el-table :data="tableData" class="point-mang-table" height="100%">
          <el-table-column
            prop="date"
            :label="$t('point_mang.index')"
            width="55"
            type="index"
            align="center"
          ></el-table-column>
          <el-table-column
            :label="$t('point_mang.equipmentClassification')"
            :render-header="addRedStar"
            align="center"
          >
            <template slot-scope="scope">
              <el-select
                :placeholder="
                  $t('share.PleaseChoose') +
                  $t('point_mang.equipmentClassification')
                "
                v-model="scope.row.componentDevicetypeId"
              >
                <el-option
                  :label="item.devicetypeName"
                  :value="item.devicetypeId"
                  v-for="item in DevicetypeIdOptions"
                  :key="item.devicetypeId"
                >
                </el-option>
              </el-select>
            </template>
          </el-table-column>

          <el-table-column
            :label="$t('point_mang.InspectionStandards')"
            :render-header="addRedStar"
            align="center"
          >
            <template slot-scope="scope">
              <el-input
                type="textarea"
                :placeholder="
                  $t('share.PleaseChoose') + $t('point_mang.PleaseEnter')
                "
                v-model="scope.row.patrolContent"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column :label="$t('point_mang.dataFormat')" align="center">
            <template slot-scope="scope">
              <!-- multiple
                filterable
                allow-create
                default-first-option -->
              <el-select
                v-model="scope.row.mainDevicetypeId"
                :placeholder="
                  $t('share.PleaseChoose') + $t('point_mang.dataFormat')
                "
              >
                <el-option
                  v-for="item in options"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                >
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('point_mang.IntelligentRecognitionType')"
            align="center"
          >
            <template slot-scope="scope">
              <span
                class="intelligenceType"
                @click="intelligenceTypeBtn(scope.row)"
                >{{
                  scope.row.algSubtypeName ? scope.row.algSubtypeName : "设置"
                }}</span
              >
            </template>
          </el-table-column>
          <el-table-column :label="$t('share.operate')" align="center">
            <template slot-scope="scope">
              <el-button size="mini" type="primary">
                {{ $t("share.copy") }}
              </el-button>
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.row, scope.$index)"
                >{{ $t("share.delete") }}</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        </div>
        <div class="saveBtn">
          <el-button type="primary" @click="submitForm">{{
            $t("share.save")
          }}</el-button>
        </div>
      </section>
      <section class="point-mang-right point-mang-empty" v-if="!devicetypeId">
        <div style="line-height: 36px">请先选择左侧点位</div>
      </section>
    </div>
    <el-dialog
      :title="$t('point_mang.SetIntelligentRecognitionType')"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
      border
    >
      <el-table
        :data="intelligenceTypeData"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        default-expand-all
        row-key="id"
        @selection-change="handleSelectionChangeDialog"
        ref="multipleTable"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          type="index"
          width="55"
          align="center"
          :label="$t('point_mang.index')"
        ></el-table-column>
        <!-- <el-table-column
          prop="algName"
          align="center"
          :label="$t('point_mang.AlgorithmName')"
        ></el-table-column> -->
        <el-table-column :label="$t('patrolpoint.AlgorithmName')">
          <template slot-scope="scope">
            {{
              scope.row.algSubtypeName
                ? scope.row.algSubtypeName
                : scope.row.algName
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="patrolContent"
          align="center"
          :label="$t('point_mang.ThresholdUpperLimit')"
          :render-header="addRedStar"
        >
          <!-- <template slot-scope="scope">
            <el-input></el-input>
          </template> -->
        </el-table-column>
        <el-table-column
          prop="mainDevicetypeId"
          align="center"
          :label="$t('point_mang.LowerThresholdLimit')"
          :render-header="addRedStar"
        >
          <!-- <template slot-scope="scope">
            <el-input></el-input>
          </template> -->
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">{{ $t("share.cancel") }}</el-button>
        <el-button type="primary" @click="dialogTableOk">{{
          $t("share.confirm")
        }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getTreeAreaDeviceSelect,
  cilikList,
  devicetype,
  dataFormat,
  add,
  remove,
  algList,
  subtypeList,
} from "@/api/point/point_mang";
export default {
  data() {
    return {
      treeData: [],
      defaultProps: {
        children: "children",
        label: "devicetypeName",
      },
      tableData: [],
      DevicetypeIdOptions: [],
      options: [],
      value: [],
      dialogVisible: false,
      intelligenceTypeData: [],
      devicetypeId: null,
      dialogTableSelect: [],
      stdpatrolPointId: null,
      dialogTableSelectName: [],
      filterText: null,
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {},
  mounted() {
    this.init();
    devicetype().then((res) => {
      if (res.code == 200) {
        res.data.forEach((item) => {
          if (item.devicetypeId !== 1) {
            this.DevicetypeIdOptions.push(item);
          }
        });
      }
    });
    dataFormat().then((res) => {
      if (res.code == 200) {
        console.log(this.options, res.data);
        res.data.forEach((item) => {
          item.dictValue = String(item.dictValue);
        });
        this.options = res.data;
      }
    });
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true;
      return data.devicetypeName.indexOf(value) !== -1;
    },
    init(qurey) {
      getTreeAreaDeviceSelect(qurey).then((res) => {
        this.tableData = [];
        if (res.code == 200) {
          res.data.forEach((item) => {
            if (item.devicetypeId !== 1) {
              this.treeData.push(item);
            }
          });
        }
      });
    },
    // 给表头加必填符号*
    addRedStar(h, { column }) {
      return [
        h("span", { style: "color: red" }, "*"),
        h("span", " " + column.label),
      ];
    },
    intelligenceTypeBtn(row) {
      this.stdpatrolPointId = row.stdpatrolPointId;
      subtypeList().then((res0) => {
        if (res0.code == 200) {
          algList().then((res1) => {
            if (res1.code == 200) {
              let list = res1.rows;
              list.forEach((item) => {
                item.children = [];
                item.id = `${item.algId}_${item.algId}`;
                res0.rows.forEach((i) => {
                  i.id = i.algSubtypeId;
                  if (item.algId == i.algId && item.algName == i.algName) {
                    item.children.push(i);
                  }
                });
              });
              this.intelligenceTypeData = list;
              this.dialogVisible = true;
              this.$nextTick(() => {
                if (row.alarmThreshold) {
                  let data = JSON.parse(row.alarmThreshold);
                  let idArr = [];
                  data.forEach((item) => {
                    idArr.push(item.id.split("_")[1]);
                  });
                  idArr.forEach((id) => {
                    let show = res0.rows.find(
                      (item) => item.algSubtypeId == id
                    );
                    if (show) {
                      this.$refs.multipleTable.toggleRowSelection(show, true);
                    }
                  });
                }
              });
            }
          });
        }
      });
    },
    // 给表头加必填符号*
    addRedStar(h, { column }) {
      return [
        h("span", { style: "color: red" }, "*"),
        h("span", " " + column.label),
      ];
    },
    // 树点击
    handleNodeClick(data) {
      console.log(data, 11111111111);
      this.devicetypeId = data.devicetypeId;
      this.tableData = [];
      this.initClickList(data);
    },
    initClickList(data) {
      cilikList(data.devicetypeId).then((res) => {
        if (res.code == 200) {
          console.log(res, 111);
          this.tableData = res.rows;
        }
      });
    },
    addBtn() {
      if (this.tableData.length < 200) {
        this.tableData.push({});
      } else {
        this.$message({
          type: "warning",
          message: "最多添加200条数据!",
        });
      }
    },
    // 保存
    submitForm() {
      if (!this.tableData.length) return;
      let flag = this.tableData.every((item) => {
        if (item.componentDevicetypeId && item.patrolContent) {
          return true;
        } else {
          return false;
        }
      });

      if (flag) {
        add(this.tableData).then((res) => {
          this.initClickList(this.devicetypeId);
        });
      } else {
        this.$message({
          type: "warning",
          message: "必填项不能为空!",
        });
      }
    },
    // 删除
    handleDelete(row, index) {
      if (!row.stdpatrolPointId) {
        this.tableData.splice(index, 1);
      } else {
        remove(row.stdpatrolPointId).then((res) => {
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.initClickList(row);
          }
        });
      }
      return;
    },
    // 智能识别多选
    handleSelectionChangeDialog(val) {
      this.dialogTableSelect = [];
      this.dialogTableSelectName = [];
      val.forEach((item) => {
        let data = {
          id: `sub_${item.algSubtypeId}`,
          code: item.algSubtypeCode || "",
          upperValue: item.upperValue || "",
          lowerValue: item.lowerValue || "",
          algSubtypeName: item.algSubtypeName || "",
        };
        this.dialogTableSelect.push(data);
        this.dialogTableSelectName.push(item.algSubtypeName);
      });
    },
    dialogTableOk() {
      this.dialogVisible = false;
      console.log(this.dialogTableSelect, this.stdpatrolPointId);
      this.tableData.forEach((item) => {
        if (item.stdpatrolPointId == this.stdpatrolPointId) {
          item.alarmThreshold = JSON.stringify(this.dialogTableSelect);
          item.algSubtypeName = this.dialogTableSelectName.join(",");
        }
      });
    },
    handleClose() {
      this.dialogVisible = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.point-mang-page {
  padding: 14px;
  overflow: hidden;
}

.point-mang-layout {
  flex: 1 1 auto !important;
  min-height: 0;
  height: 100%;
  display: grid;
  grid-template-columns: 260px minmax(0, 1fr);
  gap: 14px;
  overflow: hidden;
}

.point-mang-left,
.point-mang-right {
  height: 100%;
  min-height: 0;
  overflow: hidden;
}

.point-mang-left,
.point-mang-right {
  display: flex;
  flex-direction: column;
  padding: 12px;
  background: #0f124a;
  border: 1px solid #0b2567;
}

.point-mang-tree {
  flex: 1 1 auto;
  min-height: 0;
  overflow-y: auto;
  overflow-x: hidden;
}

.point-mang-toolbar {
  flex: 0 0 auto;
  display: flex;
  align-items: center;
  gap: 12px;
  min-height: 36px;
  color: #dcecff;
}

.point-mang-table-wrap {
  flex: 1 1 auto;
  min-height: 0;
  height: 0;
  margin-top: 10px;
  overflow: hidden;
}

.point-mang-table {
  height: 100%;
}

.point-mang-empty {
  align-items: center;
  justify-content: center;
  color: #dcecff;
}

.qurey {
  flex: 0 0 auto;
  display: flex;
  margin-bottom: 10px;
  ::v-deep.el-button {
    background-color: #46a6ff !important;
    color: #fff !important ;
  }
}
.intelligenceType {
  color: rgb(17, 189, 217);
  cursor: pointer;
}
.saveBtn {
  flex: 0 0 auto;
  text-align: center;
  margin-top: 10px;
}
</style>
