<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"
                ref="tree"
                lazy
                :load="loadNode"
                @node-click="handleNodeClick"
                node-key="id"
                :default-expanded-keys="defaultExpandKeys"
                :current-node-key="defaultActive"
                highlight-current
              />
            </div>
          </div>
        </el-col>
        <el-col :span="20" :xs="24">
          <div class="from_table">
            <el-form
              :model="queryParams"
              ref="queryForm"
              :inline="true"
              v-show="showSearch"
            >
              <el-form-item label="名称" prop="name">
                <el-input
                  v-model="queryParams.name"
                  placeholder="请输入名称"
                  clearable
                  size="small"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <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 label="巡检时间">
                <el-date-picker
                  v-model="daterangeCheckTime"
                  size="small"
                  style="width: 240px"
                  value-format="yyyy-MM-dd"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                ></el-date-picker>
              </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:house:add']"
                  >新增</el-button
                >
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="revise"
                  size="mini"
                  :disabled="single"
                  @click="handleUpdate"
                  v-hasPermi="['taicangpop:house:edit']"
                  >修改</el-button
                >
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="remove"
                  size="mini"
                  :disabled="multiple"
                  @click="handleDelete"
                  v-hasPermi="['taicangpop:house:remove']"
                  >删除</el-button
                >
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="export"
                  size="mini"
                  :loading="exportLoading"
                  @click="handleExport"
                  v-hasPermi="['taicangpop:house:export']"
                  >导出</el-button
                >
              </el-col>
              <right-toolbar
                :showSearch.sync="showSearch"
                @queryTable="getList"
              ></right-toolbar>
            </el-row>

            <el-table
              v-loading="loading"
              :data="houseList"
              @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="name" />

              <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"
                prop="checkTime"
                width="180"
              >
                <template slot-scope="scope">
                  <span>{{
                    parseTime(scope.row.checkTime, "{y}-{m}-{d}")
                  }}</span>
                </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:house:edit']"
                    >修改</el-button
                  >
                  <el-button
                    class="table_icon_text"
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row)"
                    v-hasPermi="['taicangpop:house: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-dialog
              :title="title"
              :visible.sync="open"
              width="500px"
              append-to-body
              :close-on-click-modal="false"
              :destroy-on-close="true"
            >
              <el-form
                ref="form"
                :model="form"
                :rules="rules"
                label-width="auto"
                class="data_container"
              >
                <el-form-item label="名称" prop="name">
                  <el-input v-model="form.name" placeholder="请输入名称" />
                </el-form-item>
                <el-form-item label="归属部门" prop="deptId">
                  <treeselect
                    v-model="form.deptId"
                    :options="deptOptions"
                    :show-count="true"
                    placeholder="请选择归属部门"
                    @select="depidChange"
                  />
                </el-form-item>
                <el-form-item label="所属楼栋" prop="buildingId">
                  <el-select v-model="form.buildingId" placeholder="请选择楼幢">
                    <el-option
                      v-for="item in louList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="户主" v-if="xiu">
                  <el-select v-model="form.holderId" placeholder="请选择户主">
                    <el-option
                      v-for="item in huzhuList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.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="checkTime">
                  <el-date-picker
                    clearable
                    size="small"
                    v-model="form.checkTime"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="选择巡检时间"
                  >
                  </el-date-picker>
                </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.parentname
                }}</el-descriptions-item>
                <el-descriptions-item label="苑名称">{{
                  form.deptname
                }}</el-descriptions-item>
                <el-descriptions-item label="楼名称">{{
                  form.buildingname
                }}</el-descriptions-item>
                <el-descriptions-item label="室名称">{{
                  form.name
                }}</el-descriptions-item>
                <!-- <el-descriptions-item label="户主">
                  {{
                  form.holdername
                }}
                </el-descriptions-item> -->
                <el-descriptions-item label="类型">{{
                  form.type == 1 ? "户籍" : "流动"
                }}</el-descriptions-item>
                <el-descriptions-item label="分色">{{
                  form.colorname
                }}</el-descriptions-item>
                <el-descriptions-item label="巡检事件">{{
                  form.checkTime
                }}</el-descriptions-item>
                <el-descriptions-item label="备注">{{
                  form.remark
                }}</el-descriptions-item>
              </el-descriptions>
            </el-dialog>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import {
  listHouse,
  getHouse,
  delHouse,
  addHouse,
  updateHouse,
  exportHouse,
} from "@/api/taicangpop/house";
import { listPerson } from "@/api/taicangpop/person";
import { treeselect, listDept } from "@/api/system/dept";
import { listBuilding } from "@/api/taicangpop/building";

