<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="课件名称" prop="caseName">
            <el-input v-model="queryParams.caseName" placeholder="请输入课件名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <!-- <el-form-item label="课件所属用户id" prop="userId">
            <el-input v-model="queryParams.userId" placeholder="请输入课件所属用户id" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!-- <el-form-item label="课件上传用户id" prop="uploadUserId">
            <el-input
              v-model="queryParams.uploadUserId"
              placeholder="请输入课件上传用户id"
              clearable
              style="width: 240px"
              @keyup.enter="handleQuery"
            />
          </el-form-item> -->
          <!-- <el-form-item label="文件地址" prop="caseFileUrl">
            <el-input v-model="queryParams.caseFileUrl" placeholder="请输入文件地址" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!-- <el-form-item label="文件美化后地址" prop="caseBeautifyFileUrl">
            <el-input
              v-model="queryParams.caseBeautifyFileUrl"
              placeholder="请输入文件美化后地址"
              clearable
              style="width: 240px"
              @keyup.enter="handleQuery"
            />
          </el-form-item> -->
          <!-- <el-form-item label="课件描述" prop="caseDescription">
            <el-input v-model="queryParams.caseDescription" placeholder="请输入课件描述" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <el-form-item label="上传方式" prop="uploadType">
            <el-select v-model="queryParams.uploadType" placeholder="请选择上传方式" clearable @clear="handleQuery" @change="handleQuery">
              <el-option v-for="item in uploadTypeoptions" :key="item.id" :label="item.label" :value="item.id"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所有者" prop="userIds">
            <el-select v-model="userIds" multiple placeholder="请选择所有者" clearable @clear="handleQuery" @change="handleQuery">
              <el-option v-for="item in commentDoctorIdoptions" :key="item.userId" :label="item.userName" :value="item.userId"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="点评专家" prop="commentUserIds">
            <el-select v-model="commentUserIds" multiple placeholder="请选择点评专家" @clear="handleQuery" @change="handleQuery">
              <el-option v-for="item in commentExpertIdoptions" :key="item.userId" :label="item.userName" :value="item.userId"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery" @clear="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['business:caseBaseInfo:add']">课件上传</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['business:caseBaseInfo:edit']"
              >修改</el-button
            >
          </el-col> -->
          <!-- <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['business:caseBaseInfo:remove']"
              >删除</el-button
            >
          </el-col> -->
          <!-- <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['business:caseBaseInfo:export']">导出</el-button>
          </el-col> -->
          <!-- <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar> -->
        </el-row>
      </template>

      <el-table v-loading="loading" :data="caseBaseInfoList" :cellStyle="cellStyle">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column label="课件编号" align="center" prop="caseId" v-if="true" />
        <el-table-column label="课件名称" align="center" prop="caseName" />
        <el-table-column label="项目" align="center" prop="projectName" />
        <el-table-column label="所有者" align="center" prop="userName" />
        <el-table-column label="上传方式" align="center" prop="uploadType">
          <template #default="scope">
            {{scope.row.uploadType === '0'?'直接上传' :'志愿者上传'}}
          </template>
        </el-table-column>
        <el-table-column label="上传人" align="center" prop="uploadUserName" />
        <el-table-column label="审核状态" align="center" prop="checkStatus" v-if="caseReviewFiled == '0'">
          <template #default="scope">
            {{scope.row.checkStatus === '0'?'未审核' :(scope.row.checkStatus === '1'?'通过': '拒绝')}}
          </template>
        </el-table-column>
        <el-table-column label="是否已美化" align="center" prop="beautifyStatus" v-if="caseReviewFiled == '0'">
          <template #default="scope">
            {{scope.row.beautifyStatus === '0'?'否' :'是'}}
          </template>
        </el-table-column>
        <el-table-column label="点评专家" align="center" prop="commentUseName" v-if="caseCommentFiled == '0'" />
        <el-table-column label="状态" align="center" prop="caseStatus">
          <template #default="scope">
            {{scope.row.caseStatus === '0'?'正常' :'禁用'}}
          </template>
        </el-table-column>
        <!-- <el-table-column label="课件所属用户id" align="center" prop="userId" /> -->
        <!-- <el-table-column label="课件上传用户id" align="center" prop="uploadUserId" /> -->
        <!-- <el-table-column label="文件地址" align="center" prop="caseFileUrl" />
        <el-table-column label="文件美化后地址" align="center" prop="caseBeautifyFileUrl" /> -->
        <!-- <el-table-column label="课件描述" align="center" prop="caseDescription" />
        <el-table-column label="点评专家ID" align="center" prop="commentUserId" /> -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
          <template #default="scope">
            <el-tooltip content="查看" placement="top">
              <!--  icon="View" -->
              <el-button link type="primary" @click="handleDetail(scope.$index)" style="font-size: 12px;" v-hasPermi="['business:caseBaseInfo:query']"
                >查看</el-button
              >
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <!--  icon="Edit" -->
              <el-button @click="handleUpdate(scope.row)" link type="primary" style="font-size: 12px;" v-hasPermi="['business:caseBaseInfo:edit']"
                >修改</el-button
              >
            </el-tooltip>
            <el-tooltip :content="scope.row.caseStatus === '0'?'禁用' :'启用'" placement="top">
              <!--  icon="CircleCheck" -->
              <el-button
                @click="handleDisable($event, scope.row)"
                link
                type="primary"
                style="font-size: 12px;"
                v-hasPermi="['business:caseBaseInfo:changeStatus']"
                >{{scope.row.caseStatus === '0'?'禁用' :'启用' }}</el-button
              >
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <!--  icon="Delete" -->
              <el-button
                @click="handleDelete($event, scope.row)"
                v-hasPermi="['business:caseBaseInfo:remove']"
                :disabled="scope.row.caseStatus === '0'"
                link
                type="primary"
                style="font-size: 12px;"
                >删除</el-button
              >
            </el-tooltip>
            <!-- <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['business:caseBaseInfo:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['business:caseBaseInfo: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 :title="dialog.title" v-model="dialog.visible" width="700px" append-to-body>
      <el-form ref="caseBaseInfoFormRef" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="课件所属用户id" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入课件所属用户id" />
        </el-form-item> -->
        <!-- <el-form-item label="课件上传用户id" prop="uploadUserId">
          <el-input v-model="form.uploadUserId" placeholder="请输入课件上传用户id" />
        </el-form-item> -->
        <el-form-item label="课件名称" prop="caseName">
          <el-input
            v-model="form.caseName"
            maxlength="30"
            placeholder="请输入课件名称"
            @input="(e) => (form.caseName = e.replace(/[^a-zA-Z0-9\u4E00-\u9FA5\,\.\-]/g, ''))"
          />
        </el-form-item>
        <el-form-item label="项目名称" prop="caseName">
          <el-input
            v-model="form.projectName"
            maxlength="30"
            placeholder="请输入项目名称"
            @input="(e) => (form.projectName = e.replace(/[^a-zA-Z0-9\u4E00-\u9FA5\,\.\-]/g, ''))"
          />
        </el-form-item>
        <el-form-item label="所有者" prop="userId" v-if="loginIdentity != '0'">
          <el-select v-model="form.userId" placeholder="请选择所有者" style="width:100%">
            <el-option v-for="item in commentDoctorIdoptions" :key="item.userId" :label="item.userName" :value="item.userId"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文件上传" prop="caseFileList">
          <!-- :disabled="upload.isUploading" -->
          <el-upload
            class="upload-demo"
            drag
            :on-remove="handleRemove"
            :headers="upload.headers"
            v-model:file-list="form.caseFileList"
            :action="upload.url"
            multiple
            :limit="5"
            :on-success="handleFileSuccess"
            :on-exceed="handleExceed"
            :before-upload="checkFileType"
            :on-error="handleFileError"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">支持扩展名：.pdf .MP4 .doc .docx .jpg .ppt .pptx等文件</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="美化文件上传" prop="caseBeautifyFileList" v-if="form.id">
          <!-- :disabled="upload.isUploading" -->
          <el-upload
            class="upload-demo"
            drag
            :on-remove="handleRemove"
            :headers="upload.headers"
            v-model:file-list="form.caseBeautifyFileList"
            :action="upload.url"
            multiple
            :limit="5"
            :on-success="handleFileSuccess"
            :on-exceed="handleExceed"
            accept=".pptx,.ppt"
            :before-upload="checkFileType"
            :on-error="handleFileError"
          >
            <!-- accept=".pdf ,.MP4, .doc, .docx ,.pdf ,.jpg ,.ppt,.pptx" -->
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <!-- <div class="el-upload__tip" slot="tip">支持扩展名：.pdf .MP4 .doc .docx .pdf .jpg .ppt .pptx</div> -->
            <div class="el-upload__tip" slot="tip">支持扩展名：.pptx .ppt</div>
          </el-upload>
        </el-form-item>
        <!-- <el-form-item label="文件地址" prop="caseFileUrl">
          <el-input v-model="form.caseFileUrl" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="文件美化后地址" prop="caseBeautifyFileUrl">
          <el-input v-model="form.caseBeautifyFileUrl" placeholder="请输入文件美化后地址" />
        </el-form-item>
        <el-form-item label="课件描述" prop="caseDescription">
          <el-input v-model="form.caseDescription" placeholder="请输入课件描述" />
        </el-form-item>
        <el-form-item label="点评专家ID" prop="commentUserId">
          <el-input v-model="form.commentUserId" placeholder="请输入点评专家ID" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" :disabled="upload.isUploading" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看课件详情对话框 -->
    <el-dialog :title="detaildialog.title" v-model="detaildialog.visible" width="800px" append-to-body>
      <div class="view_url">
        <el-row :gutter="20">
          <el-col :span="6" class="text_left">课件名称：</el-col>
          <el-col :span="18" class="text_right">{{ caseBaseInfoList[viewUrlIndex].caseName }}</el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6" class="text_left">项目名称：</el-col>
          <el-col :span="18" class="text_right">{{ caseBaseInfoList[viewUrlIndex].projectName }}</el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6" class="text_left">所有者：</el-col>
          <el-col :span="18" class="text_right">{{ caseBaseInfoList[viewUrlIndex].userName }}</el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6" class="text_left">上传方式：</el-col>
          <el-col :span="18" class="text_right">{{ caseBaseInfoList[viewUrlIndex].uploadType === '0' ? '直接上传' :'志愿者上传'}}</el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6" class="text_left">上传人：</el-col>
          <el-col :span="18" class="text_right">{{ caseBaseInfoList[viewUrlIndex].uploadUserName }}</el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6" class="text_left">已上传课件：</el-col>
          <el-col :span="18" class="text_right" style="flex-direction: column;">
            <div
              v-for="(item, index) in caseBaseInfoList[viewUrlIndex].caseFileList"
              :key="index"
              style="display:flex;align-items:center;margin-top: 10px;"
            >
              <div>{{item.name}}</div>
              <div style="margin-left:40px;cursor: pointer;color: blue;}" @click="downInfo(item.ossId)">下载</div>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6" class="text_left">美化课件：</el-col>
          <el-col :span="18" style="padding-top:10px; flex-direction: column;">
            <div
              v-for="(item, index) in caseBaseInfoList[viewUrlIndex].caseBeautifyFileList"
              :key="index"
              style="margin-top:10px;display:flex;align-items:center"
            >
              <div>{{item.name}}</div>
              <div style="margin-left:40px;cursor: pointer;color: blue;}" @click="downInfo(item.ossId)">下载</div>
            </div>
          </el-col>
        </el-row>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="hideViewUrlDialog">确 定</el-button>
          <el-button @click="hideViewUrlDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CaseBaseInfo" lang="ts">
import api from "@/api/login"
import {
  listCaseBaseInfo,
  getCaseBaseInfo,
  delCaseBaseInfo,
  addCaseBaseInfo,
  updateCaseBaseInfo,
  listExpert,
  listDoctor
} from '@/api/business/caseBaseInfo';
import { CaseBaseInfoVO, CaseBaseInfoQuery, CaseBaseInfoForm, Doctoroption } from '@/api/business/caseBaseInfo/types';
import { globalHeaders } from '@/utils/request';
import { UploadFileVO } from '@/api/system/tenant/types';
import { UploadFiles } from "element-plus";
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const caseBaseInfoList = ref<CaseBaseInfoVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);

