<template>
  <div class="app-container">
    <el-card>
      <el-form label-width="80px">
        <div class="grab"  id="add">
          <div class="search">
            <div class="sl">
              <el-form-item label="编号" prop="toolCode">
                <el-input
                  v-model="queryParams.toolCode"
                  placeholder="请输入编号"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="中文别名" prop="toolName">
                <el-input
                  v-model="queryParams.toolName"
                  placeholder="请输入中文别名"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="形态" prop="status">
                <el-select
                  v-model="queryParams.status"
                  placeholder="形态"
                  clearable
                  style="width: 240px"
                >
                  <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 label="创建时间">
                <el-date-picker
                  v-model="dateRange"
                  style="width: 240px"
                  value-format="yyyy-MM-dd"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                ></el-date-picker>
              </el-form-item>
            </div>
            <div class="sr">
              <el-button type="primary" icon="el-icon-search">搜索</el-button>
              <el-button icon="el-icon-refresh-left">重置</el-button>
            </div>
          </div><!--search 默认查询-->
        </div><!--grab-->
      </el-form><!--el-form-->
    </el-card><!--el-card-->

    <el-card class="lrtt">
      <div class="lt">
        <el-input
          v-model="deptName"
          placeholder="请输入部门名称"
          clearable
          size="small"
          prefix-icon="el-icon-search"
          style="margin-bottom: 20px"
        />
        <div class="divide"></div><!--divide 分隔-->
        <el-tree
          :data="deptOptions"
          :props="defaultProps"
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
          ref="tree"
          node-key="id"
          default-expand-all
          highlight-current
          @node-click="handleNodeClick"
        />
      </div><!--lt 左-->
      <div class="rt">
        <el-table v-loading="loading" :data="toolList">
          <el-table-column label="编号" align="center" key="toolCode" prop="toolCode" v-if="columns[0].visible" />
          <el-table-column label="中文别名" align="center" key="toolName" prop="toolName" v-if="columns[1].visible" :show-overflow-tooltip="true" />
          <el-table-column label="类别" align="center" key="toolType" prop="toolType" v-if="columns[2].visible" :show-overflow-tooltip="true" >
            <template slot-scope="scope">
              <template v-for="dict in dict.type.tool_type">
                <span v-if="scope.row.toolType == dict.value">{{ dict.label }}</span>
              </template>
            </template>
          </el-table-column>
          <el-table-column label="部门" align="center" key="deptName" prop="dept.deptName" v-if="columns[3].visible" :show-overflow-tooltip="true" />
          <el-table-column label="负责人" align="center" key="toolPrincipalsName" prop="toolPrincipalsName" v-if="columns[4].visible" width="120" />
          <el-table-column label="形态" align="center" key="status" v-if="columns[5].visible">
            <template slot-scope="scope">
              <el-tag type="success" v-if="scope.row.status == '0'">正常</el-tag>
              <el-tag type="info" v-if="scope.row.status == '1'">禁用</el-tag>
            </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="250"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button type="text" icon="el-icon-info" @click="handleDetail(scope.row)">查看</el-button>
             <!--  <el-button type="text" icon="el-icon-download">下载</el-button>
              <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['tool:edit', 'tool:remove']">
                <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="handleUpdate" icon="el-icon-edit"
                                    v-hasPermi="['tool:edit']">编辑</el-dropdown-item>
                  <el-dropdown-item command="handleDelete" icon="el-icon-delete"
                                    v-hasPermi="['tool:remove']">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown> -->
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div><!--rt 右-->
    </el-card><!--el-card-->

    <!-- 工具详情对话框 -->
    <el-drawer :visible.sync="detailDrawerOpen" :modal-append-to-body="false" size="85%" class="no-padding">
      <template #title>
        <span>工具名称</span>
      </template>
      <tool-detail ref="toolDetailRef" :toolDetail="toolDetail"/>
    </el-drawer><!--el-drawer 详情-抽屉-->

    <bl-user-selector  ref="peopleSelect" :type="'single'" :isCheck="true" :open="toolPrincipalsChoose" @cancel="toolPrincipalsChoose=false"   @submit="submitPeople"></bl-user-selector>
  </div><!--app-container-->
</template>

<script>
  import { listDocument } from "@/api/document/document";
  import { listTool, getTool, delTool, addTool, updateTool } from "@/api/tool/tool";
  import { deptTreeSelect } from "@/api/system/user";
import { getToken } from "@/utils/auth";
import { Base64 } from 'js-base64'
import Treeselect from "@riophae/vue-treeselect";
import blUserSelector from "@/components/user-selector/src/user-selector";
import toolDetail from "./toolDetail";

export default {
  name: "User",
  dicts: ['sys_normal_disable', 'tool_type'],
  components: { Treeselect, blUserSelector, toolDetail },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      toolPrincipalsChoose: false,
      // 总条数
      total: 0,
      // 工具表格数据
      toolList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      toolPrincipalsData: [],
      toolDetail: {},
      detailDrawerOpen: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        toolCode: undefined,
        toolName: undefined,
        status: 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 }
      ],
      // 表单校验
      rules: {
        toolCode: [
          { required: true, message: "编号不能为空", trigger: "blur" },
          { min: 2, max: 30, message: '编号长度必须介于 2 和 30 之间', trigger: 'blur' }
        ],
        toolName: [
          { max: 50, message: '中文别名不能超过50个字', trigger: 'blur' }
        ],
        toolPrincipals: [
          { required: true, message: "负责人不能为空", trigger: "blur" }
        ],
        toolSource: [
          { max: 50, message: '来源不能超过50个字', trigger: 'blur' }
        ],
        toolUse: [
          { max: 50, message: '用途不能超过50个字', trigger: 'blur' }
        ]
      },
      // 新增时的关联附件
      docList: [],
      docQueryParams: {
        pageNum: 1,
        pageSize: 10,
        toolId: ''
      },
      addDocShow: false,
      viewDialogOpen: false,
      viewDialogTitle: '',
      previewUrl: ''
    };
  },
  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: {
    handlePriew(row){
      this.previewUrl = process.env.VUE_APP_TOOL_TECH_FILE_VIEW_API + '/onlinePreview?url=' + encodeURIComponent(Base64.encode(process.env.VUE_APP_BASE_API + row.docUrl));
      this.viewDialogTitle = '文档在线预览'
      this.viewDialogOpen = true;
    },
    /**
     * 新增上传附件
     */
    handleDocAdd() {
      this.addDocShow = true
    },
    handleClick(){

    },
    submitPeople(peopleList){
      console.log(peopleList);
      this.form.toolPrincipals = peopleList[0]['userId']
      this.form.toolPrincipalsName = peopleList[0]['nickName']
      this.toolPrincipalsChoose = false;
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listTool(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.toolList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    getDeptName(items, id) {
      let label = ''
      items.forEach(item => {
        if(item['id'] == id){
          label = item['label']
          return
        }
      })
      if(label == ''){
        items.forEach(item => {
          if (item.children) {
            label = this.getDeptName(item.children, id)
          }
        })
      }
      return label
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.toolRespDept = data.id;
      this.handleQuery();
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.userName + '"用户吗？').then(function() {
        return changeUserStatus(row.userId, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    // 取消按钮
    cancel() {
      this.addDrawerOpen = 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();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.deptId = undefined;
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    handleDetail(row){
      this.detailDrawerOpen = true
      this.toolDetail = row
    },
  }
};
</script>
<style scoped>
</style>
