<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="组织名称" prop="parentId">
        <treeselect
          :normalizer="normalizer3"
          :options="List2"
          placeholder="请选择所属组织"
          v-model="queryParams.id"
          style="width: 300px"
        />
      </el-form-item>

      <!-- <el-input
          v-model="queryParams.parentId"
          placeholder="请输入组织名称"
          clearable
          @keyup.enter.native="handleQuery"
        /> -->

      <el-form-item label="区域名称" prop="">
        <treeselect
          :normalizer="normalizer4"
          :options="areaList"
          placeholder="请选择所属区域"
          v-model="queryParams.areaId"
          style="width: 300px"
        />
      </el-form-item>
      <el-form-item label="组织地址" prop="">
        <el-input
          v-model="queryParams.organizeAddress"
          placeholder="请输入组织地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系人" prop="">
        <el-input
          v-model="queryParams.contacts"
          placeholder="请输入联系人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入联系电话"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button 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="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:area:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
          >展开/折叠</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:area:export']"
          >导出</el-button
        >
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="List"
      style="width: 100%; margin-bottom: 20px"
      row-key="id"
      border
      :default-expand-all="isExpandAll"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column label="组织名称" align="center" prop="organizeName" />
      <el-table-column label="所属区域" align="center" prop="areaName" />
      <el-table-column label="组织地址" align="center" prop="organizeAddress" />
      <el-table-column label="联系人" align="center" prop="contacts" />
      <el-table-column label="联系电话" align="center" prop="phone" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:area:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleAdd2(scope.row)"
            v-hasPermi="['system:area:add']"
            >新增</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:area:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改区域管理对话框 -->

    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <!-- <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="所属上级区域" prop="areaId">
          <treeselect
            :normalizer="normalizer"
            :options="areaList"
            placeholder="请选择所属上级区域"
            v-model="form.areaId"
          />
        </el-form-item>

        <el-form-item label="区域名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入区域名称" />
        </el-form-item>
        <el-form-item label="区域编码" prop="code">
          <el-input v-model.number="form.code" placeholder="请输入区域编码" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model.number="form.sort" placeholder="请输入排序" />
        </el-form-item>
      </el-form> -->

      <el-form-item label="所属上级组织" prop="parentId" v-if="form.id != 1">
        <treeselect
          :normalizer="normalizer2"
          :options="List"
          placeholder="请选择所属组织"
          v-model="form.parentId"
        />
      </el-form-item>

      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="所属区域" prop="areaId">
          <treeselect
            :normalizer="normalizer"
            :options="areaList"
            placeholder="请选择所属区域"
            v-model="form.areaId"
          />
        </el-form-item>

        <el-form-item label="组织名称" prop="organizeName">
          <el-input v-model="form.organizeName" placeholder="请输入组织名称" />
        </el-form-item>
        <el-form-item label="组织地址" prop="organizeAddress">
          <el-input
            v-model="form.organizeAddress"
            placeholder="请输入组织地址"
          />
        </el-form-item>
        <el-form-item label="联系人" prop="contacts">
          <el-input v-model="form.contacts" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="联系人电话" prop="phone">
          <el-input
            v-model="form.phone"
            maxlength="11"
            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 { list, getinfo, delinfo, add, edit } from "@/api/system/info.js";
import { listArea } from "@/api/system/area.js";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  components: { Treeselect },
  name: "areas",
  data() {
    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile =
        /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;

      if (regMobile.test(value)) {
        return cb();
      }

      cb(new Error("请输入合法的手机号"));
    };
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 区域管理表格数据
      List: [],
      List2: [],
      areaList: [],
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        parentId: undefined,
        areaId: undefined,
        organizeName: "",
        organizeAddress: "",
        phone: "",
        contacts: "",
        id: undefined,
      },
      // 表单参数
      form: {
        id: undefined,
        parentId: undefined,
        areaId: undefined,
        organizeName: "",
        organizeAddress: "",
        phone: "",
        contacts: "",
      },
      // 表单校验
      rules: {
        phone: [
          {
            required: true,
            validator: checkMobile,
            trigger: "blur",
            message: "请输入正确的手机号",
          },
        ],
        code: [
          { required: true, message: "区域编码不能为空" },
          { type: "number", message: "区域编码必须为数字值", trigger: "blur" },
        ],
        areaId: [
          { required: true, message: "请选择所属上级区域", trigger: "blur" },
        ],
        parentId: [
          { required: true, message: "请选择所属上级区域", trigger: "blur" },
        ],
        organizeName: [
          { required: true, message: "请输入组织名称", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 转换部门数据结构 */
    normalizer4(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        areaId: node.id,
        label: node.name,
        children: node.children,
      };
    },

    normalizer3(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.organizeName,
        children: node.children,
      };
    },

    normalizer2(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        areaId: node.id,
        label: node.organizeName,
        children: node.children,
      };
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        areaId: node.areaId,
        label: node.name,
        children: node.children,
      };
    },
    /** 查询区域管理列表 */
    getList() {
      listArea(this.queryParams).then((response) => {
        this.areaList = this.handleTree(response.data);
      });
      this.loading = true;
      list(this.queryParams).then((response) => {
        this.List = this.handleTree(response.data);
        this.List2 = this.List;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        parentId: undefined,
        areaId: undefined,
        organizeName: "",
        organizeAddress: "",
        phone: "",
        contacts: "",
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      list(this.queryParams).then((response) => {
        this.List = this.handleTree(response.data);
        this.loading = false;
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        parentId: undefined,
        areaId: undefined,
        organizeName: "",
        organizeAddress: "",
        phone: "",
        contacts: "",
        id: undefined,
      };
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 项目新增按钮操作 */
    handleAdd2(row) {
      this.reset();
      this.form.areaId = row.areaId;
      this.form.parentId = row.id;
      this.open = true;
      this.title = "添加区域管理";
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      list(this.queryParams).then((response) => {
        this.List = this.handleTree(response.data);
      });
      this.reset();
      listArea(this.queryParams).then((response) => {
        this.areaList = this.handleTree(response.data);
      });
      this.open = true;
      this.title = "添加区域管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getinfo(id).then((response) => {
        if (response.data.phone == 0) {
          response.data.phone = "";
        }
        this.form = response.data;
        this.open = true;
        this.title = "修改区域管理";
      });
    },

    /** 提交按钮 */
    submitForm() {
      if (this.form.phone == "" || this.form.phone.toString().length == 11) {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            if (this.form.id != null) {
              edit(this.form).then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              add(this.form).then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      } else {
        this.$message.error("请输入正确的手机号码");
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm("是否确认删除？")
        .then(function () {
          return delinfo(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/area/export",
        {
          ...this.queryParams,
        },
        `area_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style lang='scss'>
</style>