const userIds = ref<Array<string | number>>([]);
const commentUserIds = ref<Array<string | number>>([]);
const total = ref(0);
const commentDoctorIdoptions = ref<Doctoroption[]>([]);
const commentExpertIdoptions = ref<Doctoroption[]>([]);
const viewUrlIndex = ref(-1);
const queryFormRef = ref<ElFormInstance>();
const caseBaseInfoFormRef = ref<ElFormInstance>();
const tenantId = ref(localStorage.getItem("tenantId")||'');
const caseCommentFiled = ref('0');
const caseReviewFiled = ref('0');

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

const detaildialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const loginIdentity = localStorage.getItem('loginIdentity');

const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadImgUrl = ref(baseUrl + '/resource/oss/upload'); // 上传的图片服务器地址
const uploadTypeoptions = [
  { id: '0', label: '直接上传' },
  { id: '1', label: '志愿者上传' }
];
const initFormData: CaseBaseInfoForm = {
  id: undefined,
  userId: undefined,
  uploadUserId: undefined,
  caseName: undefined,
  caseFileUrl: undefined,
  caseStatus: undefined,
  caseBeautifyFileUrl: undefined,
  checkStatus: undefined,
  caseDescription: undefined,
  beautifyStatus: undefined,
  uploadType: undefined,
  commentUserId: undefined,
  caseFileList: undefined,
  caseBeautifyFileList:undefined
};

