<template>
  <div class="safe-monitor-setting-page">
    <TopBackTitle :showBackBtn="false"></TopBackTitle>
    <div class="container-box flex p-16">
      <div class="tree-box">
        <el-input v-model="filterText" placeholder="请输入关键字"></el-input>
        <el-tree
          class="filter-tree mt-10"
          highlight-current
          :data="treeData"
          :props="defaultProps"
          lazy
          :load="loadTree"
          :filter-node-method="filterNode"
          @node-click="handleClickTree"
          ref="tree"
        >
        </el-tree>
      </div>
      <div class="content-box" ref="contentRef">
        <el-table
          class="mt-12"
          :data="tableData"
          border
          style="width: 100%"
          :height="tableHeight"
        >
          <el-table-column type="index" label="序号" width="60">
          </el-table-column>
          <el-table-column prop="stnm" label="测站名称"></el-table-column>
          <el-table-column prop="stcd" label="测站编码"></el-table-column>
          <el-table-column prop="flag" label="是否代表站"> 否 </el-table-column>
          <el-table-column prop="prjtp" label="测站类型"> </el-table-column>
          <el-table-column prop="prjtpCode" label="测站类型编码">
          </el-table-column>
          <el-table-column prop="monProj" label="监测要素"> </el-table-column>
          <el-table-column prop="stcdOv" label="测站概况"> </el-table-column>
          <el-table-column label="操作" width="100">
            <template slot-scope="scope">
              <el-button
                type="text"
                :disabled="!scope.row.monProj"
                @click="handleSetForm(scope.row)"
                >告警配置</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <div class="mt-24 flex justify-end">
          <el-pagination
            background
            layout="prev, pager, next"
            :page-size="params.pageSize"
            :total="params.total"
          >
          </el-pagination>
        </div>

        <el-tabs
          class="mt-12"
          v-model="currentType"
          type="border-card"
          @tab-click="handleChangeTab"
          v-if="tabsList.length"
        >
          <el-tab-pane
            lazy
            v-for="tabItem in tabsList"
            :key="tabItem.label"
            :label="tabItem.label"
            :name="tabItem.key"
          >
            <Form
              :disabled="!currentResInfo"
              v-if="formConfig[tabItem.key]"
              :formData="formConfig[tabItem.key].formData"
              :rules="formConfig[tabItem.key].rules"
              :formItems="formConfig[tabItem.key].formItems"
              @submit="handleSaveRowForm"
            ></Form>
          </el-tab-pane>
        </el-tabs>
        <div v-else class="no-tabs-box mt-16">暂无监测要素</div>
      </div>
    </div>
  </div>
</template>
<script>
import TopBackTitle from "@/components/TopBackTitle";

import { getAreasData } from "@/api/areas/index";
import {
  getReservoirBaseListData,
  getReservoirCZListData,
  saveReservoirCZMonitorConfigData,
  getReservoirCZMonitorConfigData,
} from "@/api/reservoir";
import { getRunProjectList } from "@/api/dike";

import { formConfig } from "./js";
import Form from "./components/Form.vue";