import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "House",
  dicts: ["b_color_type"],
  components: { Treeselect },
  data() {
    return {
      infoBoole: false,
      value: "",
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 住户管理表格数据
      houseList: [],
      // 部门名称
      deptName: undefined,
      // 部门树选项
      deptOptions: undefined,
      defaultProps: {
        children: "children",
        label: "label",
        isLeaf: "leaf",
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //详情弹出层
      infoOpen: false,
      // 部门权限id时间范围
      daterangeCheckTime: [],
      xiu: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        color: null,
        checkTime: null,
        deptId: undefined,
        buildingId: undefined,
      },
      defaultExpandKeys: [],
      defaultActive: "",
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
        color: [{ required: true, message: "分色不能为空", trigger: "change" }],
        checkTime: [
          { required: true, message: "巡检时间不能为空", trigger: "blur" },
        ],
      },
      louList: [],
      huzhuList: [],
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    // this.getTreeselect();
    // this.getList();
  },
  methods: {
    /**
     * 部门发生变化
     */
    getId(e) {
      //   console.log(e, "aaaaalllll");
    },
    depidChange(node, instanceId) {
      //   console.log(node, "选中");
      if (!node.children) {
        let parmar = {
          deptId: node.id,
        };
        listBuilding(parmar).then((res) => {
          this.louList = res.rows;
        });
      } else {
        this.louList = [];

        this.form.deptId = undefined;
      }
    },

    /** 查询部门下拉树结构 */
    getTreeselect(node, resolve) {
      if (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;
          });
          this.defaultExpandKeys.push(datas[0].id);
          return resolve(datas);
        });
      }
    },
    loadNode(node, resolve) {
      this.defaultExpandKeys = [];
      this.defaultActive = "";
      if (node.level == 0) {
        this.getTreeselect(node, resolve);
      }
      if (node.level > 0 && node.level < 5) {
        let queryParam = {
          parentId: node.data.id,
        };
        this.reqListDept(queryParam, resolve);
      }
      // 5级子节点根据id获取接口数据
      else if (node.level == 5) {
        let queryParam = {
          deptId: node.data.id,
        };
        this.reqListBuilding(queryParam, resolve);
      } else {
        return resolve([]); // 加上这个，防止在该节点没有子节点时一直转圈的问题发生。
      }
    },
    reqListDept(queryParam, resolve) {
      listDept(queryParam).then((res) => {
        let datas = res.data;
        datas.forEach((item) => {
          item.children = item.children;
          item.label = item.deptName;
          item.id = item.deptId;
          item.parentId = item.parentId;
        });
        // 动态展开第一级
        this.defaultExpandKeys.push(datas[0].deptId);
        return resolve(datas);
      });
    },
    // 请求楼栋表
    reqListBuilding(queryParam, resolve) {
      listBuilding(queryParam).then((res) => {
        let datas = res.rows;
        datas.forEach((item) => {
          item.children = item.children;
          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,
          buildingId: datas[0].id,
          deptId: datas[0].parentId,
        };
        this.getList();
        return resolve(datas);
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data, node) {
      if (node.level == 5) {
        let deptId = //默认请求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();
      } //
    },
    /** 查询住户管理列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCheckTime && "" != this.daterangeCheckTime) {
        this.queryParams.params["beginCheckTime"] = this.daterangeCheckTime[0];
        this.queryParams.params["endCheckTime"] = this.daterangeCheckTime[1];
      }
      listHouse(this.queryParams).then((response) => {
        this.houseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        buildingId: null,
        color: null,
        checkTime: null,
        holderId: 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.daterangeCheckTime = [];
      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.xiu = false;
      this.title = "添加住户管理";
    },
    /**查看详情 */
    handleInfo(row) {
      this.reset();
      const id = row.id;
      getHouse(id).then((response) => {
        this.form = response.data;
        this.infoOpen = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row, text) {
      this.reset();
      const id = row.id || this.ids;
      getHouse(id).then((response) => {
        this.form = response.data;
        // 字典回显
        let Data = {
          deptId: this.form.deptId,
        };
        listBuilding(Data).then((res) => {
          this.louList = res.rows;
        });
        let params = {
          buildingId: this.form.buildingId,
          deptId: this.form.deptId,
          houseId: this.form.id,
        };
        listPerson(params).then((res) => {
          this.huzhuList = res.rows;
          // console.log("户主", res);
          this.open = true;
        });
        this.title = "修改住户管理";
        // 显示可修改户主
        this.xiu = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateHouse(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.userId = JSON.parse(
              sessionStorage.getItem("USER_INFO")
            ).userId;
            addHouse(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 delHouse(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$modal
        .confirm("是否确认导出所有住户管理数据项？")
        .then(() => {
          this.exportLoading = true;
          return exportHouse(queryParams);
        })
        .then((response) => {
          this.$download.name(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
  },
};
</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>
<style lang="scss" scoped>
::v-deep .el-descriptions-row th {
  text-align: center !important;
  width: 130px !important;
}
::v-deep .textData {
  padding-bottom: 10px;
}
</style>
