<template>
  <div class="p-2">
    <!-- 查询条件 -->
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="mb-[10px]" v-show="showSearch">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="68px">
            <el-form-item label="用户名称" prop="userName">
              <el-input v-model="queryParams.userName" placeholder="请输入用户名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="用户职称" prop="title">
              <el-select v-model="queryParams.title" placeholder="全部职称" clearable style="width: 240px">
                <el-option v-for="dict in _system_user_type_title" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="用户身份" prop="loginIdentity">
              <el-select v-model="queryParams.loginIdentity" placeholder="全部身份" clearable style="width: 240px">
                <el-option v-for="dict in _system_user_type_identity" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery" icon="Search">搜索</el-button>
              <el-button @click="resetQuery" icon="Refresh">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>
    <!-- 查询条件 -->

    <el-card shadow="hover">
      <!-- 操作按钮 -->
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button type="primary" plain @click="handleAdd()" v-has-permi="['system:user:add']" icon="Plus">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain @click="handleUpdate()" :disabled="single" v-has-permi="['system:user:edit']" icon="Edit">
              修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain @click="handleDelete($event)" :disabled="multiple" v-has-permi="['system:user:remove']" icon="Delete">
              删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="UploadFilled" @click="handleImport"> 批量上传 </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :search="true"></right-toolbar>
        </el-row>
      </template>
      <!-- 操作按钮 -->
      <!-- 表格 -->
      <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange" empty-text="未找到搜索内容，请重新尝试">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="用户编号" align="center" prop="userCode" width="130" />
        <el-table-column label="用户昵称" align="center" prop="nickName" :show-overflow-tooltip="true" />
        <el-table-column label="手机号码" align="center" prop="phonenumber" width="120" />
        <el-table-column label="身份" align="center" prop="loginIdentity" :formatter="loginIdentityFormatter" />
        <el-table-column label="公司/医院" align="center" prop="organizationName" />
        <el-table-column label="职称" align="center" prop="title" :formatter="titleFormatter" />
        <el-table-column label="课件数" align="center" prop="caseNumber" />
        <el-table-column label="关联医生" align="center" prop="doctorNumber" />
        <el-table-column label="状态" align="center" key="status">
          <template #default="scope">
            <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作" fixed="right" width="180" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top" v-if="scope.row.userId !== 1">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:user:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top" v-if="scope.row.userId !== 1">
              <el-button
                link
                type="primary"
                icon="Delete"
                :disabled="scope.row.status === '0' || scope.row.doctorNumber > 0"
                @click="handleDelete($event, scope.row)"
                v-hasPermi="['system:user:remove']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 表格 -->
      <!-- 分页 -->
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
      <!-- 分页 -->
    </el-card>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog ref="formDialogRef" :title="dialog.title" v-model="dialog.visible" :width="dialogWidth + 'px'" append-to-body @close="closeDialog">
      <el-form :model="form" :rules="rules" ref="userFormRef" label-width="100px">
        <el-form-item label="用户名称" prop="nickName">
          <el-input
            v-model="form.nickName"
            placeholder="请输入用户名称"
            maxlength="30"
            @input="(e) => (form.nickName = e.replace(/[^a-zA-Z0-9\u4E00-\u9FA5]/g, ''))"
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入手机号码" maxlength="11" />
        </el-form-item>
        <el-form-item label="用户身份" prop="loginIdentity">
          <el-select v-model="form.loginIdentity" placeholder="请选择用户身份" clearable style="width: 100%" :disabled="!canEdit">
            <el-option v-for="dict in sys_register_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="关联志愿者" prop="bindVolunteerList" v-if="form.loginIdentity == '0'" >
          <el-select v-model="form.bindVolunteerList" multiple placeholder="请选择志愿者" clearable style="width: 100%" :disabled="dialog.title != '新增用户'">
            <el-option v-for="dict in allVolunteerList" :key="dict.userId" :label="dict.userName" :value="dict.userId" />
          </el-select>
        </el-form-item>
        <el-form-item label="关联医生" prop="bindDoctorList" v-if="form.loginIdentity == '1'">
          <el-select v-model="form.bindDoctorList" multiple placeholder="请选择医生" clearable style="width: 100%" :disabled="dialog.title != '新增用户'">
            <el-option v-for="dict in allDoctorList" :key="dict.userId" :label="dict.userName" :value="dict.userId" />
          </el-select>
        </el-form-item>
        <el-form-item label="医院" prop="organizationName">
          <el-input
            v-model="form.organizationName"
            placeholder="请输入医院名称"
            maxlength="30"
            @input="(e) => (form.organizationName = e.replace(/[^a-zA-Z0-9\u4E00-\u9FA5]/g, ''))"
          />
        </el-form-item>
        <el-form-item label="职称" prop="title" v-if="form.loginIdentity != '1'">
          <el-select v-model="form.title" placeholder="请选择职称" clearable style="width: 100%">
            <el-option v-for="dict in sys_user_title" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="解析次数" prop="caseAnalysisTimes" v-if="form.loginIdentity == '0'">
          <el-input v-model="form.caseAnalysisTimes" type="number"/>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.value">{{
              dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div v-if="dialog.title == '修改用户'">
        <div>课件上传情况：</div>
        <el-table v-loading="caseTableLoading" :data="caseList" :cellStyle="cellStyle">
          <el-table-column label="课件名称" align="center" prop="caseName" />
          <el-table-column label="审核状态" align="center" prop="checkStatus" :formatter="checkStatusFormatter" v-if="form.loginIdentity != '2'" />
          <el-table-column label="点评状态" align="center" prop="commentStatus" v-if="form.loginIdentity == '2'" >
            <template #default="scope">
            {{scope.row.commentStatus === '0'?'已点评' :(scope.row.commentStatus === '1'?'待点评': '重新点评')}}
          </template>
          </el-table-column>
          <el-table-column label="点评分数" align="center" prop="commentScore" v-if="form.loginIdentity == '2'"/>
          <el-table-column label="点评内容" align="center" prop="commentContent" v-if="form.loginIdentity == '2'" show-overflow-tooltip  />
        </el-table>
        <pagination
          v-show="caseTotal > 0"
          :total="caseTotal"
          v-model:page="caseQueryParams.pageNum"
          v-model:limit="caseQueryParams.pageSize"
          @pagination="getCaseList"
        />
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel()">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或修改用户配置对话框 -->

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="1200px" append-to-body>
      <div class="import_dialog">
        <el-steps :active="active" finish-status="success" class="import_dialog_steps">
          <el-step title="上传文件" />
          <el-step title="确认导入" />
          <el-step title="导入成功" />
        </el-steps>
        <!-- 步骤1：下载模板文件或上传文件 -->
        <view v-if="active == 0">
          <el-form-item label="用户身份" style="width: 30%;margin-top: 20px;">
            <el-select v-model="uploadFileData.loginIdentity" placeholder="请选择用户身份" clearable >
              <el-option v-for="dict in sys_register_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-upload
            ref="uploadRef"
            accept=".xlsx, .csv"
            :headers="upload.headers"
            :action="upload.url"
            :before-upload="handleFileBeforeUpload"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :on-error="handleFileError"
            :disabled="upload.isUploading"
            :auto-upload="false"
            :limit="1"
            style="margin-top: 30px;"
            :data="uploadFileData"
          >
            <el-row align="middle" justify="center">
              <el-col :span="12" style="font-weight: 600;">上传文件</el-col>
              <el-col :span="12"><el-button type="primary">添加文件</el-button></el-col>
            </el-row>

            <template #tip>
              <div class="el-upload__tip" style="margin: 20px 25px;">
                <span style="line-height: 25px;"
                  >当前支持csv、xlsx格式文件（文件大小在10M以内且行数在10万以内,若超出限制,请分批导入），请使用office
                  2010及以上版本，否则可能出现乱码，必须严格按照模板内容填入客户数据，否则可能会出现导入异常</span
                >
                <el-link type="primary" style="font-size:14px;vertical-align: baseline;margin-left: 20px;" @click="importTemplate(1)"
                  >下载csv模板</el-link
                >
                <el-link type="primary" style="font-size:14px;vertical-align: baseline;margin-left: 20px;" @click="importTemplate(2)"
                  >下载excel模板</el-link
                >
              </div>
            </template>
          </el-upload>
        </view>

        <!-- 步骤1：下载模板文件或上传文件 -->

        <!-- 步骤2、3：获取上传文件的数据并筛选，导入数据 -->
        <div v-if="active == 1 || active == 2" style="margin-top: 40px;">
          <el-table v-loading="importTableLoading" :data="importUserList" height="50vh" :cellStyle="cellStyle">
            <el-table-column label="用户ID" align="center" prop="userCode" />
            <el-table-column label="用户名称" align="center" prop="nickName" />
            <el-table-column label="手机号码" align="center" prop="phonenumber" />
            <el-table-column label="身份" align="center" prop="loginIdentity" :formatter="loginIdentityFormatter" />
            <el-table-column label="公司/部门" align="center" prop="organizationName" />
            <el-table-column label="职称" align="center" prop="title" :formatter="titleFormatter" />
            <el-table-column label="解析次数" align="center" prop="caseAnalysisTimes" v-if="uploadFileData.loginIdentity == '0'"/>
            <el-table-column label="状态" align="center" prop="userStatus" :formatter="userStatusFormatter" />
            <el-table-column label="导入结果" align="center" prop="importStatus" :formatter="importStatusFormatter" v-if="active == 2" />
            <el-table-column label="操作" fixed="right" width="120" class-name="small-padding fixed-width" v-if="active == 1">
              <template #default="scope">
                <el-button type="danger" plain icon="Delete" @click="handleDeleteImport($event, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="importTotal > 0"
            :total="importTotal"
            v-model:page="importQueryParams.pageNum"
            v-model:limit="importQueryParams.pageSize"
            @pagination="getImportList"
          />
        </div>
        <!-- 步骤2、3：获取上传文件的数据并筛选，导入数据 -->
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="upload.open = false">取 消</el-button>
          <el-button type="primary" @click="submitFileForm">{{ btnName }}</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 用户导入对话框 -->
  </div>