export default {
  components: { TopBackTitle, Form },
  data() {
    return {
      formConfig: JSON.parse(JSON.stringify(formConfig)),
      currentType: "",
      tabsList: [
        // {
        //   label: "水情监测",
        //   key: "waterCase",
        // },
        // {
        //   label: "降雨监测",
        //   key: "rainCase",
        // },
        // {
        //   label: "渗流监测",
        //   key: "vadoseCase",
        // },
        // {
        //   label: "变形监测",
        //   key: "distortedCase",
        // },
        // {
        //   label: "应力监测",
        //   key: "stressCase",
        // },
        // {
        //   label: "应变监测",
        //   key: "strainCase",
        // },
        // {
        //   label: "水利学量监测",
        //   key: "wccmCase",
        // },
      ],
      filterText: "",
      treeData: [],
      defaultProps: {
        children: "children",
        label: "label",
        isLeaf: "leaf",
      },
      params: {
        pageSize: 20,
        pageNum: 1,
        total: 0,
      },
      searchCode: "",
      searchType: "",
      searchTypeOptions: [],
      tableData: [],
      currentResInfo: null,
      currentCZInfo: null,
      tableHeight: null,
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  computed: {},
  created() {},
  mounted() {
    let h = this.$refs.contentRef.offsetHeight - 490 - 60;
    this.tableHeight = h > 0 ? h : 300;
  },
  methods: {
    getTableData() {
      getReservoirCZListData({
        pageSize: this.params.pageSize,
        pageNum: this.params.pageNum,
        data: {
          prjcd: this.currentResInfo.dikeCode,
        },
      }).then((res) => {
        this.tableData = res.records;
        this.params.total = res.total;
      });
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    loadTree(node, resolve) {
      console.log("loadTree-node >>>>>  ", node, node.isLeaf);
      const { level, isLeaf, data } = node;
      if (isLeaf || data.layer === 4) {
        getRunProjectList({
          pageSize: 1000,
          pageNum: 1,
          data: {
            adcd: data.value,
          },
        }).then((res) => {
          console.log("load-true??? >>>>>  ", res);
          if (res.records) {
            resolve(
              res.records.map((item) => {
                return {
                  label: item.dikeName,
                  value: item.dikeCode,
                  dikeCode: item.dikeCode,
                  dikeName: item.dikeName,
                  layer: 2,
                  leaf: true,
                };
              })
            );
          } else {
            resolve([]);
          }
        });
        return;
      }
      // 非最后一级节点处理
      getAreasData(data.value).then((res) => {
        resolve(
          res.data.map((item) => {
            return {
              label: item.name,
              value: item.id,
              parentid: item.parentid,
              layer: item.layer,
              leaf: item.layer < 4,
            };
          })
        );
      });
    },
    handleClickTree(data, node) {
      console.log("handleClickTree111 >>>>>  ", data, node);
      if (node.isLeaf && data.layer < 4) {
        console.log("点击叶子节点----加载测站列表 >>>> ");
        this.tableData = [];
        this.tabsList = [];
        this.params.pageNum = 1;
        this.currentResInfo = data;
        this.getTableData();
      }
    },
    // 配置
    handleSetForm(row) {
      this.currentCZInfo = row;
      if (row.monProj) {
        let types = row.monProj.split(",");
        let keys = Object.keys(formConfig);
        let tabs = Object.values(formConfig);
        let list = types
          .map((type) => {
            let index = tabs.findIndex((v) => v.formData.mpType === type);
            if (index !== -1) {
              return {
                label: tabs[index].label,
                key: keys[index],
              };
            }
          })
          .filter((v) => v);
        this.tabsList = list;
        this.currentType = (list[0] && list[0].key) || "";
      } else {
        this.tabsList = [];
      }
      getReservoirCZMonitorConfigData(row.id).then((res) => {
        if (res.data?.length) {
          res.data.forEach((item) => {
            let formData =
              (this.formConfig[item.mpType] &&
                this.formConfig[item.mpType].formData) ||
              {};
            Object.keys(formData).forEach((key) => {
              formData[key] = item[key];
            });
            formData.id = item.id;
            if (
              (item.warnValue && item.warnValue.split(",").length > 1) ||
              item.mpType === "HDM01"
            ) {
              formData.warnValueArr = item.warnValue.split(",");
            } else {
              formData.warnValueArr = [];
            }
            formData.tempUserList = [];
            if (item.warnOperators && item.warnOperators.length) {
              formData.tempUserList = item.warnOperators.map((v) => v.name);
            }
          });
          console.log("此时formConfig >>> ", this.formConfig);
          console.log("此时tabs >>> ", this.tabsList);
        }
      });
    },
    handleSaveRowForm(data) {
      console.log("handleSaveRowForm-data >>>>>  ", data);
      saveReservoirCZMonitorConfigData({
        ...data,
        warnInterval:
          data.warnInterval !== "" ? Number(data.warnInterval) : null,
        dikeCode: this.currentCZInfo.prjcd,
        stcd: this.currentCZInfo.stcd,
      })
        .then((res) => {
          this.$message.success("保存成功");
        })
        .catch((err) => {
          console.log("err >>>>>  ", err);
          this.$message.error("保存失败");
        });
    },
    handleChangeTab(tab) {
      console.log("handleChangeTab >>>>>  ", tab);
    },
  },
};
</script>
<style scoped lang="scss">
.safe-monitor-setting-page {
  position: relative;
  font-size: 14px;
  height: 100%;

  .container-box {
    height: calc(100% - 56px);
  }

  .tree-box {
    flex-shrink: 0;
    width: 240px;
    padding: 12px;
    background: #fff;
    border-radius: 2px;
  }

  .filter-tree {
    overflow: auto;
    height: calc(100% - 46px);
  }

  .content-box {
    flex: 1;
    background: #fff;
    margin-left: 10px;
    padding: 12px;
    overflow: auto;
  }

  .no-tabs-box {
    padding: 72px;
    text-align: center;
    border: 1px solid #ccc;
    box-shadow: 0 0 1px 2px #eee;
  }

  .bottom-box {
    border: 1px solid #ccc;
    padding: 10px;
    background: #f4f5f7;
  }

  .w-100 {
    width: 100px;
  }

  .w-180 {
    width: 180px;
  }

  .w-200 {
    width: 200px;
  }
}
</style>