const data = reactive<PageData<CaseBaseInfoForm, CaseBaseInfoQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: undefined,
    userIds: undefined,
    commentUserIds: undefined,
    uploadUserId: undefined,
    caseName: undefined,
    caseFileUrl: undefined,
    caseBeautifyFileUrl: undefined,
    checkStatus: undefined,
    caseDescription: undefined,
    beautifyStatus: undefined,
    uploadType: undefined,
    commentUserId: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '主键不能为空', trigger: 'blur' }],
    userId: [{ required: true, message: '所有者不能为空', trigger: 'change' }],
    uploadUserId: [{ required: true, message: '课件上传用户id不能为空', trigger: 'blur' }],
    caseName: [{ required: true, message: '课件名称不能为空', trigger: 'blur' }],
    caseFileList: [{ required: true, message: '文件不能为空', trigger: 'change' }]
    // caseBeautifyFileUrl: [{ required: true, message: '文件美化后地址不能为空', trigger: 'blur' }],
    // checkStatus: [{ required: true, message: '审核状态不能为空', trigger: 'change' }],
    // caseDescription: [{ required: true, message: '课件描述不能为空', trigger: 'blur' }],
    // beautifyStatus: [{ required: true, message: '美化状态 0否 1是不能为空', trigger: 'change' }],
    // uploadType: [{ required: true, message: '上传方式 0直接上传 1志愿者上传不能为空', trigger: 'change' }],
    // commentUserId: [{ required: true, message: '点评专家ID不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

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

