<template>
  <!-- <div class="app-container" id="L-size-main">
    <el-row :gutter="20">
      用户数据
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" id="L-header">
          <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 label="单位类型" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="用户状态"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="dict in dict.type.dwlx"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="统一社会信用代码" prop="phonenumber">
            <el-input
              v-model="queryParams.phonenumber"
              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-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8" id="L-tab">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:user:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
              v-hasPermi="['system:user:import']"
            >导入</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:user:export']"
            >导出</el-button>
          </el-col>
        </el-row>

        <el-table v-loading="loading" :data="userList" :height="tabHeader" :max-height="tabHeader" :row-class-name="tableRowClassName">
          <el-table-column type="index" label="序号" width="50" align="center" />
          <el-table-column label="单位名称" align="center" key="nickName" prop="nickName">
            <template slot-scope="scope">{{ scope.row.unitInfo.nickName }}</template>
          </el-table-column>
          <el-table-column label="单位类型" align="center" key="dwlx" prop="dwlx">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.dwlx" :value="scope.row.dwlx"/>
            </template>
          </el-table-column>
          <el-table-column label="统一社会信用代码" align="center" key="userName" prop="userName">
            <template slot-scope="scope">{{ scope.row.unitInfo.userName }}</template>
          </el-table-column>
          <el-table-column label="所属区域" align="center" key="ssqycounty" prop="ssqycounty">
            <template slot-scope="scope">{{ scope.row.unitInfo.ssqycounty }}</template>
          </el-table-column>
          <el-table-column label="所属行业" align="center" key="sshy" prop="sshy">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sshy" :value="scope.row.sshy"/>  
              {{ scope.row.sshy }}
            </template>
          </el-table-column>
          <el-table-column label="单位地址" align="center" key="dwxxdz" prop="dwxxdz">
            <template slot-scope="scope">{{ scope.row.unitInfo.dwxxdz }}</template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="160"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope" v-if="scope.row.userId !== 1">
              <el-button
                size="mini"
                type="text"
                @click="handleUpdate(scope.row)"
              >查看</el-button>
              <el-button
                size="mini"
                type="text"
                @click="handleUpdate(scope.row)"
              >编辑</el-button>
              <el-button
                size="mini"
                type="text"
                @click="handleDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          id="L-pagination"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>
  </div> -->
  <div class="L-main" id="L-size-main">
    <div class="content-search" id="L-header">
      <div class="search-title">查询条件</div>
      <el-form :inline="true" :model="queryParams" ref="queryForm" size="small" class="demo-form-inline">
        <el-row>
          <el-col :span="6">
            <el-form-item label="单位名称：" prop="nickName">
              <el-input
                v-model="queryParams.nickName"
                placeholder="请输入单位名称"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单位类型：" prop="dwlx">
              <el-select
                v-model="queryParams.dwlx"
                placeholder="用户状态"
                clearable
              >
                <el-option
                  v-for="dict in dict.type.dwlx"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="统一社会信用代码：" class="tyshxydm-class" prop="userName">
              <el-input
                v-model="queryParams.userName"
                placeholder="请输入统一社会信用代码"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="3" style="text-align: right;padding-right: 20px;">
            <el-form-item class="unit-form">
              <el-button size="mini" @click="resetQuery">重置</el-button>
              <el-button size="mini" type="primary" @click="handleQuery">查询</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <main>
      <div class="search-title">
        <span class="search-title-span">任务列表</span>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
              v-hasPermi="['system:user:import']"
            >导入</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:user:export']"
            >导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:user:add']"
            >新增单位</el-button>
          </el-col>
        </el-row>
      </div>
      <section>
        <el-table v-loading="loading" :data="userList" :height="tabHeader" :max-height="tabHeader" :row-class-name="tableRowClassName">
          <el-table-column type="index" label="序号" width="50" align="center" />
          <el-table-column label="单位名称" align="center" key="nickName" prop="nickName">
            <template slot-scope="scope">{{ scope.row.nickName }}</template>
          </el-table-column>
          <el-table-column label="单位类型" align="center" key="dwlx" prop="dwlx">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.dwlx" :value="scope.row.dwlx"/>
            </template>
          </el-table-column>
          <el-table-column label="统一社会信用代码" align="center" key="userName" prop="userName">
            <template slot-scope="scope">{{ scope.row.userName }}</template>
          </el-table-column>
          <el-table-column label="所属区域" align="center" key="ssqycounty" prop="ssqycounty">
            <template slot-scope="scope">{{ scope.row.ssqycity }}</template>
          </el-table-column>
          <el-table-column label="所属行业" align="center" key="sshy" prop="sshy">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sshy" :value="scope.row.sshy"/>  
              <!-- {{ scope.row.sshy }} -->
            </template>
          </el-table-column>
          <el-table-column label="单位地址" align="center" key="dwxxdz" prop="dwxxdz">
            <template slot-scope="scope">{{ scope.row.dwxxdz }}</template>
          </el-table-column>
          <el-table-column label="操作" prop="userId" class-name="table-operation" align="center">
            <template slot-scope="scope">
              <div style="display: flex;align-items: center;justify-content: center;">
                <div style="display: flex;align-items: center;">
                  <img src="@/assets/images/icon-ck@2x.png" alt="" style="width: 20px;margin-right: 5px;">
                  <span class="look-info" @click="handleLookdate(scope.row)" style="color: #1485EF;margin-right: 15px;cursor: pointer;">查看</span>
                </div>
                <div style="display: flex;align-items: center;">
                  <img src="@/assets/images/edit.png" alt="" style="width: 15px;margin-right: 5px;">
                  <span class="look-info" @click="handleUpdate(scope.row)" style="color: #1485EF;margin-right: 15px;cursor: pointer;">编辑</span>
                </div>
                <div style="display: flex;align-items: center;">
                  <img src="@/assets/images/del.png" alt="" style="width: 20px;margin-right: 5px;">
                  <span class="look-info" @click="handleDelete(scope.row)" style="color: #F50C0C;margin-right: 15px;cursor: pointer;">删除</span>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </section>
      <my-pagination 
        id="L-pagination"
        :total="total"
        :page="queryParams.current"
        :limit="queryParams.size"
        @pagination="getPagination"
        :current-page.sync="queryParams.current" 
      ></my-pagination>
    </main>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import { listUser, getUser, delUser, addUser, updateUser, resetUserPwd, changeUserStatus, deptTreeSelect } from "@/api/system/user";