</template>

<script setup name="User" lang="ts">
import api from "@/api/system/user"
import {CaseVO, ImportUserQuery, ImportUserVO, UserForm, UserQuery, UserVO, bindOption } from '@/api/system/user/types';
import { RoleVO } from "@/api/system/role/types";
import { PostVO } from "@/api/system/post/types";
import { to } from "await-to-js";
import { globalHeaders } from "@/utils/request";
import type { TableColumnCtx, UploadRawFile } from 'element-plus'
import { getTenantInfo } from "@/api/login";
import { tr } from "element-plus/es/locale";

const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance
const { sys_normal_disable, sys_user_title } = toRefs<any>(proxy?.useDict('sys_normal_disable', 'sys_user_title'));
const { _system_user_type_title, _system_user_type_identity } = toRefs<any>(proxy?.canSearchDict('/system/user/type/title', '/system/user/type/identity'));

const sys_register_type = ref<any>()

const userList = ref<UserVO[]>();
const loading = ref(true);
const showSearch = ref(true)
const ids = ref<Array<number | string>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const deptName = ref('');
const postOptions = ref<PostVO[]>([]);
const roleOptions = ref<RoleVO[]>([]);
/*** 用户导入参数 */
const upload = reactive<ImportOption>({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: ''
})

const active = ref<number>(0) //步骤条-已完成的步骤
const btnName = ref<string>("下一步") //提交按钮名称
const uploadFileData = ref<Record<string, any>>({loginIdentity:''})//上传文件时携带的数据
const importTableLoading = ref(true)//上传文件后表格的加载状态
const importUserList = ref<ImportUserVO[]>()//上传文件后查询得到的用户列表
const importQueryParams = ref<ImportUserQuery>({
  pageNum: 1,
  pageSize: 10,
  importBatch: ''
})  //上传文件后查询条件
const importTotal = ref(0);//上传文件后查询接口返回的数据总量


