<template>
  <div>
    <el-row>
      <el-col :span="4" style="padding: 10px">
        <div class="dept-left-input">
          <el-input
            v-model="keyword"
            clearable
            placeholder="请输入关键词"
            prefix-icon="el-icon-search"
            size="small"
          />
        </div>
        <div style="margin-top: 10px; font-size: 14px">
          <el-tree
            ref="tree"
            :data="treeMenus"
            :props="defaultProps"
            node-key="id"
            highlight-current
            :show-checkbox="false"
            :expand-on-click-node="true"
            :default-expand-all="true"
            accordion
            :filter-node-method="filterNode"
            @node-click="handleNodeClick"
          >
          </el-tree>
        </div>
      </el-col>
      <el-form
        :inline="true"
        :model="query"
        size="mini"
        class="demo-form-inline"
        style="float: left; margin-top: 10px"
      >
        <el-form-item label="筛选数据">
          <el-input v-model="query.search"></el-input>
        </el-form-item>
        <el-form-item>
          <!-- <el-button icon="el-icon-search" type="primary" @click="queryData">查询</el-button> -->
          <el-button
            icon="el-icon-circle-plus-outline"
            type="primary"
            @click="openAdd"
            >新增</el-button
          >
        </el-form-item>
      </el-form>
      <el-col :span="20" style="padding: 10px">
        <el-table :data="tables" border>
          <el-table-column
            align="center"
            type="index"
            label="序号"
            width="60"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="deptsName"
            label="名称"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="parentNodeId"
            label="父节点"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="updateTime"
            label="创建时间"
            width="180"
          >
            <template slot-scope="scope">{{
              scope.row.updateTime | formatDate
            }}</template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="area"
            label="区域"
          ></el-table-column>
          <el-table-column align="center" prop="customDept" label="部门类型">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.customDept === 0" type="primary"
                >非自定义</el-tag
              >
              <el-tag v-if="scope.row.customDept === 1" type="success"
                >web自定义</el-tag
              >
              <el-tag v-if="scope.row.customDept === 2" type="warning"
                >APP自定义</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="deptsDescription"
            label="描述"
          ></el-table-column>
          <el-table-column align="center" prop="state" label="状态">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.state === 0" type="primary">注销</el-tag>
              <el-tag v-if="scope.row.state === 1" type="success">正常</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="300">
            <template slot-scope="scope">
              <el-button
                @click="handlePermission(scope.row)"
                size="mini"
                type="primary"
                >绑定监测点</el-button
              >
              <el-button
                type="primary"
                @click="handleEditid(scope.row)"
                size="mini"
                >修改</el-button
              >
              <el-button
                type="danger"
                @click="handleDelete(scope.row)"
                size="mini"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <!-- 新增或修改参数配置对话框 -->
      <el-dialog
        :close-on-click-modal="false"
        :title="dialog.title"
        :visible.sync="dialog.visible"
        width="500px"
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="部门名称" prop="deptsName">
                <el-input
                  v-model="form.deptsName"
                  placeholder="请输入昵称"
                  style="width: 260px"
                />
              </el-form-item>
              <el-form-item label="父节点" prop="parentNodeId">
                <el-select
                  v-model="form.parentNodeId"
                  placeholder="请选择父节点"
                  style="width: 260px"
                >
                  <el-option
                    v-for="item in father"
                    :label="item.deptsName"
                    :value="item.parentNodeId"
                    :key="item.index"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="区域" prop="area">
                <el-select
                  v-model="form.area"
                  placeholder="请选择区域"
                  style="width: 260px"
                >
                  <el-option
                    v-for="item in city"
                    :label="item.dicName"
                    :value="item.area"
                    :key="item.index"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="部门类型" prop="customDept">
                <el-select
                  v-model="form.customDept"
                  placeholder="请选择部门类型"
                  style="width: 260px"
                >
                  <el-option
                    v-for="item in dept"
                    :label="item.label"
                    :value="item.customDept"
                    :key="item.index"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                label="部门描述"
                prop="deptsDescription"
                style="width: 360px"
              >
                <el-input
                  type="textarea"
                  v-model="form.deptsDescription"
                  placeholder="请输入中文描述"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item style="margin-left: 10%">
                <el-button
                  text-align="center"
                  type="success"
                  @click="handleSubmit"
                  >提交</el-button
                >
                <el-button
                  text-align="center"
                  type="primary"
                  @click="dialog.visible = false"
                  >取 消</el-button
                >
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-dialog>

      <el-pagination
        style="float: right; margin-top: 10px"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.current"
        :page-sizes="[10, 20, 50]"
        :page-size="page.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
      >
      </el-pagination>
    </el-row>
  </div>
