<template>
  <div class="app-container">
    <div class="table_container">
      <el-row :gutter="20">
        <!--部门数据-->
        <el-col :span="4" :xs="24">
          <div class="from_tree">
            <div class="head-container">
              <el-input
                v-model="deptName"
                placeholder="请输入部门名称"
                clearable
                size="small"
                prefix-icon="el-icon-search"
                style="margin-bottom: 20px"
              />
            </div>
            <div class="head-container">
              <el-tree
                :props="defaultProps"
                :expand-on-click-node="false"
                :filter-node-method="filterNode"
                :load="loadNode"
                lazy
                ref="tree"
                node-key="id"
                :default-expanded-keys="defaultExpandKeys"
                @node-click="handleNodeClick"
                @node-expand="handleNodeExpand"
                @node-collapse="handleNodeCollapse"
                :current-node-key="defaultActive"
                highlight-current
              />
            </div>
          </div>
        </el-col>
        <!--用户数据-->
        <el-col :span="20" :xs="24">
          <el-form
            :model="queryParams"
            ref="queryForm"
            :inline="true"
            v-show="showSearch"
            label-width="68px"
          >
            <el-form-item label="分色" prop="color">
              <el-select
                v-model="queryParams.color"
                placeholder="请选择分色"
                clearable
                size="small"
              >
                <el-option
                  v-for="dict in dict.type.b_color_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                class="search_btn"
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="handleQuery"
                >搜索</el-button
              >
              <el-button
                class="agin_btn"
                icon="el-icon-refresh"
                size="mini"
                @click="resetQuery"
                >重置
              </el-button>
            </el-form-item>
          </el-form>

          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="new"
                size="mini"
                @click="handleAdd"
                v-hasPermi="['taicangpop:check:add']"
                >新增</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="revise"
                size="mini"
                :disabled="single"
                @click="handleUpdate"
                v-hasPermi="['taicangpop:check:edit']"
                >修改</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="remove"
                size="mini"
                :disabled="multiple"
                @click="handleDelete"
                v-hasPermi="['taicangpop:check:remove']"
                >删除</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="export"
                size="mini"
                :loading="exportLoading"
                @click="handleExport"
                v-hasPermi="['taicangpop:check:export']"
                >导出</el-button
              >
            </el-col>
            <right-toolbar
              :showSearch.sync="showSearch"
              @queryTable="getList"
            ></right-toolbar>
          </el-row>

          <el-table
            v-loading="loading"
            :data="checkList"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="组团名称" align="center" prop="deptname" />
            <el-table-column
              label="楼栋名称"
              align="center"
              prop="buildingname"
            />
            <el-table-column label="住户名称" align="center" prop="housename" />
            <!-- <el-table-column label="网格员id" align="center" prop="managerId" /> -->
            <el-table-column label="分色" align="center" prop="color">
              <template slot-scope="scope">
                <dict-tag
                  :options="dict.type.b_color_type"
                  :value="scope.row.color"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
              width="200"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-zoom-in"
                  @click="handleInfo(scope.row)"
                  >查看</el-button
                >
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['taicangpop:check:edit']"
                  >修改</el-button
                >
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['taicangpop:check:remove']"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </el-col>
      </el-row>

      <!-- 添加或修改巡检记录管理对话框 -->
      <el-dialog
        :title="title"
        :visible.sync="open"
        width="500px"
        append-to-body
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <!-- <el-form-item label="网格员id" prop="managerId">
            <el-input v-model="form.managerId" placeholder="请输入网格员id" />
          </el-form-item> -->
          <el-form-item label="组团" prop="deptId">
            <treeselect
              v-model="form.deptId"
              :options="deptOptions"
              :show-count="true"
              placeholder="请选择归属组团"
              @select="treeSelect"
            />
          </el-form-item>
          <el-form-item label="楼栋" prop="buildingId">
            <el-select
              v-model="form.buildingId"
              placeholder="请输入楼栋"
              filterable
              @change="selectBuildingChange"
            >
              <el-option
                v-for="dict in buildingList"
                :key="parseInt(dict.id)"
                :label="dict.name"
                :value="parseInt(dict.id)"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="住户" prop="houseId">
            <el-select
              v-model="form.houseId"
              placeholder="请输入住户"
              filterable
            >
              <el-option
                v-for="dict in houselist"
                :key="parseInt(dict.id)"
                :label="dict.name"
                :value="parseInt(dict.id)"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="分色" prop="color">
            <el-select v-model="form.color" placeholder="请选择分色">
              <el-option
                v-for="dict in dict.type.b_color_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="form.remark"
              type="textarea"
              placeholder="请输入备注"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
      <el-dialog
        title="详情信息"
        :visible.sync="infoOpen"
        width="500px"
        append-to-body
        :close-on-click-modal="false"
        :destroy-on-close="true"
      >
        <el-descriptions title="巡检详情" :column="1" border class="textData">
          <el-descriptions-item label="苑名称">{{
            form.deptname
          }}</el-descriptions-item>
          <el-descriptions-item label="楼名称">{{
            form.buildingname
          }}</el-descriptions-item>
          <el-descriptions-item label="室名称">{{
            form.housename
          }}</el-descriptions-item>
          <el-descriptions-item label="备注">{{
            form.remark
          }}</el-descriptions-item>
        </el-descriptions>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  listCheck,
  getCheck,
  delCheck,
  addCheck,
  updateCheck,
  exportCheck,
} from "@/api/taicangpop/check";
import { treeselect, getDept, listDept } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { listBuilding } from "@/api/taicangpop/building";
import { listHouse } from "@/api/taicangpop/house";