const caseTableLoading = ref(true)//用户对应的课件表格的加载状态
const caseList = ref<CaseVO[]>()//用户对应的课件列表
const caseQueryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
})  //用户对应的课件查询条件
const caseTotal = ref(0);//用户对应的课件查询接口返回的数据总量

const allDoctorList = ref<bindOption[]>()
const allVolunteerList = ref<bindOption[]>()


const deptTreeRef = ref<ElTreeInstance>();
const queryFormRef = ref<ElFormInstance>();
const userFormRef = ref<ElFormInstance>();
const uploadRef = ref<ElUploadInstance>();
const formDialogRef = ref<ElDialogInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const dialogWidth = ref(600)

const canEdit = ref(false)

const initFormData: UserForm = {
  userId: '',
  nickName: undefined,
  phonenumber: undefined,
  status: "0",
  organizationName: '',
  title: '',
  loginIdentity: '0',
  caseAnalysisTimes: '0',
  bindDoctorList:[],
  bindVolunteerList:[]
}
const data = reactive<PageData<UserForm, UserQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: '',
    title: '',
    loginIdentity: ''
  },
  rules: {
    nickName: [{ required: true, message: "用户名称不能为空", trigger: "blur" }],
    phonenumber: [{ required: true, message: "手机号不能为空", trigger: "blur" },
    { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }],
  }
})

