<template>
  <div class="user">
    <basic-container>
      <avue-crud
        ref="crud"
        :option="option"
        :search="searchForm"
        v-model="form"
        :page.sync="page"
        :table-loading="tableLoading"
        :before-open="handleOpenBefore"
        :before-close="handleCloseBefore"
        :data="list"
        @search-change="searchChange"
        @size-change="sizeChange"
        @current-change="currentChange"
        @search-reset="searchReset"
        @refresh-change="refreshChange"
        @row-save="saveFn"
        @row-update="updateFn"
      >
        <!-- 左侧添加按钮 -->
        <template slot="menuLeft">
          <el-button v-if="sys_user_add" class="filter-item" type="primary" size="small" icon="el-icon-edit" @click="$refs.crud.rowAdd()">添加 </el-button>
          <!-- 新增沟通专员 -->
          <el-button v-if="sys_user_add && hideCommunicationOfficer" class="filter-item" type="primary" size="small" icon="el-icon-user" @click="addCommunicationOfficerFn"
            >新增服务商人员
          </el-button>
          <!-- 批量导入 -->
          <el-button class="filter-item" type="primary" size="small" icon="el-icon-upload" @click="importUserOpen">导入用户 </el-button>
        </template>
        <!-- 右侧菜单 -->
        <template slot="menuRight">
          <!-- 角色说明隐藏 -->
          <!-- <el-button
            class="role-btn"
            type="text"
            @click="roleDialogVisible = true"
            >角色说明</el-button
          > -->
        </template>
        <!-- 操作栏 -->
        <template slot="menu" slot-scope="scope">
          <el-button v-if="sys_user_edit" type="text" size="small" icon="el-icon-edit" @click="handleUpdate(scope.row, scope.index)">编辑 </el-button>
          <el-button v-if="sys_user_del" type="text" size="small" icon="el-icon-delete" @click="deleteFn(scope.row, scope.index)">删除 </el-button>
          <el-button v-if="scope.row.role.includes(5)" type="text" size="small" icon="el-icon-document" @click="fullTimeStaffRecordFn(scope.row)">备案 </el-button>
          <el-button v-if="showBoundMedicines(scope.row.role)" type="text" size="small" icon="el-icon-document" @click="boundMedicines(scope.row)">绑定药品 </el-button>
          <el-button v-if="false" type="text" size="small" icon="el-icon-document" @click="userInfoCardFn(scope.row)">个人名片 </el-button>
        </template>
        <!-- 人员名称 -->
        <template slot="realname" slot-scope="scope">
          <div class="info">
            <!-- <span class="lable"> {{ nameHide(scope.row.realname) }}</span> -->
            <span class="lable"> {{ scope.row.realname }}</span>
            <el-tooltip effect="dark" :content="scope.row.realname" placement="right">
              <i class="el-icon-unlock icon" />
            </el-tooltip>
          </div>
        </template>
        <!-- 手机号 -->
        <template slot="username" slot-scope="scope">
          <div class="info">
            <!-- <span class="lable"> {{ phoneHide(scope.row.username) }}</span> -->
            <span class="lable"> {{ scope.row.username }}</span>
            <el-tooltip effect="dark" :content="scope.row.username" placement="right">
              <i class="el-icon-unlock icon" />
            </el-tooltip>
          </div>
        </template>
        <!-- 角色 -->
        <template slot="role" slot-scope="scope">
          <span v-for="(role, index) in scope.row.roleList" :key="index">
            <el-tag>{{ role.roleName }} </el-tag>&nbsp;&nbsp;
          </span>
        </template>
        <!-- 状态 -->
        <template slot="lockFlag" slot-scope="scope">
          <el-tag>{{ scope.label }}</el-tag>
        </template>
        <!-- 评测结果 -->
        <template slot="quizResult" slot-scope="scope">
          <template v-if="scope.row.quizResult && scope.row.quizResult.length">
            <template v-for="(item, index) in scope.row.quizResult">
              <span :key="item.quizId">
                <span class="mark-text" @click="showQuizFn(item)">{{ item.finalMark || 0 }}</span>
                <span v-if="scope.row.quizResult.length - 1 !== index">/</span>
              </span>
            </template>
          </template>
        </template>
        <!-- 派工方搜索 -->
        <template slot="deptIdSearch">
          <el-select v-model="searchForm.deptId" clearable>
            <el-option v-for="item in deptLists" :key="item.deptId" :label="item.name" :value="item.deptId"> </el-option>
          </el-select>
        </template>
        <!-- 区域搜索 -->
        <template slot="areaCodesSearch">
          <el-cascader
            @change="searchFormAreaCodesChange"
            v-model="searchFormAreaCodes"
            :options="treeList"
            :key="cascaderKey"
            collapse-tags
            :props="searchCascaderProps"
            clearable
          ></el-cascader>
        </template>

        <!-- 表单-角色 -->
        <template slot="roleForm">
          <el-select v-model="form.role" :rules="[{required: true, message: '请选择角色', trigger: 'blur'}]" multiple clearable>
            <el-option v-for="item in rolesList" :key="item.roleId" :label="item.roleName" :value="item.roleId" :disabled="item.disabled"> </el-option>
          </el-select>
        </template>

        <!-- 表单-派工方 -->
        <template slot="deptIdForm">
          <el-select v-model="form.deptId" clearable @change="deptIdChange">
            <el-option v-for="item in deptLists" :key="item.deptId" :label="item.name" :value="item.deptId"> </el-option>
          </el-select>
        </template>
        <!-- 表单-区域 -->
        <template slot="areaCodesDataForm">
          <el-cascader
            :disabled="areaCodesDisabled"
            :key="cascaderKey"
            v-model="form.areaCodesData"
            :options="treeListCopy"
            collapse-tags
            :props="cascaderProps"
            clearable
          ></el-cascader>
        </template>
      </avue-crud>
    </basic-container>
    <!-- 导入用户弹窗 -->
    <el-dialog title="导入用户" :visible.sync="importUserShow" :close-on-click-modal="false" width="35%" center :before-close="importUserClose">
      <div class="import-content" v-loading="importLoading">
        <el-upload
          class="upload-demo"
          :action="uploadUrl"
          :headers="headers"
          :before-upload="importUserBefore"
          :before-remove="beforeUserRemove"
          :limit="1"
          :on-exceed="handleUserExceed"
          :on-success="handleUserSuccess"
          :on-error="handleUserError"
          accept=".xls,.xlsx"
          :file-list="userFileList"
          :show-file-list="false"
        >
          <el-button size="small" type="primary">导入用户（*.xlsx,*.xls）</el-button>
        </el-upload>
        <br />
        <el-button type="text" @click="dowmTemplateFn">下载模板</el-button>
      </div>
    </el-dialog>
    <!-- 导入用户存在失败 -->
    <el-dialog title="上传失败！" width="35%" :close-on-click-modal="false" @close="importErrorDialogShow = fasle" :visible.sync="importErrorDialogShow" center>
      <avue-crud style="width: 100%" :data="importErrorTableData" :option="importErrorTableOption"> </avue-crud>
      <span slot="footer" class="dialog-footer">
        <el-button @click="importErrorDialogShow = fasle">关 闭</el-button>
      </span>
    </el-dialog>
    <!-- 角色描述弹窗 -->
    <RoleDescriptionDialog :roleDialogVisible.sync="roleDialogVisible" />
    <!-- 个人名片弹窗 -->
    <UserCard :userCardInfo="userCardInfo" :srcList="srcList" :userCardShow.sync="userCardShow" />
    <!-- 评测结果 -->
    <QuizDialog :showDialog.sync="showAddQuizDialog" :quizItem="quizItem" />
    <!-- 上传备案 -->
    <fullTimeStaffRecordDialog @success="refreshChange" ref="fullTimeStaffRecordRef" />
    <!-- 新增沟通专员 -->
    <communicationOfficerDialog @addSuccess="refreshChange" ref="communicationOfficerRef" />
    <!-- 生产企业绑定药品 -->
    <boundMedicinesDialog @success="refreshChange" ref="boundMedicinesDialogRef" />
  </div>