import { listUnit, delUnit } from "@/api/auditPagesApi/index";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import myPagination from "@/views/components/Pagination/index.vue"

export default {
  name: "User",
  dicts: ['dwlx','sshy'],
  components: { Treeselect, myPagination },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/tc/unit/importData"
      },
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        userName: undefined,
        nickName: undefined,
        dwlx: undefined,
      },
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: "用户昵称不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "用户密码不能为空", trigger: "blur" },
          { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' },
          { pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\\ |", trigger: "blur" }
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phonenumber: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      },
      tabHeader: undefined,
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    // this.getConfigKey("sys.user.initPassword").then(response => {
    //   this.initPassword = response.msg;
    // });
  },
  mounted(){
    this.cancalDebounce();
    window.addEventListener('resize', this.cancalDebounce);
  },
  destroyed() {
    window.removeEventListener('resize', this.cancalDebounce);
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listUnit(this.queryParams).then(response => {
          this.userList = response.data.records;
          this.total = response.data.total;
          this.loading = false;
        }
      );
    },
    // 页码获取
    getPagination(pages){
      this.queryParams.current = pages.page;
      this.queryParams.size = pages.limit;
      this.getList();
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      // this.reset();
      // getUser().then(response => {
      //   this.postOptions = response.posts;
      //   this.roleOptions = response.roles;
      //   this.open = true;
      //   this.title = "添加用户";
      //   this.form.password = this.initPassword;
      // });
      this.$router.push({name: 'UnitAuth',query: {
        pageType: "add",
      }})
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$router.push({name: 'UnitAuth',query: {
        pageType: "change",
        id: row.id
      }})
    },
    /** 查看按钮操作 */
    handleLookdate(row){
      this.$router.push({name: 'UnitAuth',query: {
        pageType: "look",
        id: row.id
      }})
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$modal.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？').then(function() {
        return delUnit(userIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('/tc/unit/export', {
        ...this.queryParams
      }, `unit_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('/tc/unit/importTemplate', {
      }, `unit_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 修改table背景色
    tableRowClassName({row, rowIndex}){
      if (rowIndex % 2 !== 0) {
        return 'evenNumber-row';
      }
      return '';
    },
    // 屏幕尺寸变化
    cancalDebounce(){
      const element = document.getElementById('L-size-main'); // 通过元素的 ID 获取元素
      const header = document.getElementById('L-header'); // 通过元素的 ID 获取元素
      const pagination = document.getElementById('L-pagination'); // 通过元素的 ID 获取元素
      const elementHeight = element.offsetHeight;
      const headerHeight = header.offsetHeight;
      const paginationtHeight = pagination.offsetHeight;
      this.tabHeader = elementHeight - headerHeight - paginationtHeight - 120;
    }
  }
};
</script>