<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          :loading="syncLoading"
          @click.once="handleSync"
          v-hasPermi="['system:jlDept:syncToDept']"
        >同步</el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="jlDeptList"
              ref="table"
              row-key="id"
              border
              lazy
              :default-expand-all="false"
              :load="load"
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="行政区名" align="left" prop="name" />
      <el-table-column label="行政区编码" align="center" prop="code" />
      <el-table-column label="等级" align="center" prop="level" />
      <!--<el-table-column label="上级行政区" align="center" prop="parentName" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd(scope.row)"
            v-hasPermi="['system:jlDept:add']"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:jlDept:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:jlDept: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 v-dialog-drag :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <!--<el-form-item label="行政区编码" prop="code">-->
          <!--<el-input v-model="form.code" placeholder="请输入行政区编码" />-->
        <!--</el-form-item>-->
        <el-form-item label="行政区名" prop="name" >
          <el-input v-model="form.name" placeholder="请输入行政区名" />
        </el-form-item>
        <el-form-item label="上级行政区" prop="parentId">
          <el-input v-model="form.parentName" :disabled="true" 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>
  </div>
</template>

<script>
import {listJlDept, getJlDept, delJlDept, addJlDept, updateJlDept, syncJlDept} from "@/api/system/jlDept";
import { CountryDeptList } from "@/api/system/region";
export default {
  name: "JlDept",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 同步按钮进度
      syncLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 吉林地区管理表格数据
      jlDeptList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        // pageNum: 1,
        // pageSize: 10,
        // code: null,
        // name: null,
        // parentId: null,
        // level: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: { required: true, message: "行政区名不能为空", trigger: "blur" },
      },
      maxLevel:5,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询吉林地区管理列表 */
    getList() {
      this.loading = true;
      CountryDeptList(this.queryParams).then(response => {
        this.jlDeptList = this.handleTree(response.data, "parentId", "id");
        this.jlDeptList.forEach(node => {
          node.hasChildren = true;
        })
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        name: null,
        parentId: null,
        level: 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(row) {
      this.reset();
      getJlDept(row.id).then(response => {
        this.form.parentId=response.data.id;
        this.form.parentName=response.data.parentName;
        this.open = true;
        this.title = "添加地区管理";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getJlDept(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改地区管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateJlDept(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              // this.getList();
              this.updateTreeData(this.form);
            });
          } else {
            addJlDept(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              // this.getList();
              this.updateTreeData(this.form);
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除"' + row.name + '"的数据项？').then(function() {
        return delJlDept(ids);
      }).then(() => {
        this.getList();

      }).then(() => {
        // this.getList();
        this.updateTreeData(row);//删除后更新
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
   async load(tree, treeNode, resolve) {
      let {code, data} = await CountryDeptList({
        parentId: tree.id,
      });
      if (code !== 200) {
        return;
      }
      data.forEach(item => {
        item.hasChildren = item.level < this.maxLevel;
      });
      resolve(data);
    },
    async updateTreeData(node) {
      let {parentId} = node;
      let tableStates = this.$refs.table.store.states;
      let parentTreeNode = tableStates['treeData'][parentId];
      if (parentTreeNode && parentTreeNode.loaded) {
        this.loading = true;
        let {data, code} = await CountryDeptList({
          parentId: parentId
        });
        data.forEach(item => {
          item.hasChildren = item.level < this.maxLevel;
        });
        if (code !== 200) {
          return;
        }
        this.$set(tableStates['lazyTreeNodeMap'],parentId, data);
        this.loading = false;
      }
    },
    handleSync(){
      this.syncLoading = true
      syncJlDept().finally(()=>{
        this.syncLoading =false
      })
    }
  }
};
</script>