export default {
  name: "Check",
  dicts: ["b_color_type"],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 巡检记录管理表格数据
      checkList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      infoOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        managerId: null,
        color: null,
        buildingId: null,
        houseId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 部门树选项
      deptOptions: undefined,
      // 部门名称
      deptName: undefined,
      defaultProps: {
        children: "children",
        label: "label",
        isLeaf: "leaf",
      },
      //   default-expanded-keys
      defaultExpandKeys: [],
      defaultActive: "",
      buildingList: [],
      houselist: [],
      deptId: null,
      isInit: true,
    };
  },
  created() {
    // this.getList();
  },
  methods: {
    treeSelect(node, instanceId) {
      // console.log(node);
      if (!node.children) {
        this.deptId = node.id;
        let queryBuildingParams = {
          deptId: node.id,
        };
        this.getBuildingList(queryBuildingParams);
      }
    },
    /** 查询楼栋管理列表 */
    getBuildingList(queryBuildingParams) {
      listBuilding(queryBuildingParams).then((response) => {
        this.buildingList = response.rows;
      });
    },
    selectBuildingChange(val) {
      //   console.log(val);
      let queryHouseParams = {
        buildingId: val,
        deptId: this.deptId,
      };
      this.getHouseList(queryHouseParams);
    },
    /** 查询楼栋管理列表 */
    getHouseList(queryHouseParams) {
      // this.queryHouseParams
      listHouse(queryHouseParams).then((response) => {
        this.houselist = response.rows;
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect(node, resolve) {
      treeselect().then((response) => {
        this.deptOptions = response.data;
        let datas = response.data;
        datas.forEach((item) => {
          item.children = item.children;
          item.label = item.label;
          item.id = item.id;
          item.parentId = item.id;
        });
        if (this.isInit) {
          // 动态展开第一级
          this.defaultExpandKeys = [this.deptOptions[0].id];
        }
        return resolve(datas);
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点展开关闭
    handleNodeExpand() {
      this.isInit = false;
    },
    handleNodeCollapse() {
      this.isInit = false;
    },
    // 节点单击事件
    handleNodeClick(data, node) {
      this.isInit = false;
      //   console.log(data, node);
      // 苑
      if (node.level == 5) {
        //默认请求list项
        this.queryParams = {
          pageNum: 1,
          pageSize: 10,
          deptId: data.id,
        };
        this.getList();
      }
      // 栋
      else if (node.level == 6) {
        //默认请求list项
        this.queryParams = {
          pageNum: 1,
          pageSize: 10,
          deptId: data.deptId,
          buildingId: data.id,
        };
        this.getList();
      }
      // 室
      else if (node.level == 7) {
        //默认请求list项
        this.queryParams = {
          pageNum: 1,
          pageSize: 10,
          deptId: data.parentId,
          buildingId: data.buildingId,
          houseId: data.id,
        };
        this.getList();
      }
      //   this.queryParams.deptId = data.id;
      //   this.getList();
    },
    reqListDept(queryParam, resolve) {
      listDept(queryParam).then((res) => {
        let datas = res.data;
        // console.log(datas);
        datas.forEach((item) => {
          item.children = item.children;
          item.label = item.deptName;
          item.id = item.deptId;
          item.parentId = item.parentId;
        });
        if (this.isInit) {
          // 动态展开第一级
          this.defaultExpandKeys.push(datas[0].deptId);
        }

        return resolve(datas);
      });
    },
    // 请求楼栋表
    reqListBuilding(queryParam, resolve) {
      listBuilding(queryParam).then((res) => {
        let datas = res.rows;
        // console.log(datas);
        datas.forEach((item) => {
          item.children = item.children;
          item.label = item.name;
          item.id = item.id;
          item.parentId = item.deptId;
        });

        if (this.isInit) {
          // 动态展开第一级
          this.defaultExpandKeys.push(datas[0].id);
        }
        return resolve(datas);
      });
    },
    // 请求住户表
    reqListHouse(queryParam, resolve) {
      listHouse(queryParam).then((res) => {
        let datas = res.rows;
        // console.log(datas);
        datas.forEach((item) => {
          item.label = item.name;
          item.id = item.id;
          item.parentId = item.deptId;
          item.leaf = true;
        });
        this.defaultActive = res.rows[0].id;
        // console.log("默认选中项", this.defaultActive);
        //需要注意的是setCurrentKey函数必须要放到$nextTick里面，要不然tree还未渲染上，是找不到defaultActive的
        this.$nextTick(() => {
          this.$refs.tree.setCurrentKey(this.defaultActive);
        });
        //默认请求list项
        this.queryParams = {
          pageNum: 1,
          pageSize: 10,
          deptId: datas[0].parentId,
          houseId: datas[0].id,
          buildingId: datas[0].buildingId,
        };
        this.getList();
        return resolve(datas);
      });
    },
    loadNode(node, resolve) {
      this.defaultActive = "";
      this.defaultExpandKeys = [];
      if (node.level == 0) {
        // console.log("走了");
        this.getTreeselect(node, resolve);
      }
      if (node.level > 0 && node.level < 5) {
        // console.log(node.data);
        let queryParam = {
          parentId: node.data.id,
        };
        // console.log("<5", node.data);
        this.reqListDept(queryParam, resolve);
      }
      // 5级子节点根据id获取接口数据
      else if (node.level == 5) {
        let queryParam = {
          deptId: node.data.id,
        };
        // console.log("building", node);
        this.reqListBuilding(queryParam, resolve);
      }
      // 6级子节点根据id获取接口数据
      else if (node.level == 6) {
        let queryParam = {
          buildingId: node.data.id,
          deptId: node.data.parentId,
        };
        // console.log("housing", node);
        this.reqListHouse(queryParam, resolve);
      } else {
        return resolve([]); // 加上这个，防止在该节点没有子节点时一直转圈的问题发生。
      }
    },
    /** 查询巡检记录管理列表 */
    getList() {
      this.loading = true;
      listCheck(this.queryParams).then((response) => {
        this.checkList = response.rows;
        // console.log(this.checkList);
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        managerId: null,
        color: null,
        buildingId: null,
        houseId: null,
        createId: null,
        createBy: null,
        createTime: null,
        updateId: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        userId: null,
        deptId: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加巡检记录管理";
    },
    /**查看详情 */
    handleInfo(row) {
      const id = row.id;
      getCheck(id).then((response) => {
        this.form = response.data;
        this.infoOpen = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getCheck(id).then((response) => {
        this.form = response.data;
        let Data = {
          deptId: this.form.deptId,
        };
        listBuilding(Data).then((res) => {
          this.buildingList = res.rows;
        });
        let queryParam = {
          buildingId: this.form.buildingId,
          deptId: this.form.deptId,
        };
        listHouse(queryParam).then((res) => {
          this.houselist = res.rows;
          this.open = true;
        });

        this.title = "修改巡检记录管理";
        // 数据要调整
        // console.log(this.form);
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateCheck(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.userId = JSON.parse(
              sessionStorage.getItem("USER_INFO")
            ).userId;
            addCheck(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除巡检记录管理编号为"' + ids + '"的数据项？')
        .then(function () {
          return delCheck(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$modal
        .confirm("是否确认导出所有巡检记录管理数据项？")
        .then(() => {
          this.exportLoading = true;
          return exportCheck(queryParams);
        })
        .then((response) => {
          this.$download.name(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-descriptions-row th {
  text-align: center !important;
  width: 130px !important;
}
::v-deep .textData {
  padding-bottom: 10px;
}
</style>
