<template>
  <div class="dept-wrap">
    <el-card class="top-card-wrap">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
        <el-form-item label="机构名称" prop="deptName">
          <el-input v-model="queryParams.deptName" placeholder="请输入机构名称" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="机构状态" clearable>
            <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t('search')
          }}</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('reset') }}</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <!-- <el-col :span="1.5">
          <el-button type="info" plain icon="el-icon-sort" size="mini" @click="handleAdd">{{ $t('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>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </el-card>

    <el-card class="main-card">
      <el-table class="base-table" v-if="refreshTable" v-loading="loading" :data="deptList" row-key="deptId"
        :default-expand-all="isExpandAll" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column prop="deptName" label="机构名称" width="260" align="left"></el-table-column>
        <el-table-column prop="deptType" label="机构类型" width="200" align="left">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.department_type" :value="scope.row.deptType" />
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="200" align="center">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column prop="leader" label="联系人" width="200" align="left"></el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="300">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">

          <template slot-scope="scope">
            <el-button size="small" type="primary" plain style="padding: 5px" icon="el-icon-plus"
              @click="handleAdd(scope.row)" v-hasPermi="['system:dept:add']">新增机构</el-button>
            <el-button size="small" type="primary" plain style="padding: 5px" icon="el-icon-edit"
              @click="handleUpdate(scope.row)" v-hasPermi="['system:dept:edit']">编辑机构</el-button>
            <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)"
              v-hasPermi="['system:role:edit']">
              <el-button size="small" type="primary" plain style="padding: 5px"
                icon="el-icon-d-arrow-right">更多管理</el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="handleUserManage" icon="el-icon-user"
                  v-hasPermi="['system:user:edit']">用户管理</el-dropdown-item>
                <el-dropdown-item command="handleRoleManage" icon="el-icon-circle-check">角色管理</el-dropdown-item>
                <el-dropdown-item command="handleDelete" size="mini" type="text" icon="el-icon-delete"
                  v-if="scope.row.parentId != 0" v-hasPermi="['system:dept:remove']">删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加或修改机构对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
        <div style="margin-top: -55px">
          <el-divider style="margin-top: -30px"></el-divider>
          <el-form ref="form" :model="form" :rules="rules" label-width="100px">
            <el-row>
              <el-col :span="24" v-if="form.parentId !== 0 && form.parentId !== undefined">
                <el-form-item label="上级机构" prop="parentId">
                  <treeselect v-model="form.parentId" :options="deptOptions" :normalizer="normalizer" disabled
                    placeholder="选择上级机构" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="机构名称" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入机构名称" />
            </el-form-item>
            <el-form-item label="机构类型" prop="deptType">
              <el-select v-model="form.deptType" placeholder="请选择机构类型" clearable size="small" style="width: 100%"
                :disabled="this.form.deptId != null">
                <el-option v-for="option in deptTypeList" :key="option.value" :label="option.label"
                  :value="option.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="联系人" prop="leader">
              <el-input v-model="form.leader" placeholder="请输入联系人" maxlength="20" />
            </el-form-item>
            <el-form-item label="机构状态">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">
                  {{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <div class="title-wrap">系统账号
            </div>
            <el-form-item prop="userName">
              <span slot="label">
                <span class="span-box">
                  <span> 登录账号 </span>
                  <el-tooltip content="请为此机构创建一个账号名" placement="top"><i class="el-icon-warning-outline"></i>
                  </el-tooltip>
                </span>
              </span>
              <el-input v-model="form.userName" placeholder="请输入登录账号" :disabled="this.form.deptId != null" />
            </el-form-item>
            <el-form-item label="密码" prop="password" v-if="this.form.deptId == null">
              <el-input v-model="form.password" placeholder="请输入密码" type="password" show-password />
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword" v-if="this.form.deptId == null">
              <el-input v-model="form.confirmPassword" placeholder="请输入密码" type="password" show-password />
            </el-form-item>
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11"
                :disabled="this.form.deptId != null" />
            </el-form-item>
            <el-form-item label="首页配置" prop="menuId">
              <el-cascader :options="deptMenu" v-model="menuIds" clearable style="width: 100%"></el-cascader>
            </el-form-item>
            <el-form-item label="设备限制" prop="devmun" v-if="this.form.deptId !== 100">
              <el-input v-model="form.devmun" placeholder="请输入设备限制数量" :disabled="this.userId !== 1" />
            </el-form-item>
          </el-form>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { listDept, getDept, delDept, addDept, updateDept, listDeptExcludeChild, getDeptType } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { listMenuF } from "../../../api/system/menu";

export default {
  name: "Dept",
  dicts: ['sys_normal_disable', 'department_type'],
  components: { Treeselect },
  data() {
    const equalToPassword = (rule, value, callback) => {
      if (this.form.password !== value) {
        callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    };
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      deptList: [],
      // 机构树选项
      deptOptions: [],
      deptType: '',
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      deptTypeList: [],
      deptMenu: [],
      // 查询参数
      queryParams: {
        deptName: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: "上级机构不能为空", trigger: "blur" }
        ],
        deptName: [
          { required: true, message: "机构名称不能为空", trigger: "blur" }
        ],
        deptType: [
          { required: true, message: "机构类型不能为空", trigger: "blur" }
        ],
        leader: [
          { required: true, message: "联系人不能为空", trigger: "blur" }
        ],
        userName: [
          { required: true, message: "登陆账号不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' },
          {
            trigger: 'blur',
            validator: (rule, value, callback) => {
              var passwordreg = /(?![A-Z]*$)(?![a-z]*$)(?![0-9]*$)(?![^a-zA-Z0-9]*$)/
              if (!passwordreg.test(value)) {
                callback(new Error('密码须由大写,小写字母,数字,特殊符中的2种及以上类型组成'))
              }
              else {
                callback()
              }
            }
          },
        ],
        confirmPassword: [
          {
            required: true,
            trigger: 'blur',
            message: '请再次输入您的密码',
          },
          {
            required: true,
            validator: equalToPassword,
            trigger: 'blur',
          },
        ],
        phone: [
          { required: true, message: "联系电话不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      },
      //菜单id数组
      menuIds: [],
      userId: null,
    };
  },
  created() {
    this.getList();
    this.getListMenu()
  },
  methods: {
    /** 查询菜单列表 */
    getListMenu() {
      listMenuF(this.queryParams).then(response => {
        this.deptMenu = this.handleTree(response.data, "menuId");
      });
    },
    /** 查询机构列表 */
    getList() {
      this.loading = true;
      listDept(this.queryParams).then(response => {
        this.deptList = this.handleTree(response.data, "deptId");
        this.loading = false;
      });
    },
    /** 转换机构数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deptId: null,
        parentId: 0,
        deptName: undefined,
        orderNum: 0,
        leader: undefined,
        phone: undefined,
        email: undefined,
        status: "0",
        deptType: 0,
        showOwner: false,
        menuId: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.form.deptType = null;
      if (row != undefined) {
        this.form.parentId = row.deptId;
      }
      else {
        this.form.parentId = 0;
      }
      console.log("this.form:", this.form)
      this.open = true;
      this.title = "添加机构";
      //查询机构类型
      if (row.deptType == null) {
        row.deptType = '';
        this.deptType = row.deptType;
        this.getDeptType();
      } else {
        this.deptType = row.deptType;
        this.getDeptType();
      }
      listDept().then(response => {
        this.deptOptions = this.handleTree(response.data, "deptId");
      });
    },
    //获取机构类型
    getDeptType() {
      getDeptType(this.deptType, this.form.showOwner).then(response => {
        this.deptTypeList = response.data.map((item) => {
          return { value: item.deptType, label: item.deptTypeName };
        });
      });
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.userId = this.$store.state.user.userId;
      console.log(this.userId)
      this.reset();
      getDept(row.deptId).then(response => {
        this.form = response.data;
        console.log(this.form)
        this.open = true;
        this.title = "修改机构";
        this.form.showOwner = true;
        if (row.deptType == null) {
          row.deptType = '';
          this.deptType = row.deptType;
          this.getDeptType();
        } else {
          this.deptType = row.deptType;
          this.getDeptType();
        }
        listDeptExcludeChild(row.deptId).then(response => {
          this.deptOptions = this.handleTree(response.data, "deptId");
          if (this.deptOptions.length == 0) {
            const noResultsOptions = { deptId: this.form.parentId, deptName: this.form.parentName, children: [] };
            this.deptOptions.push(noResultsOptions);
          }
        });
      });
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleUserManage":
          this.handleUserManage(row);
          break;
        case "handleRoleManage":
          this.handleRoleManage(row);
          break;
        case "handleDelete":
          this.handleDelete(row);
          break;
        default:
          break;
      }
    },
    /** 用户管理操作 */
    handleUserManage: function (row) {
      const deptId = row.deptId;
      // this.$router.push("/system/user-manage/user/" + deptId);
      const obj = {
        path: '/systemS/enterprise/index',
        query: {
          id: deptId
        }
      };
      this.$tab.closeOpenPage(obj);
    },
    /** 角色管理操作 */
    handleRoleManage: function (row) {
      const deptId = row.deptId;
      // this.$router.push("/system/role-manage/role/" + deptId);
      const obj = {
        path: '/systemS/enterprise/role',
        query: {
          id: deptId
        }
      };
      this.$tab.closeOpenPage(obj);
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.menuId = this.menuIds.length > 0 ? this.menuIds[this.menuIds.length - 1] : null;
          console.log(this.form.menuId);
          if (this.form.deptId != null) {
            updateDept(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDept(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除名称为"' + row.deptName + '"的数据项？').then(function () {
        return delDept(row.deptId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    }
  }
};
</script>

<style lang="scss">
.text-wrap {
  font-size: 16px;
  margin: -10px 0 10px 0;
  font-weight: 500;
}

.dept-wrap {
  padding: 6px;
}

.top-card-wrap {
  margin-bottom: 5px;
}

.card-wrap {
  padding-bottom: 100px;
}

.title-wrap {
  position: relative;
  padding-left: 10px;
  font-size: 16px;
  color: #303133;
  font-weight: 700;
  margin-bottom: 25px;

  &:before {
    content: '';
    background-color: #3796ec;
    width: 3px;
    height: 18px;
    position: absolute;
    left: 0;
    top: 50%;
    margin-top: -9px;
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
    border-radius: 3px;
  }
}
</style>