const { queryParams, form, rules } = toRefs<PageData<UserForm, UserQuery>>(data)



//格式化身份
const loginIdentityFormatter = (row: UserVO, column: TableColumnCtx<UserVO>) => {
  if (sys_register_type) {
    let temp = sys_register_type.value.filter((item: { value: string; }) => item.value == row.loginIdentity)
    return temp[0] ? temp[0].label : row.title
  } else {
    return row.loginIdentity
  }
}

//格式化职称
const titleFormatter = (row: UserVO, column: TableColumnCtx<UserVO>) => {
  if (sys_user_title) {
    let temp = sys_user_title.value.filter((item: { value: string; }) => item.value == row.title)
    return temp[0] ? temp[0].label : row.title
  } else {
    return '/'
  }
}

//格式化批量导入-用户状态
const userStatusFormatter = (row: ImportUserVO, column: TableColumnCtx<ImportUserVO>) => {
  if (row.userStatus == '0') {
    return '新用户'
  } else if (row.userStatus == '1') {
    return '已存在'
  } else {
    return '未知'
  }
}

//格式化批量导入-导入结果
const importStatusFormatter = (row: ImportUserVO, column: TableColumnCtx<ImportUserVO>) => {
  if (row.importStatus == '0') {
    return '未导入'
  } else if (row.importStatus == '1') {
    return '导入成功'
  } else {
    return '未知'
  }
}