const upload = reactive<ImportOption>({
  open: false,
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload'
});

const hideViewUrlDialog = () => {
  detaildialog.visible = false;
};

const checkFileType = (file?: any) => {
  const fileName = file.name;
  const fileType = fileName.substring(fileName.lastIndexOf('.'));
  console.log(fileType, 'fileType');
  let arr = ['.pptx','.ppt', '.pdf', '.doc', '.docx', '.txt', '.xls', '.xlsx', '.jpg', '.png', '.mp4', '.avi', '.mp3']
  if (arr.indexOf(fileType) == -1) {
    proxy?.$modal.msgError('上传文件格式错误');
    return false;
  }
  upload.isUploading = true
};

/** 文件上传失败 */
const handleFileError = () => {
  upload.isUploading = false
}

/** 查询课件基础信息列表 */
const getList = async () => {
  console.log('Into getList');

  loading.value = true;
  const res = await listCaseBaseInfo(queryParams.value);
  caseBaseInfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 获取点评专家列表 */
const getexpertList = async () => {
  const res = await listExpert();
  commentExpertIdoptions.value = res.data;

};

/** 获取医生列表 */
const getdoctorList = async () => {
  const res = await listDoctor();
  commentDoctorIdoptions.value = res.data;
};

const downInfo = (ossId: string) => {
  // window.open(url.replace('http', 'https'));
  proxy?.$download.oss(ossId)
};
/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  caseBaseInfoFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  queryParams.value.userIds = userIds.value.join(',')
  queryParams.value.commentUserIds = commentUserIds.value.join(',')
  getList();
};
const handleRemove = (file: UploadFile, uploadFiles: UploadFiles) => {
  proxy?.$modal.msgSuccess("文件删除成功");
};
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  userIds.value = []
  commentUserIds.value = []
  handleQuery();
};