</template>
<script>
import {
  tree,
  list,
  quyu,
  depts,
  datalist,
  add,
  del,
  panduan,
  updated,
  getById,
} from "@/api/admin/dept";
export default {
  data() {
    return {
      /**树结构 */
      dialog: {
        title: "",
        visible: false,
      },
      treeMenus: [],
      queryParams: {},
      query: {
        search: "",
      },
      list: [],
      form: {},
      page: {
        size: 10,
        current: 1,
        total: 0,
      },
      city: [],
      father: [],
      dept: [
        { label: "非自定义", customDept: 0 },
        { label: "web自定义", customDept: 1 },
        { label: "app自定义", customDept: 2 },
      ],
      /**树配置选项 */
      defaultProps: {
        children: "children",
        label: "label",
      },
      /**搜索关键字 */
      keyword: "",
      rules: {
        deptName: [
          { required: true, message: "部门名称不能为空", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    // 实时监听表格
    tables: function () {
      const search = this.query.search;
      if (search) {
        return this.list.filter((dataNews) => {
          return Object.keys(dataNews).some((key) => {
            return String(dataNews[key]).toLowerCase().indexOf(search) > -1;
          });
        });
      }
      return this.list;
    },
  },
  filters: {
    formatDate: function (value) {
      //这里的 value 就是需要过滤的数据
      var date = new Date(value);
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      var hours = date.getHours();
      var minutes = date.getMinutes();
      var seconds = date.getSeconds();
      return (
        year +
        "-" +
        month +
        "-" +
        day +
        " " +
        hours +
        ":" +
        minutes +
        ":" +
        seconds
      );
    },
  },
  watch: {
    /**根据名称筛选树 */
    keyword(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.treedata();
  },
  mounted() {
    this.queryData();
    this.city1();
    this.fathered();
  },
  methods: {
    /**筛选节点 */
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },

    /**
     * 缩放条拖动进而改变左侧div宽度方法
     */
    bindResize() {
      /**开始坐标 */
      let startX;
      /**开始宽度 */
      let startWidth = getScalableDivWidth();

      document
        .querySelector("#drag-dept")
        .addEventListener("mousedown", startDrag);

      function startDrag(e) {
        startX = e.clientX;
        startWidth = getScalableDivWidth();

        document.documentElement.addEventListener("mousemove", onDrag);
        document.documentElement.addEventListener("mouseup", stopDrag);
      }

      function onDrag(e) {
        let newWidth = startWidth + e.clientX - startX;
        document.querySelector("#drag-dept-left").style.width = newWidth + "px";
      }

      function stopDrag() {
        document.documentElement.removeEventListener("mousemove", onDrag);
        document.documentElement.removeEventListener("mouseup", stopDrag);
      }

      /**获取宽度 */
      function getScalableDivWidth() {
        return parseInt(
          window.getComputedStyle(document.querySelector("#drag-dept-left"))
            .width,
          10
        );
      }
    },
    /**
     * 获取树结构
     */
    treedata() {
      tree().then((response) => {
        if (response.code === "A0000") {
          this.treeMenus = response.data;
        }
      });
    },
    queryData() {
      this.list = {};
      this.queryParams.page = this.page.current;
      this.queryParams.limit = this.page.size;
      list(this.queryParams).then((response) => {
        if (response.code === "A0000") {
          this.list = response.data;
          this.page.total = response.total;
        }
      });
    },
    city1() {
      quyu().then((response) => {
        if (response.code === "A0000") {
          var arr = [];
          for (var i = 0; i < response.data.length; i++) {
            let p = {
              area: response.data[i].dicIndex,
              dicName: response.data[i].dicName,
            };
            arr.push(p);
          }
          this.city = arr;
        }
      });
    },
    // fathered(){
    //   depts().then(response => {
    //     if(response.code==='A0000'){
    //       var arr = []
    //       for(var i=0;i<response.data.length;i++){
    //          let p = {
    //            parentNodeId:response.data[i].deptsIndex,
    //            deptsName:response.data[i].deptsName
    //          }
    //        arr.push(p)
    //       }
    //       this.father = arr
    //      }
    //   })
    // },
    openAdd() {
      this.resetForm();
      this.dialog = {
        title: "新增部门",
        visible: true,
        //flag: 0
      };
    },
    handleEditid(row) {
      this.resetForm();
      this.dialog = {
        title: "修改部门",
        visible: true,
        //flag: 0
      };
      let data = {
        deptsIndex: row.deptsIndex,
      };
      getById(data).then((response) => {
        if (response.code === "A0000") {
          console.log(response.data);
          this.form = response.data;
        }
      });
    },
    handleSubmit: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const id = this.form.deptsIndex;
          if (id !== undefined) {
            let p = {
              area: this.form.area,
              customDept: this.form.customDept,
              deptsName: this.form.deptsName,
              deptId: this.form.deptsIndex,
              deptsDescription: this.form.deptsDescription,
              parentNodeId: this.form.parentNodeId,
            };
            updated(p).then((response) => {
              if (response.code === "A0000") {
                this.$message.success("修改成功");
                this.dialog.visible = false;
                this.queryData();
                this.treedata();
              }
            });
          } else {
            let p = {
              area: this.form.area,
              customDept: this.form.customDept,
              deptsName: this.form.deptsName,
              deptsDescription: this.form.deptsDescription,
              parentNodeId: this.form.parentNodeId,
            };
            add(p).then((response) => {
              if (response.code === "A0000") {
                this.$message.success("添加部门成功");
                this.dialog.visible = false;
                this.queryData();
                this.treedata();
              }
            });
            // this.gkeyadd()
          }
        }
      });
    },
    // 表单重置
    resetForm() {
      this.form = {};
      if (this.$refs["form"]) {
        this.$refs["form"].resetFields();
      }
    },
    records() {},
    handleSizeChange(val) {
      this.page.size = val;
      if (this.queryParams.deptsIndex) {
        this.queryDatalist();
      } else {
        this.queryData();
      }
    },
    handleCurrentChange(val) {
      this.page.current = val;
      if (this.queryParams.deptsIndex) {
        this.queryDatalist();
      } else {
        this.queryData();
      }
    },
    handleNodeClick(data, node) {
      this.queryParams.deptsIndex = data.deptsIndex;
      console.log(this.deptsIndex);
      this.queryDatalist();
    },
    queryDatalist() {
      this.queryParams.page = this.page.current;
      this.queryParams.limit = this.page.size;
      datalist(this.queryParams).then((response) => {
        if (response.code === "A0000") {
          this.list = response.data;
          this.page.total = response.total;
        }
      });
    },
    // 删除
    async handleDelete(row) {
      // console.log(row)
      //  let data={
      // 'deptIndex':row.deptsIndex
      // }
      // let response = null
      //response = await panduan(data)
      //console.log(response)
      //if(response.data===1){
      this.$confirm("此操作将永久删除该部门, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let data = {
            deptIndex: row.deptsIndex,
          };
          del(data).then((response) => {
            this.$message({ type: "success", message: "部门删除成功" });
          });
          this.queryData();
          this.treedata();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
      //  }
      //   }else{
      // this.$confirm("该部门未绑定了其他资源，此操作将永久删除该部门, 是否继续?", "提示", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   type: "warning",
      // }).then(() => {
      //    let data={
      //   'deptIndex':row.deptsIndex
      //   }
      //   del(data).then(response => {
      //      this.$message({type: "success",message: "部门删除成功",});
      //   })
      //  this.queryData()
      //  }).catch(() => {
      //       this.$message({
      //         type: "info",
      //         message: "已取消删除",
      //       });
      //     });
      //   }
    },
  },
};
</script>
<style>
</style>
