<template>
  <div class="sec-left app-container point-mang-page" style="height: 100%">
    <div class="sec-line point-mang-left">
      <div class="qurey">
        <el-input
          :placeholder="$t('point_mang.PleaseEnterTheContent')"
          v-model="filterText"
          class="input-with-select"
        >
        </el-input>
        <el-button
          class="button"
          type="primary"
          icon="el-icon-search"
        ></el-button>
      </div>
      <div class="sec-a2 point-mang-tree-wrap">
        <el-tree
          :data="treeDataNew"
          :props="defaultProps"
          @node-click="handleNodeClick"
          node-key="devicetypeId"
          ref="tree"
          :filter-node-method="filterNode"
          class="point-mang-tree"
        ></el-tree>
      </div>
    </div>
    <div class="wid point-mang-right" style="flex: 1" v-if="devicetypeId">
      <div class="form point-mang-form" ref="form">
        <el-alert
          title="提示"
          class="point-mang-alert"
          type="info"
          :description="$t('point_mang.tableHeadMsg')"
          show-icon
        />
        <div class="line point-mang-toolbar">
          <div>
            <el-button type="primary" @click="addBtn" size="small" icon="el-icon-plus">{{
              $t("share.addTo")
            }}</el-button>
          </div>
          <div class="point-mang-toolbar-tip">（0/200）{{ $t("point_mang.tableHeadMsg") }}</div>
          <el-button type="primary" size="small" @click="submitForm">{{
            $t("share.save")
          }}</el-button>
        </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-popover
                  v-model="showTreePopover"
                  placement="bottom"
                  trigger="click"
                >
                  <div class="popover-content">
                    <el-tree
                      :data="DevicetypeIdOptions"
                      :props="defaultPropsObj"
                      @node-click="
                        (node) => handleNodeClickInSelect(node, scope.row)
                      "
                    />
                  </div>

                  <el-input
                    :key="scope.row.devicetypeName"
                    slot="reference"
                    v-model="scope.row.devicetypeName"
                    placeholder="请选择设备类型"
                    readonly
                    @click.native="showTreePopover = true"
                  />
                </el-popover>
              </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">
                <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"
                  @click="handleCopy(scope.row)"
                >
                  {{ $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>
    </div>
    <div class="wid point-mang-right point-mang-empty" v-if="!devicetypeId">
        <div style="line-height: 36px">请先选择左侧点位</div>
    </div>
    <el-dialog
      :title="$t('point_mang.SetIntelligentRecognitionType')"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
      custom-class="point-mang-dialog"
      border
    >
      <el-table
        :data="intelligenceTypeData"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        default-expand-all
        row-key="id"
        @selection-change="handleSelectionChangeDialog"
        ref="multipleTable"
        height="45vh"
      >
        <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 :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" v-if="scope.row.upperFlag == 1">
            <el-input
              v-model="scope.row.upperValue"
              :disabled="disabledFn(scope.row)"
            ></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" v-if="scope.row.lowerFlag == 1">
            <el-input
              v-model="scope.row.lowerValue"
              :disabled="disabledFn(scope.row)"
            ></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 {
  components: {},
  data() {
    return {
      treeDataNew: [],
      defaultProps: {
        children: "children",
        label: "devicetypeName",
      },
      tableData: [],
      // DevicetypeIdOptions: [],
      options: [],
      value: [],
      dialogVisible: false,
      intelligenceTypeData: [],
      devicetypeId: null,
      dialogTableSelect: [],
      stdpatrolPointId: null,
      dialogTableSelectName: [],
      filterText: null,
      showTreePopover: false,
      selectedDeviceTypeName: "",
      DevicetypeIdOptions: [],
      defaultPropsObj: {
        children: "children",
        label: "devicetypeName",
      },
    };
  },
  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 = Number(item.dictValue);
        });
        this.options = res.data;
      }
    });
  },
  methods: {
    handleNodeClickInSelect(data, row) {
      if (row) {
        row.componentDevicetypeId = data.devicetypeId;
        row.devicetypeName = data.devicetypeName;
        this.showTreePopover = false;
      }
    },
    getDeviceTypeNameById(id) {
      function findNode(nodes) {
        for (const node of nodes) {
          if (node.devicetypeId === id) return node.devicetypeName;
          if (node.children) {
            const result = findNode(node.children);
            if (result) return result;
          }
        }
        return "";
      }
      return findNode(this.DevicetypeIdOptions);
    },

    filterNode(value, data) {
      if (!value) return true;
      return data.devicetypeName.indexOf(value) !== -1;
    },
    init(qurey) {
      devicetype(qurey).then((res) => {
        this.treeDataNew = [];
        this.tableData = [];
        if (res.code == 200) {
          res.data.forEach((item) => {
            if (item.devicetypeId !== 1) {
              this.treeDataNew.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) {
          this.tableData = res.rows.map((row) => ({
            ...row,
            devicetypeName: this.getDeviceTypeNameById(
              row.componentDevicetypeId
            ),
          }));
        }
      });
      getTreeAreaDeviceSelect(data.devicetypeId).then((res) => {
        if (res.code == 200) {
          this.DevicetypeIdOptions = res.data.filter(
            (item) => item.devicetypeId !== 1 && item.powerMainEquFlag == "Yes"
          );
          this.$nextTick(() => {
            cilikList(data.devicetypeId).then((res2) => {
              if (res2.code == 200) {
                this.tableData = res2.rows.map((row) => ({
                  ...row,
                  devicetypeName: this.getDeviceTypeNameById(
                    row.componentDevicetypeId
                  ),
                }));
              }
            });
          });
        }
      });
    },
    areaNormalizer(node) {
      return {
        id: node.devicetypeId,
        label: node.devicetypeName,
        children: node.children,
      };
    },
    addBtn() {
      if (this.tableData.length < 200) {
        this.tableData.push({
          componentDevicetypeId: null,
          devicetypeName: "",
          patrolContent: "",
          mainDevicetypeId: null,
        });
      } else {
        this.$message.warning("最多添加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);
          this.$message({
            type: "success",
            message: "保存成功",
          });
        });
      } 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;
    },
    // 复制
    handleCopy(row) {
      let { stdpatrolPointId, ...newObj } = row;
      console.log(newObj, 111);
      newObj.patrolContent = row.patrolContent + "_复制";
      this.tableData.push(newObj);
    },
    handleNodeClickOption(data) {
      console.log(data, 111);
    },
    disabledFn(row) {
      console.log(
        this.$refs.multipleTable.selection.some((item) => item.id === row.id)
          ? false
          : false
      );
      return this.$refs.multipleTable.selection.some(
        (item) => item.id === row.id
      )
        ? false
        : true;
    },
  },
};
</script>

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

.sec-left {
  width: 100%;
  display: flex;
  height: 100%;
  min-height: 0;
  overflow: hidden;
}

.sec-line {
  width: 260px;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 12px;
  background: #0f124a;
  border: 1px solid #0b2567;
  box-sizing: border-box;
}

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

.wid {
  flex: 1;
  min-width: 0;
  display: flex;
  padding-left: 14px;
  overflow: hidden;
}

.point-mang-right {
  width: 100%;
}

.point-mang-form {
  width: 100%;
  height: 100%;
  min-height: 0;
  display: flex;
  flex-direction: column;
  padding: 12px;
  background: #0f124a;
  border: 1px solid #0b2567;
  overflow: hidden;
}

.point-mang-tree {
  color: #dcecff;
  background: transparent;
}

.point-mang-left ::v-deep .el-tree-node__content {
  height: 30px;
}

.point-mang-left ::v-deep .el-tree-node__content:hover {
  background: rgba(77, 223, 255, 0.12);
}

.point-mang-left ::v-deep .el-tree-node:focus > .el-tree-node__content {
  background: rgba(77, 223, 255, 0.18);
}

.point-mang-toolbar {
  flex: 0 0 auto;
  display: flex;
  align-items: center;
  justify-content: space-between;
  min-height: 36px;
  color: #dcecff;
}

.point-mang-toolbar-tip {
  margin: 0 10px;
  white-space: nowrap;
}

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

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

.point-mang-table ::v-deep .el-table__body-wrapper {
  overflow-y: auto;
}

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

.qurey {
  flex: 0 0 auto;
  display: flex;
  margin-bottom: 10px;
  gap: 10px;
  .input-with-select {
    flex: 1;
  }
  ::v-deep.el-button {
    background-color: #46a6ff !important;
    color: #fff !important ;
  }
}
.point-mang-alert {
  flex: 0 0 auto;
  margin-bottom: 10px;
}
.intelligenceType {
  color: rgb(17, 189, 217);
  cursor: pointer;
}
.popover-content {
  max-height: 200px;
  overflow-y: auto;
  padding: 5px 0;
}

::v-deep .point-mang-dialog {
  max-height: 70vh;
  display: flex;
  flex-direction: column;

  .el-dialog__body {
    flex: 1 1 auto;
    min-height: 0;
    overflow: hidden;
  }
}
// .tree-select {
//   position: absolute;
//   z-index: 9999999;
//   width: 100%;
//   max-height: 200px;
//   overflow-y: auto;
//   border: 1px solid #dcdfe6;
//   border-radius: 4px;
//   background: #fff;
//   box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
// }
</style>