/** 文件个数超出限制*/
const handleExceed = () => {
  upload.isUploading = false;
  proxy?.$modal.msgWarning('只支持上传5个文件');
};

const handleFileSuccess = (response: any, file: UploadFile, uploadFiles: UploadFiles) => {
  console.log('上传成功:response===', response);
  console.log('上传成功:file===', file);
  console.log('form==',form.value)
  upload.isUploading = false;
  if(!form.value.caseName){
    let name = form.value.caseFileList[0].name
    form.value.caseName = name.substring(0,name.lastIndexOf('.'))
  }
  if(form.value.caseFileList){
    form.value.caseFileList = form.value.caseFileList.filter( (item:any) => !item?.response?.code||item?.response?.code == '200')
  }
  if(form.value.caseBeautifyFileList){
    form.value.caseBeautifyFileList = form.value.caseBeautifyFileList.filter( (item:any) => !item?.response?.code||item?.response?.code == '200')
  }
  if (response.code == '200') {
    proxy?.$modal.msgSuccess('文件上传成功');
  } else {
    proxy?.$modal.msgError('文件上传失败，请重试');
  }
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加课件基础信息';
};
// 查看详情

const handleDetail = (index: any) => {
  viewUrlIndex.value = index;
  detaildialog.title = '课件详情';
  detaildialog.visible = true;
};
/** 修改按钮操作 */
const handleUpdate = async (row?: CaseBaseInfoVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getCaseBaseInfo(_id);
  if (!res.data.caseFileList) {
    res.data.caseFileList = [];
  }
  if (!res.data.caseBeautifyFileList) {
    res.data.caseBeautifyFileList = [];
  }
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改课件基础信息';
};

