<template>
  <div class="app-container">
    <el-row :gutter="20"  >
      <!--部门数据-->
      <el-col :span="5" :xs="24" style="min-height: calc(100vh - 140px); box-shadow: 5px 0px 0px 0px #ECF2FE;">
        <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" style="overflow-y: auto; max-height: calc(100vh - 180px);">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            highlight-current
            :default-expanded-keys="expandedKeys"
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="19" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="用户名称" prop="userName">
            <el-input
              v-model="queryParams.userName"
              placeholder="请输入用户名称"
              clearable
              style="width: 240px"
              @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-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button  type="primary" plain
              icon="el-icon-refresh"  size="mini"  @click="handleSynch"
            >同步部门及用户信息</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <div  v-tableHeight="{customHeight: 85}">
          <el-table v-loading="loading" :data="userList" header-cell-class-name="table-header-style"	height="100%">
            <el-table-column label="工号" align="center" key="personId" prop="personId" v-if="columns[0].visible" />
            <el-table-column label="用户名称" align="center" key="userName" prop="userName" v-if="columns[1].visible" :show-overflow-tooltip="true" />
            <el-table-column label="部门" align="center" key="deptName" prop="dept.deptName" v-if="columns[2].visible" :show-overflow-tooltip="true" />
            <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber" v-if="columns[3].visible" width="120" />
            <el-table-column label="行政级别" align="center" key="rankName" prop="rankName" v-if="columns[4].visible" width="120" />
            <el-table-column label="兼职" align="center" key="sideline" prop="sideline"  width="90" >
              <template slot-scope="scope">
                  {{scope.row.sideline=='1'?'兼职':'主职'}}
              </template>
            </el-table-column>

            <el-table-column label="用户类型" align="center" key="userType" prop="userType" v-if="columns[5].visible" width="120" >
              <template slot-scope="scope">
                <dict-tag :options="dict.type.bus_user_type" :value="scope.row.userType"/>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[6].visible" width="160">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="100"
              class-name="small-padding fixed-width" >
              <template slot-scope="scope" >
                <el-button size="mini" type="text" icon="el-icon-view"
                  @click="handleView(scope.row)"
                >分配角色</el-button>

              </template>
            </el-table-column>
          </el-table>
        </div>

        <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="600px" append-to-body>
      <el-form ref="form" :model="form"  label-width="80px" class="view_form">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户姓名" prop="nickName">
              {{form.userName}}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="行政级别" prop="rankName">
              {{form.rankName}}
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="归属部门" prop="deptId">
              {{form.allPathName}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phonenumber">
              {{form.phonenumber}}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工号" prop="personId">
              {{form.personId}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户性别">
              <!-- 0=男,1=女,2=未知 -->
              {{ form.sex==0?'男':(form.sex==1?'女':'未知')}}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              {{form.status==0?'正常':'停用'}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="用户类型">
              <el-select v-model="form.userType" clearable multiple placeholder="请选择用户类型" style="width: 100%;">
                <el-option  v-for="dict in userTypeFilter(dict.type.bus_user_type)"
                  :key="dict.value" :label="dict.label" :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              {{form.remark}}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateUserType">确 定</el-button>
        <el-button @click="cancel">关  闭</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { listUser, getUser,  updateUser,  deptTreeSelect, handleSynch } from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "User",
  dicts: ['sys_normal_disable', 'sys_user_sex', 'bus_user_type'],
  components: { Treeselect },
  data() {
    return {

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      expandedKeys:[],
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined
      },
      // 列信息
      columns: [
        { key: 0, label: `工号`, visible: true },
        { key: 1, label: `用户名称`, visible: true },
        { key: 2, label: `部门`, visible: true },
        { key: 3, label: `手机号码`, visible: true },
        { key: 4, label: `行政级别`, visible: true },
        { key: 5, label: `用户类型`, visible: true },
        { key: 6, label: `创建时间`, visible: true }
      ],

    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.getDeptTree();
    this.getConfigKey("sys.user.initPassword").then(response => {
      this.initPassword = response.msg;
    });
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
        this.expandedKeys[0] = this.deptOptions[0].id;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.handleQuery();
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        deptId: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: "0",
        remark: undefined,
        postIds: [],
        roleIds: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 同步按钮操作 */
    handleSynch() {
      handleSynch().then(response => {
        // this.getList();
        this.$modal.msgSuccess("用户同步中，请稍后刷新列表查看！");
      });
    },
    /** 修改按钮操作 */
    handleView(row) {
      this.reset();

      this.form = {...row, userType: row.userType.split(',')};
      this.open = true;
      this.title = "查看用户";

      // const userId = row.userId || this.ids;
      // getUser(userId).then(response => {
      //   this.form = response.data;
      //   // this.postOptions = response.posts;
      //   // this.roleOptions = response.roles;
      //   // this.$set(this.form, "postIds", response.postIds);
      //   // this.$set(this.form, "roleIds", response.roleIds);
      //   this.open = true;
      //   this.title = "查看用户";
      //   this.form.password = "";
      // });
    },

    // 修改用户类型
    updateUserType() {
       if(this.form.userType.length > 0){
        var data = {userId: this.form.userId,userName:this.form.userName, userType: this.form.userType.join(",")}
         updateUser(data).then(res => {
          this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
         })
       } else {
        this.$modal.msgError("请选择用户类型")
       }

    },
    userTypeFilter(data){
      var allPath = this.form.allPathName;
      if(allPath){
        let chars = ['缉私局', '兴庆海关','银川河东机场海关', '石嘴山海关','中卫海关','技术中心','保健中心','银川数据分中心'];
        let containsAny = chars.some(char => allPath.indexOf(char) !== -1);
        var arr = [];
        if(containsAny){ //  != 4 6 7
          arr = ['4','6','7']
          return data.filter(item => !arr.includes(item.value))
        } else {
          arr = ['2','5']
        }
        return data.filter(item => !arr.includes(item.value))
      } else {
        return data;
      }
    },

  }
};
</script>

<style scoped>
::v-deep .view_form .el-form-item{
  margin-bottom: 10px;
}
</style>