//批量导入-用户状态 文字颜色
const cellStyle = ({ row, column }) => {
  let userStatusStyle
  let importStatusStyle
  let controlStatusStyle
  switch (row.userStatus) {
    case '0':
      userStatusStyle = { 'color': '#67c23a' } // #0f0
      break;
    case '1':
      userStatusStyle = { 'color': '#f00' }
      break;
    default:
      userStatusStyle = { 'color': '#000' }
      break;
  }

  switch (row.importStatus) {
    case '0':
      importStatusStyle = { 'color': '#f00' }
      break;
    case '1':
      importStatusStyle = { 'color': '#67c23a' }
      break;
    default:
      importStatusStyle = { 'color': '#000' }
      break;
  }

  switch (row.commentStatus) {
    case '0':
      controlStatusStyle = { 'color': '#67c23a' }
      break;
    case '1':
    case '2':
      controlStatusStyle = { 'color': '#f00' }
      break;
    default:
      controlStatusStyle = { 'color': '#000' }
      break;
  }

  if (column.label == '状态') {
    return userStatusStyle
  } else if (column.label == '导入结果') {
    return importStatusStyle
  }else if (column.label == '点评状态') {
    return controlStatusStyle
  }
}

//格式化课件审核状态
const checkStatusFormatter = (row: CaseVO, column: TableColumnCtx<CaseVO>) => {
  if (row.checkStatus == '0') {
    return '未审核'
  } else if (row.checkStatus == '1') {
    return '通过'
  } else if (row.checkStatus == '2') {
    return '拒绝'
  } else {
    return '未知'
  }
}

/** 根据名称筛选部门树 */
watchEffect(
  () => { deptTreeRef.value?.filter(deptName.value); },
  {
    flush: 'post' // watchEffect会在DOM挂载或者更新之前就会触发，此属性控制在DOM元素更新后运行
  }
);

/** 查询用户列表 */
const getList = async () => {
  loading.value = true;
  const res = await api.listUser(queryParams.value);
  loading.value = false;
  userList.value = res.rows;
  total.value = res.total;
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getList()
}
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.pageNum = 1;
  deptTreeRef.value?.setCurrentKey(undefined);
  handleQuery();
}