/** 禁用启用按钮操作 */
const handleDisable = async (event:any, row?: CaseBaseInfoVO) => {
  let target = event.target;
  if(target.nodeName == "SPAN"){
   target = event.target.parentNode;
  }
  target.blur();

  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm(row?.caseStatus === '0' ? '是否确认禁用课件？' : '是否确认启用课件？').finally(() => (loading.value = false));
  let params = {
    id: row?.id,
    caseStatus: row?.caseStatus === '0' ? '1' : '0'
  };
  await updateCaseBaseInfo(params).finally(() => (buttonLoading.value = false));
  proxy?.$modal.msgSuccess(row?.caseStatus === '0' ? '禁用成功' : '启用成功');
  await getList();
};
// 判断名称
const checkName = (val:any) => {
  let judge = true
  let str = '^[\a-zA-Z\u4E00-\u9FA5]+$'
  var reg = new RegExp(str);
  judge = reg.test(val)
  if(val.length > 30){
    judge = false
  }
  return judge
};
/** 课件提交按钮 */
const submitForm = () => {
  caseBaseInfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (!form.value.caseFileList || form.value.caseFileList.length == 0) {
        proxy?.$modal.msgError('请上传文件');
        return;
      } else {
        let tempArr: { name: any; url: any; ossId: any }[] = [];
        form.value.caseFileList.forEach((element:any) => {
          if (element.response) {
            let tempVO = element.response as any;
            tempArr.push({
              name: tempVO.data.name,
              url: tempVO.data.url,
              ossId: tempVO.data.ossId
            });
          } else {
            tempArr.push({
              name: element.name,
              url: element.url,
              ossId: element.ossId
            });
          }
        });
        console.log(tempArr, 'tempArr');
        form.value.caseFileList = tempArr;
      }
      if(form.value.caseBeautifyFileList && form.value.caseBeautifyFileList.length > 0){
        let tempArr2: { name: any; url: any; ossId: any }[] = [];
        form.value.caseBeautifyFileList.forEach((element:any) => {
          if (element.response) {
            let tempVO = element.response as any;
            tempArr2.push({
              name: tempVO.data.name,
              url: tempVO.data.url,
              ossId: tempVO.data.ossId
            });
          } else {
            tempArr2.push({
              name: element.name,
              url: element.url,
              ossId: element.ossId
            });
          }
        });
        console.log(tempArr2, 'tempArr2');
        form.value.caseBeautifyFileList = tempArr2;
      }

      delete form.value.createTime;
      buttonLoading.value = true;
      if (form.value.id) {
        form.value.beautifyStatus = undefined
        form.value.checkStatus = undefined
        await updateCaseBaseInfo(form.value).finally(() => (buttonLoading.value = false));
      } else {
        //  课件新增信息
        form.value.uploadUserId = localStorage.getItem('userId') || '';
        form.value.userId = loginIdentity !== '0' ? form.value.userId : localStorage.getItem('userId') || '';
        console.log(form.value, 'fileList.value');
        form.value.caseStatus = '0';
        form.value.checkStatus = '0';
        form.value.uploadType = window.localStorage.getItem('loginIdentity') === '1' ? '1' : '0';
        await addCaseBaseInfo(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('修改成功');
      dialog.visible = false;
      await getList();
    }
  });
};

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

  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除课件').finally(() => (loading.value = false));
  await delCaseBaseInfo(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'business/caseBaseInfo/export',
    {
      ...queryParams.value
    },
    `caseBaseInfo_${new Date().getTime()}.xlsx`
  );
};

const initData = async () =>{
  const res = await api.getTenantInfo(tenantId.value || '')
  if(res.data){
   let {caseComment,caseReview} = res.data
   caseCommentFiled.value = caseComment
   caseReviewFiled.value = caseReview
  }
  getList();
  getexpertList();
  getdoctorList();
}

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

<style lang="scss" scoped>
.upload-demo {
  width: 100%;
}
.view_url {
  box-sizing: border-box;
  padding: 15px 30px;
  .text_left {
    font-size: 16px;
    font-weight: 600;
    color: black;
    margin-top: 15px;
  }

  .text_right {
    margin-top: 15px;
    // color: blue;
    // text-decoration: underline;
    display: flex;

    .text_right_icon {
      margin-left: 10px;
    }
  }
}
</style>