</template>

<script>
import {mapGetters} from 'vuex';
import {tableOption, importErrorTableOption} from '@/const/crud/admin/user';
import {listDept} from '@/api/wmdaagent';
import {getAreaTreeApi} from '@/api/areaTree';
import {roleExcludeList, getListByDeptApi} from '@/api/admin/role';
import {templateDownload} from '@/api/assignPoints/currency/manList';
import RoleDescriptionDialog from './components/roleDescriptionDialog.vue';
import QuizDialog from '@/views/admin/wmscorepackagestatus/components/quizDialog';
import fullTimeStaffRecordDialog from './components/fullTimeStaffRecordDialog.vue';
import communicationOfficerDialog from './components/communicationOfficerDialog.vue';
import boundMedicinesDialog from './components/boundMedicinesDialog.vue';
import UserCard from './components/UserCard.vue';
import {addObj, delObj, fetchList, putObj, getUserDetails, batchChannelCert, getAuthInfo, getUserInfoApi} from '@/api/admin/user';
import store from '@/store';
import {getDictType} from '@/api/common';
import {filterCodes, extractPaths} from '@/util/treeUtils.js';

export default {
  components: {
    RoleDescriptionDialog,
    UserCard,
    QuizDialog,
    fullTimeStaffRecordDialog,
    communicationOfficerDialog,
    boundMedicinesDialog
  },
  data() {
    return {
      hideCommunicationOfficer: true,
      dialogType: '',
      option: tableOption,
      searchFormAreaCodes: [],
      searchForm: {
        certType: '',
        areaCodes: []
      },
      searchCascaderProps: {
        multiple: true,
        label: 'name',
        value: 'id'
      },
      form: {
        role: [],
        deptId: '',
        areaCodesData: []
      },
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20, // 每页显示多少条,
        isAsc: false // 是否倒序
      },
      list: [],
      tableLoading: false,
      deptIdList: [],
      rolesList: [], // 角色列表
      importUserShow: false,
      importLoading: false,
      uploadUrl: '/admin/wmtask/task-batch-import',
      headers: {
        Authorization: 'Bearer ' + store.getters.access_token
      },
      importErrorDialogShow: false,
      importErrorTableOption,
      importErrorTableData: [],
      userFileList: [],
      roleDialogVisible: false,
      cascaderKey: 0,
      treeList: [],
      treeListCopy: [],

      cascaderProps: {
        multiple: true,
        label: 'name',
        value: 'id'
      },

      genderList: [],
      userDegreeList: [],
      userCardInfo: {},
      userCardShow: false,
      srcList: [],
      quizItem: {},
      showAddQuizDialog: false,
      deptLists: [],
      areaCodesDisabled: true,
      noArea: false,
      isLevel2csoDept: {}
    };
  },
  watch: {
    'form.role'(newVal) {
      if (!newVal) return;
      // 检查角色是否为全职、兼职或招商经理
      const deptId = this.findObject(this.option.column, 'deptId');
      // 角色为csm展示上级主管
      const parentIdList = this.findObject(this.option.column, 'parentIdList');
      // 选择区域
      const areaCodesData = this.findObject(this.option.column, 'areaCodesData');
      const isDeptRole = !newVal || newVal.length === 0 || [5, 6, 31].some(role => newVal.includes(role));
      this.$set(deptId, 'editDisplay', !isDeptRole);
      this.$set(deptId, 'addDisplay', !isDeptRole);
      if ([5, 6, 37].some(role => newVal.includes(role))) {
        this.form.areaCodesData = [];
        this.noArea = true;
        this.$set(areaCodesData, 'editDisplay', false);
        this.$set(areaCodesData, 'addDisplay', false);
      } else {
        this.noArea = false;
        this.$set(areaCodesData, 'editDisplay', true);
        this.$set(areaCodesData, 'addDisplay', true);
      }
      // 检查角色是否为CSM
      const isCsm = newVal && newVal.includes(19);
      this.$set(parentIdList, 'editDisplay', isCsm);
      this.$set(parentIdList, 'addDisplay', isCsm);
    },
    'form.deptId'(newval) {
      this.isLevel2csoDept = {};
      // this.form.areaCodesData = [];
      if (!newval) {
        this.form.areaCodesData = [];
        this.areaCodesDisabled = true;
      }
      if (newval) {
        const curr = this.deptLists.find(item => item.deptId === newval);
        if (this.noArea) {
          this.isLevel2csoDept = curr;
        }
        if (curr.areaCodes && curr.areaCodes.length) {
          const treeList = JSON.parse(JSON.stringify(this.treeList));
          const currTree = filterCodes(curr.areaCodes, treeList);
          this.treeListCopy = currTree;
        } else {
          this.treeListCopy = this.treeList;
        }
        this.areaCodesDisabled = false;
      }
    }
  },
  computed: {
    ...mapGetters(['permissions', 'userInfo'])
  },
  created() {
    this.sys_user_add = this.permissions['sys_user_add'];

    this.sys_user_edit = this.permissions['sys_user_edit'];
    this.sys_user_del = this.permissions['sys_user_del'];
    this.user_record_check = this.permissions['user_record_check'];
    this.getList(this.page);
    this.getAreaTree();
    this.getRoleList();
    this.getListByDept();
    this.getDict();
  },
  mounted() {
    // 50 隐藏沟通专员
    const roles = this.userInfo.roles;
  },
  methods: {
    // 判断可以绑定药品的角色id
    showBoundMedicines(role) {
      const flag = role.some(item => item >= 49 || item == 39 || item == 41);
      return flag;
    },
    // 生产企业监督员绑定药品
    boundMedicines(row) {
      const info = JSON.parse(JSON.stringify(row));
      this.$refs.boundMedicinesDialogRef.addFn(info);
    },

    deptIdChange() {
      this.form.areaCodesData = [];
    },
    addCommunicationOfficerFn() {
      this.$refs.communicationOfficerRef.show();
    },
    fullTimeStaffRecordFn(row) {
      this.$refs.fullTimeStaffRecordRef.showInfo(row);
    },
    // 名字脱敏
    nameHide(name) {
      let userName;
      if (name.length == 2) {
        userName = name.substring(0, 1) + '*'; //截取name 字符串截取第一个字符，
      } else if (name.length == 3) {
        userName = name.substring(0, 1) + '*' + name.substring(2, 3); //截取第一个和第三个字符
      } else if (name.length > 3) {
        userName = name.substring(0, 1) + '*' + '*' + name.substring(3, name.length); //截取第一个和大于第4个字符
      }
      return userName;
    },
    phoneHide(phone) {
      let reg = /^(1[3-9][0-9])\d{4}(\d{4}$)/; // 定义手机号正则表达式
      phone = phone.replace(reg, '$1****$2');
      return phone; // 185****6696
    },
    // 获取列表
    async getList(page, params) {
      this.tableLoading = true;
      const obj = Object.assign(
        {
          current: page.currentPage,
          size: page.pageSize
        },
        params,
        this.searchForm
      );

      if (obj.role) {
        obj.role = [obj.role];
      }
      const res = await fetchList(obj);

      res.data.data.records.forEach(item => {
        item.role = item.roleList.map(iten => iten.roleId);
      });
      const records = res.data.data.records;
      this.list = records;

      this.page.total = res.data.data.total;
      this.tableLoading = false;
    },
    // 获取派工方列表
    // async getDeptIdList() {
    //   const res = await listDept();
    //   console.log("res", res);
    //   this.deptIdList = res.data.data;
    // },
    // 获取区域树列表
    async getAreaTree() {
      const res = await getAreaTreeApi();

      this.treeList = res.data.data;
    },
    // 获取字典
    getDict() {
      getDictType({type: 'gender'}).then(res => {
        this.genderList = res.data.data;
      });
      getDictType({type: 'user_degree'}).then(res => {
        this.userDegreeList = res.data.data;
      });
    },
    searchFormAreaCodesChange(e) {
      console.log('e', e);
    },
    // 获取角色列表
    async getRoleList() {
      const res = await roleExcludeList();
      // 当前角色：BC总负责人，筛选出角色19: csm
      if (this.userInfo.roles.includes(35)) {
        res.data.data = response.data.data.filter(item => item.roleId === 19);
      }
      let data = res.data.data;
      const roleList = [5, 6, 37];
      data = data.filter(item => !roleList.includes(item.roleId));
      this.rolesList = data;
      this.rolesList.forEach((ele, idx) => {
        this.$set(this.rolesList[idx], 'disabled', false);
      });
    },
    async getListByDept() {
      const res = await getListByDeptApi();
      this.deptLists = res.data.data;
    },
    // 新增编辑前操作
    handleOpenBefore(show, type) {
      ++this.cascaderKey;
      // 请求角色列表
      show();
    },
    // 关闭前
    handleCloseBefore(done, type) {
      let self = this;
      for (let key in self.form) {
        self.form[key] = '';
      }
      ++this.cascaderKey;
      this.form = {};
      this.form.areaCodesData = [];
      done();
    },

    // 编辑
    async handleUpdate(row, index) {
      if (row.role.includes(5) || row.role.includes(37)) {
        return this.$refs.communicationOfficerRef.editFn(row);
      }

      const role = row.roleList.map(item => item.roleId);
      row.role = role;
      const areaCodes = row.areaCodes;

      const treeList = JSON.parse(JSON.stringify(this.treeList));
      const currTree = filterCodes(areaCodes, treeList);
      if (currTree) {
        const ids = extractPaths(currTree);
        row.areaCodesData = ids;
      }
      this.$forceUpdate();
      this.$refs.crud.rowEdit(row, index);
      this.form.password = undefined;
    },
    // 删除
    deleteFn(row, index) {
      this.$confirm('此操作将永久删除该用户(用户名:' + row.username + '), 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delObj(row.userId)
          .then(() => {
            this.list.splice(index, 1);
            this.$notify.success('删除成功');
          })
          .catch(() => {
            this.$notify.error('删除失败');
          });
      });
    },
    // 个人名片
    async userInfoCardFn(row) {
      this.srcList = [];
      const res = await getUserInfoApi(row.userId);
      this.userCardInfo = res.data.data;
      // 性别回显
      const curr = this.genderList.find(item => item.value === this.userCardInfo.gender);
      if (curr) {
        this.userCardInfo.genderLabel = curr.label;
      }
      // 学历回显
      const curr2 = this.userDegreeList.find(item => item.value === this.userCardInfo.degree);
      if (curr2) {
        this.userCardInfo.degreeLabel = curr2.label;
      }
      if (this.userCardInfo.qualificationsUrl && this.userCardInfo.qualificationsUrl.length) {
        const arr = this.userCardInfo.qualificationsUrl.map(item => process.env.VUE_APP_URL + item);
        this.userCardInfo.qualificationsUrl = arr;
        this.srcList = arr;
      }
      this.userCardShow = true;
    },
    // 导入用户
    importUserOpen() {
      this.uploadUrl = 'admin/user/batch';
      this.importUserShow = true;
    },
    // 导入用户弹窗关闭
    importUserClose() {
      this.importUserShow = false;
      this.userFileList = [];
    },
    // 导入模板前
    importUserBefore() {
      this.importLoading = true;
    },
    beforeUserRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleUserExceed(files, fileList) {
      this.$message.warning('最多上传一个文件');
    },
    // 用户导入成功
    handleUserSuccess(res, file) {
      this.importLoading = false;
      // 上传成功
      if (res.code === 0) {
        this.$message.success('上传成功！');
        this.importUserClose();
        this.getList(this.page);
        return;
      }
      // 初始化用户文件列表
      this.userFileList = [];
      // 检查上传失败的情况
      if (res.data && res.data.code === 'FAILURE') {
        // 上传有错误
        const errorData = res.data.data;
        this.importErrorTableData = Object.keys(errorData).map(key => ({
          reason: key,
          index: errorData[key]
        }));
        this.importErrorDialogShow = true;
      } else {
        // 其他上传失败情况
        this.$message.error(res.msg);
      }
    },
    // 导入失败
    handleUserError(err) {
      this.$message.error('上传失败！');
      this.importLoading = false;
    },
    // 下载模板
    dowmTemplateFn() {
      this.importLoading = true;
      templateDownload({
        fileName: 'batch_create_user_template.xlsx'
      })
        .then(response => {
          this.importLoading = false;
          let url = window.URL.createObjectURL(new Blob([response.data]));
          let link = document.createElement('a');
          link.style.display = 'none';
          link.href = url;
          link.setAttribute('download', '批量创建用户模板.xlsx');
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
        .catch(() => {
          this.importLoading = false;
        });
    },
    updateDepartmentInfo() {
      if (!this.form.deptId) {
        this.form.deptId = this.userInfo.deptId;
        const curr = this.deptLists.find(item => item.deptId === this.form.deptId);
        this.isLevel2csoDept = curr;
      }
      this.form.areaCodes = this.isLevel2csoDept.areaCodes;
    },

    async saveFn(row, done, loading) {
      if (this.noArea) {
        this.updateDepartmentInfo();
      } else {
        const flattenedArray = this.form.areaCodesData.flat();
        const areaCodes = Array.from(new Set(flattenedArray));
        this.form.areaCodes = areaCodes;
      }
      this.form.phone = this.form.username;
      if (this.form.phone.indexOf('*') > 0) {
        this.form.phone = undefined;
      }
      if (!this.form.deptId) {
        this.form.deptId = this.userInfo.deptId;
      }
      if (!this.form.parentIdList) {
        this.form.parentIdList = [];
      }
      addObj(this.form)
        .then(() => {
          this.getList(this.page);
          if (this.validateField) {
          }
          const obj = {
            role: [],
            deptId: '',
            areaCodesData: []
          };
          this.$set(this, 'form', obj);

          this.$notify.success('创建成功');
          done();
        })
        .catch(() => {
          loading();
        });
    },
    async updateFn(row, done, loading) {
      if (this.noArea) {
        this.updateDepartmentInfo();
      } else {
        const flattenedArray = this.form.areaCodesData.flat();
        const areaCodes = Array.from(new Set(flattenedArray));
        this.form.areaCodes = areaCodes;
      }
      this.form.phone = this.form.username;
      if (this.form.phone.indexOf('*') > 0) {
        this.form.phone = undefined;
      }
      putObj(this.form)
        .then(() => {
          this.form = {
            role: [],
            deptId: '',
            areaCodesData: []
          };
          this.getList(this.page);
          done();
          this.$notify.success('创建成功');
        })
        .catch(() => {
          loading();
        });
    },
    extractLastElements(array) {
      // 创建一个新的空数组来存储结果
      let result = [];
      // 遍历输入的二维数组
      for (let i = 0; i < array.length; i++) {
        // 检查内部数组是否非空
        if (array[i].length > 0) {
          // 将内部数组的最后一个元素添加到结果数组中
          result.push(array[i][array[i].length - 1]);
        }
      }
      // 返回结果数组
      return result;
    },
    // 搜索
    searchChange(param, done) {
      this.searchForm = param;
      if (this.searchFormAreaCodes.length) {
        const codes = this.extractLastElements(this.searchFormAreaCodes);
        this.searchForm.areaCodes = codes;
      }
      this.page.currentPage = 1;
      this.getList(this.page, param);
      done();
    },
    // page修改
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.getList(this.page);
    },
    currentChange(current) {
      this.page.currentPage = current;
      this.getList(this.page);
    },
    refreshChange() {
      this.getList(this.page);
    },
    searchReset() {
      // this.searchForm = {};
      ++this.cascaderKey;
      this.searchFormAreaCodes = [];
    },
    // 合规测评
    showQuizFn(quizItem) {
      this.quizItem = quizItem;
      this.showAddQuizDialog = true;
    }
  }
};
</script>

<style lang="scss" scoped>
.import-content {
  text-align: center;
}
.info {
  .lable {
    margin-right: 5px;
  }
  .icon {
    cursor: pointer;
  }
}
</style>