/** 删除按钮操作 */
const handleDelete = async (event: any, row?: UserVO) => {
  let target = event.target;
  if (target.nodeName == "SPAN") {
    target = event.target.parentNode;
  }
  target.blur();

  if (Number(row?.caseNumber) > 0) {
    proxy?.$modal.msgWarning("该用户已上传课件，不可删除");
    return
  }
  const userIds = row?.userId || ids.value;
  const [err] = await to(proxy?.$modal.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？') as any);
  if (!err) {
    await api.delUser(userIds);
    await getList();
    proxy?.$modal.msgSuccess("删除成功");
  }
}

/** 用户状态修改  */
const handleStatusChange = async (row: UserVO) => {
  let text = row.status === "0" ? "启用" : "停用"
  try {
    await proxy?.$modal.confirm('确认要"' + text + '""' + row.userName + '"用户吗?');
    await api.changeUserStatus(row.userId, row.status);
    proxy?.$modal.msgSuccess(text + "成功");
  } catch (err) {
    row.status = row.status === "0" ? "1" : "0";
  }
}
/** 跳转角色分配 */
// const handleAuthRole = (row: UserVO) => {
//   const userId = row.userId;
//   router.push("/system/user-auth/role/" + userId);
// }

/** 选择条数  */
const handleSelectionChange = (selection: UserVO[]) => {
  ids.value = selection.map((item) => item.userId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 导入按钮操作 */
const handleImport = () => {
  uploadRef.value?.clearFiles();
  active.value = 0
  btnName.value = '下一步'
  importTableLoading.value = true
  importUserList.value = []
  importQueryParams.value.importBatch = ''
  importTotal.value = 0


  upload.title = "批量导入";
  upload.open = true;

}

/** 下载模板操作 */
const importTemplate = (type: number) => {
  let url = ''
  let fileType = ''
  if (type == 1) {
    url = '/business/importUser/importCsvTemplate'
    fileType = '.csv'
  } else if (type == 2) {
    url = '/business/importUser/importExcelTemplate'
    fileType = '.xlsx'
  }

  proxy?.download(url, {
  }, `user_template_${new Date().getTime()}${fileType}`);
}

/* 文件上传前处理 */
const handleFileBeforeUpload = (rawFile: UploadRawFile) => {
  let fileType = rawFile.name.substring(rawFile.name.lastIndexOf('.') + 1).toUpperCase()
  if (fileType == 'CSV') {
    upload.url = import.meta.env.VITE_APP_BASE_API + "/business/importUser/csvData"
  } else if (fileType == 'XLSX') {
    upload.url = import.meta.env.VITE_APP_BASE_API + "/business/importUser/excelData"
  } else {
    proxy?.$modal.msgError('选择的文件格式错误,请重新选择！');
    return false
  }
}

/**文件上传中处理 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};
const handleFileError = () => {
  upload.isUploading = false;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: UploadFile) => {
  console.log('上传成功:response===', response)
  console.log('上传成功:file===', file)
  upload.isUploading = false;
  if (response.code == '200') {
    proxy?.$modal.msgSuccess('文件上传成功')
    active.value = 1
    btnName.value = '确认'
    importQueryParams.value.importBatch = response.data.importBatch
    getImportList()
  } else {
    proxy?.$modal.msgError(response.msg || '文件上传失败，请重试')
  }
  // uploadRef.value?.handleRemove(file);
}

/** 查询批量导入用户列表 */
const getImportList = async () => {
  importTableLoading.value = true;
  const res = await api.importUserList(importQueryParams.value);
  importTableLoading.value = false;
  importUserList.value = res.rows;
  importTotal.value = res.total;
}

/** 批量导入表格-删除按钮操作 */
const handleDeleteImport = async (event: any, row: ImportUserVO) => {
  let target = event.target;
  if (target.nodeName == "SPAN") {
    target = event.target.parentNode;
  }
  target.blur();

  const userIds = row.userId
  const [err] = await to(proxy?.$modal.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？') as any);
  if (!err) {
    await api.delImportUser(userIds);
    await getImportList();
    proxy?.$modal.msgSuccess("删除成功");
  }
}

/* 提交批量导入的数据 */
const submitImportData = async (importBatch: string) => {
  await api.submitImportData(importBatch)
  active.value = 2
  importQueryParams.value.pageNum = 0
  await getImportList();
  proxy?.$modal.msgSuccess('用户导入成功')
}

/** 提交上传文件 */
function submitFileForm() {
  let step = active.value
  if (step == 0) {
    if(uploadFileData.value.loginIdentity == ''){
      proxy?.$modal.msgWarning('请先选择用户身份')
      return
    }
    uploadRef.value?.submit();
  } else if (step == 1) {
    //导入数据
    submitImportData(importQueryParams.value.importBatch)
  } else if (step == 2) {
    //完成数据导入
    upload.open = false
    getList();
  }
}

/** 查询批量导入用户列表 */
const getCaseList = async () => {
  caseTableLoading.value = true;
  const res = await api.caseList(caseQueryParams.value);
  caseTableLoading.value = false;
  caseList.value = [...res.rows];
  caseTotal.value = res.total;
}

/** 重置操作表单 */
const reset = () => {
  form.value = { ...initFormData };
  userFormRef.value?.resetFields();
}
/** 取消按钮 */
const cancel = () => {
  dialog.visible = false;
  reset();
}

/** 新增按钮操作 */
const handleAdd = async () => {
  reset();
  const { data } = await api.getUser();
  dialogWidth.value = 600
  dialog.visible = true;
  dialog.title = "新增用户";
  postOptions.value = data.posts;
  roleOptions.value = data.roles;
  canEdit.value = true
}
/** 修改按钮操作 */
const handleUpdate = async (row?: UserForm) => {
  reset();
  const userId = row?.userId || ids.value[0]
  const { data } = await api.getUser(userId)
  dialogWidth.value = 1000
  dialog.visible = true;
  dialog.title = "修改用户";
  Object.assign(form.value, data.user);
  postOptions.value = data.posts;
  roleOptions.value = data.roles;

  let id = row?.userId || ''
  if(row?.loginIdentity == '0'){
    caseQueryParams.value = {
      pageNum: 1,
      pageSize: 10,
      userId: id
    }
  }else if(row?.loginIdentity == '1'){
    caseQueryParams.value = {
      pageNum: 1,
      pageSize: 10,
      uploadUserId: id
    }
  }else if(row?.loginIdentity == '2'){
    caseQueryParams.value = {
      pageNum: 1,
      pageSize: 10,
      commentUserId: id
    }
  }
  caseTotal.value = 0
  caseList.value = []
  await getCaseList()

  try {
    if((data.user.bindDoctorList && data.user.bindDoctorList.length > 0)
    || (data.user.bindVolunteerList && data.user.bindVolunteerList.length > 0)
    || (caseList.value && caseList.value.length > 0)){
      canEdit.value = false
    }else{
      canEdit.value = true
    }
  } catch (error) {
    canEdit.value = true
  }
}

/** 提交按钮 */
const submitForm = () => {
  userFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      form.value.userId ? await api.updateUser(form.value) : await api.addUser(form.value);
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  })
}


/**
 * 关闭用户弹窗
 */
const closeDialog = () => {
  dialog.visible = false;
  resetForm();
}

/**
 * 重置表单
 */
const resetForm = () => {
  userFormRef.value?.resetFields();
  userFormRef.value?.clearValidate();

  form.value.status = '1';
}

const initData = async () => {
  const res = await getTenantInfo(localStorage.getItem("tenantId") || '')
  let authorizedLogin = res.data.authorizedLogin
  sys_register_type.value = []
  if (authorizedLogin.indexOf('0') != -1) {
    sys_register_type.value.push({ value: '0', label: '医生' })
  }
  if (authorizedLogin.indexOf('1') != -1) {
    sys_register_type.value.push({ value: '1', label: '志愿者' })
  }
  if (authorizedLogin.indexOf('2') != -1) {
    sys_register_type.value.push({ value: '2', label: '专家' })
  }
  api.getALLDoctorList().then(res =>{
    if(res.code == 200){
      allDoctorList.value = res.data
    }
  })

  api.getALLVolunteerList().then(res =>{
    if(res.code == 200){
      allVolunteerList.value = res.data
    }
  })
  getList()
}

onMounted(() => {
  initData()
});
</script>

<style lang="scss" scoped>
.import_dialog {
  box-sizing: border-box;
  padding: 15px 30px;
  width: 100%;
  height: 70vh;

  .import_dialog_steps {
    width: 60%;
    margin: 0 auto;
  }
}


:deep(.el-step__icon-inner) {
  height: 24px;
  line-height: 24px;
}

:deep(.el-step.is-horizontal .el-step__line) {
  width: calc(100% - 110px);
  left: 100px !important;
}

:deep(.el-step__head.is-wait) {
  color: #a8abb2;
  border-color: #a8abb2;

  .el-step__line {
    background: #a8abb2;
  }

  .el-step__title {
    color: #a8abb2;
  }
}

:deep(.el-step__head.is-process) {
  .el-step__icon {
    color: #fff;
    background-color: #409EFF;
    border-color: #409EFF;
  }

  .el-step__line {
    background: #a8abb2;
  }
}

:deep(.el-step__title.is-wait),
:deep(.el-step__title.is-process) {
  color: #a8abb2;
  font-weight: 400;
  font-size: 14px;
  line-height: 24px;
}

:deep(.el-step__title.is-success),
:deep(.el-step__title.is-process) {
  color: #000;
  font-weight: 400;
  line-height: 24px;
  font-size: 14px;
}

:deep(.el-step__head.is-success) {
  color: #409EFF;
  border-color: #409EFF;

  .el-step__line {
    background: #409EFF;
  }
}

:deep(.el-step__main) {
  position: absolute;
  left: 30px;
  top: 0;
  white-space: nowrap;
}
</style>
