<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="课件状态" prop="checkStatus">
            <el-select v-model="queryParams.checkStatus" placeholder="全部状态" clearable @clear="handleQuery" @change="handleQuery">
              <el-option v-for="item in _business_caseBaseInfo_type_caseReviewStatus" :key="item.value" :label="item.label" :value="item.value">
              </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>
            <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">
      <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="createTime" />
        <el-table-column label="状态" align="center" prop="checkStatus">
          <template #default="scope">
            {{scope.row.checkStatus === '0'?'未审核' :(scope.row.checkStatus === '1'?'审核通过': '审核未通过')}}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="285">
          <template #default="scope">
            <!-- 0未审核 1通过 2拒绝 -->
            <el-tooltip content="通过" placement="top">
              <!--  icon="Circle-check" -->
              <el-button
                link
                type="primary"
                v-hasPermi="['business:auditBaseInfo:pass']"
                :disabled="scope.row.checkStatus == '1'"
                style="font-size: 12px;"
                @click="handlePass($event, scope.row)"
                >通过</el-button
              >
            </el-tooltip>
            <el-tooltip content="拒绝" placement="top">
              <!--  icon="Circle-close" -->
              <el-button
                link
                type="primary"
                v-hasPermi="['business:auditBaseInfo:reject']"
                :disabled="scope.row.checkStatus == '2'"
                style="font-size: 12px;"
                @click="handleRefuse(scope.row)"
                >拒绝</el-button
              >
            </el-tooltip>
            <el-tooltip content="下载" placement="top">
              <!--  icon="Download" -->
              <el-button
                link
                type="primary"
                v-hasPermi="['business:auditBaseInfo:download']"
                @click="handleDown(scope.$index)"
                style="font-size: 12px;"
                >下载</el-button
              >
            </el-tooltip>
            <el-tooltip :content="scope.row.checkStatus === '2'?'查看原因' :'上传美化'" placement="top">
              <!-- <el-button @click="handleBeautify(scope.row, scope.$index)" link type="primary" icon="Opportunity"></el-button> -->
              <el-button
                @click="handleBeautify(scope.row, scope.$index)"
                style="font-size: 12px;"
                link
                type="primary"
                :disabled="scope.row.checkStatus == '0'"
                v-hasPermi="['business:auditBaseInfo:upload']"
                >{{ scope.row.checkStatus === '2'?'查看原因' :'上传美化'}}</el-button
              >
            </el-tooltip>
            <el-tooltip content="通知下载" placement="top">
              <!--  icon="Download" -->
              <el-button link type="primary" @click="handleNoticeDown(scope.row)" style="font-size: 12px;">通知下载</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>
    <!-- 美化ppt对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="800px" append-to-body>
      <el-form ref="caseBaseInfoFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文件上传" prop="caseBeautifyFileList">
          <!--  :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
            :on-success="handleFileSuccess"
            :before-upload="checkFileType"
            :on-error="handleFileError"
            accept=".pptx ,.ppt"
            v
          >
            <!-- accept=".pdf ,.MP4, .doc, .docx ,.pptx ,.jpg ,.ppt" -->
            <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 .pptx .jpg .ppt</div> -->
            <div class="el-upload__tip" slot="tip">支持扩展名：.pptx .ppt</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" :disabled="upload.isUploading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审核不通过课件对话框 -->
    <el-dialog :title="refusedialog.title" v-model="refusedialog.visible" width="800px" append-to-body>
      <div class="view_url">
        <div style="margin-bottom:40px;">确认课件无法通过审核请填写未通过原因及修改意见</div>
        <el-input
          type="textarea"
          placeholder="请填写修改意见及未通过原因"
          maxlength="200"
          show-word-limit
          v-model="form.rejectReason"
          @input="(e) => (form.rejectReason = e.replace(/[^a-zA-Z0-9\u4E00-\u9FA5\,\.\。\，\-\s]/g, ''))"
        />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="hideViewUrlDialog">取 消</el-button>
          <el-button type="primary" @click="refusesubmitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审核不通过课件详情对话框 -->
    <el-dialog :title="refusedetaildialog.title" v-model="refusedetaildialog.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].rejectReason }}</el-col>
        </el-row>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="hidedetailViewUrlDialog">取 消</el-button>
          <el-button type="primary" @click="hidedetailViewUrlDialog">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 下载课件对话框 -->
    <el-dialog :title="downdialog.title" v-model="downdialog.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" style="display: flex;flex-wrap: wrap;">
            <div
              v-for="(item, index) in caseBaseInfoList[downviewUrlIndex].caseFileList"
              :key="index"
              style="display:flex;align-items:center;margin-right: 35px;margin-bottom: 10px;"
            >
              <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 @click="hidedownViewUrlDialog">取 消</el-button>
          <el-button type="primary" @click="hidedownViewUrlDialog">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <!--通知下载美化文件-->
    <el-dialog :title="noticeDownDialog.title" v-model="noticeDownDialog.visible" width="800px" append-to-body>
      <div class="view_url">
        <el-row :gutter="20">
          <div class="notice-tips">请复制下方通知信息发送项目群提醒医生下载文件</div>
          <el-col :span="24">
            <div class="text-wrap">
              <el-input type="textarea" :rows="5" placeholder="请输入内容" v-model="beautifyNotice"></el-input>
              <!--<el-icon class="el-icon-document-copy copy-btn" style="width:20px;height:20px;"></el-icon>-->
              <svg-icon icon-class="clipboard" @click="copyTextSuccess"></svg-icon>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="CaseBaseInfo" lang="ts">
import { copyText } from 'vue3-clipboard'
import { ChecklistCaseBaseInfo, getCaseBaseInfo, updateCaseBaseInfo, listExpert, listDoctor, getBeautifyNotice } from '@/api/business/caseBaseInfo';
import { CaseBaseInfoVO, CaseBaseInfoQuery, CaseBaseInfoForm, Doctoroption } from '@/api/business/caseBaseInfo/types';
import { globalHeaders } from '@/utils/request';
import { UploadFiles } from 'element-plus';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { _business_caseBaseInfo_type_caseReviewStatus } = toRefs<any>(proxy?.canSearchDict('/business/caseBaseInfo/type/caseReviewStatus'));

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 total = ref(0);
const commentDoctorIdoptions = ref<Doctoroption[]>([]);
const viewUrlIndex = ref(-1);
const downviewUrlIndex = ref(-1);
const queryFormRef = ref<ElFormInstance>();
const caseBaseInfoFormRef = ref<ElFormInstance>();

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

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

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

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

const noticeDownDialog = reactive<DialogOption>({
  visible:false,
  title:'通知下载美化文件'
})

const beautifyNotice = ref()

const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadImgUrl = ref(baseUrl + '/resource/oss/upload'); // 上传的图片服务器地址

const initFormData: CaseBaseInfoForm = {
  id: undefined,
  userId: undefined,
  uploadUserId: undefined,
  caseName: undefined,
  caseFileUrl: undefined,
  caseStatus: undefined,
  caseBeautifyFileUrl: undefined,
  caseBeautifyFileList: undefined,
  checkStatus: undefined,
  caseDescription: undefined,
  beautifyStatus: undefined,
  uploadType: undefined,
  commentUserId: undefined,
  caseFileList: undefined,
  rejectReason: undefined
};

const data = reactive<PageData<CaseBaseInfoForm, CaseBaseInfoQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: undefined,
    userIds: undefined,
    uploadUserId: undefined,
    caseName: undefined,
    caseFileUrl: undefined,
    caseBeautifyFileUrl: undefined,
    checkStatus: undefined,
    caseDescription: undefined,
    beautifyStatus: undefined,
    uploadType: undefined,
    commentUserId: undefined,
    commentUserIds: 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' }],
    caseBeautifyFileList: [{ 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.checkStatus) {
    case '1':
      controlStatusStyle = { 'color': '#67c23a' }
      break;
    case '2':
      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 copyTextSuccess = () => {
  if (beautifyNotice.value) {
    copyText(beautifyNotice.value, undefined, (error: any) => {
      if (error) {
        ElMessage.error('复制失败！');
      } else {
        ElMessage.success('复制成功！');
      }
    });


  }
}

const hideViewUrlDialog = () => {
  refusedialog.visible = false;
};
const hidedetailViewUrlDialog = () => {
  refusedetaildialog.visible = false;
};
const hidedownViewUrlDialog = () => {
  downdialog.visible = false;
};
/** 文件上传失败 */
const handleFileError = () => {
  upload.isUploading = false
}
const checkFileType = (file?: any) => {
  const fileName = file.name;
  const fileType = fileName.substring(fileName.lastIndexOf('.'));
  console.log(fileType, 'fileType');
  let arr = ['.pptx','.ppt']
  if (arr.indexOf(fileType) == -1) {
    proxy?.$modal.msgError('上传文件格式错误');
    return false;
  }
  upload.isUploading = true
  // if (fileType != ('.pdf' || '.MP4' || '.doc' || '.docx' || '.pdf' || '.jpg' || '.ppt' || '.word')) {
  //   proxy?.$modal.msgError('上传文件格式错误');
  //   return false;
  // }
};
/** 查询课件基础信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await ChecklistCaseBaseInfo(queryParams.value);
  caseBaseInfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
  console.log(loading.value);
};

const downInfo = (ossId: string) => {
  // window.open(url.replace('http', 'https'));
  proxy?.$download.oss(ossId)
};

/** 获取点评专家列表 */
const getexpertList = () => {
  const res = listExpert();
};

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

/** 取消按钮 */
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(',')
  getList();
};
const handleRemove = (file: UploadFile, uploadFiles: UploadFiles) => {
  proxy?.$modal.msgSuccess("文件删除成功");
};
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  userIds.value = []
  handleQuery();
};

const handleFileSuccess = (response: any, file: UploadFile, uploadFiles: UploadFiles) => {
  console.log('上传成功:response===', response);
  console.log('上传成功:file===', file);
  console.log('uploadFiles',uploadFiles)
  upload.isUploading = false;
  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 handleRefuse = async (row?: CaseBaseInfoVO) => {
  const _id = row?.id || ids.value[0];
  const res = await getCaseBaseInfo(_id);
  Object.assign(form.value, res.data);
  refusedialog.title = '审核拒绝';
  refusedialog.visible = true;
};

/** 拒绝课件操作按钮 */
const refusesubmitForm = async () => {
  if(!form.value.rejectReason){
    proxy?.$modal.msgWarning('请填写未通过原因及修改意见');
    return
  }
  await proxy?.$modal.confirm('是否拒绝课件？').finally(() => (loading.value = false));
  let params = {
    id: form.value.id,
    rejectReason: form.value.rejectReason,
    checkStatus: '2'
  };
  await updateCaseBaseInfo(params).finally(() => (buttonLoading.value = false));
  proxy?.$modal.msgSuccess('拒绝成功');
  refusedialog.visible = false;
  await getList();
};

/** 美化按钮操作 */
const handleBeautify = async (row: CaseBaseInfoVO, index: any) => {
  if (row?.checkStatus === '2') {
    viewUrlIndex.value = index;
    refusedetaildialog.title = '审核拒绝原因详情';
    refusedetaildialog.visible = true;
  } else {
    const _id = row?.id || ids.value[0];
    const res = await getCaseBaseInfo(_id);
    if (!res.data.caseBeautifyFileList) {
      res.data.caseBeautifyFileList = [];
    }
    Object.assign(form.value, res.data);
    dialog.visible = true;
    dialog.title = '美化PPT';
  }
};

/** 下载按钮操作 */
const handleDown = async (index: any) => {
  downviewUrlIndex.value = index;
  downdialog.title = '已上传课件';
  downdialog.visible = true;
};

const handleNoticeDown = async (row?: CaseBaseInfoVO) =>{
  const _id = row?.id || ids.value[0]
  const res = await getBeautifyNotice(_id)
  if(Number(res.data?.beautifyFileDownload) > 0){
    beautifyNotice.value = `${res.data.projectName}已有${res.data.caseNumber}位医生完成课件上传\r\n${res.data.beatifyCaseNumber}位老师上传内容已美化\r\n${res.data.userName}老师已下载美化文件\r\n手机下载请点击：${res.data.appUrl}\r\n电脑下载请点击：${res.data.pcUrl}`
  }else {
    beautifyNotice.value = `${res.data.projectName}已有${res.data.caseNumber}位医生完成课件上传\r\n${res.data.beatifyCaseNumber}位老师上传内容已美化\r\n请未下载美化文件的${res.data.userName}老师登录系统下载课件，谢谢\r\n手机下载请点击：${res.data.appUrl}\r\n电脑下载请点击：${res.data.pcUrl}\r\n${res.data.userName}老师可点击上方链接快速进入系统，下载已美化课件`
  }
  noticeDownDialog.visible = true
};

/** 通过课件操作按钮 */
const handlePass = async (event:any, row?: CaseBaseInfoVO) => {
  let target = event.target;
  if(target.nodeName == "SPAN"){
   target = event.target.parentNode;
  }
  target.blur();

  await proxy?.$modal.confirm('是否通过课件？').finally(() => (loading.value = false));
  let params = {
    id: row?.id,
    checkStatus: '1'
  };
  await updateCaseBaseInfo(params).finally(() => (buttonLoading.value = false));
  proxy?.$modal.msgSuccess('通过成功');
  await getList();
};

/** 美化ppt提交按钮 */
const submitForm = async () => {
  if(!form.value.caseBeautifyFileList || form.value.caseBeautifyFileList.length == 0){
    proxy?.$modal.msgError("请先上传美化文件")
    return
  }

  let tempArr: { name: any; url: any; ossId: any }[] = [];
  console.log(tempArr, 'tempArr');
  form.value.caseBeautifyFileList.forEach((element: UploadFile) => {
    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
      });
    }
  });
  delete form.value.createTime;
  form.value.caseBeautifyFileList = tempArr;
  buttonLoading.value = true;
  let params = {
    beautifyStatus: '1',
    caseBeautifyFileList: form.value.caseBeautifyFileList,
    id: form.value.id
  }
  await updateCaseBaseInfo(params).finally(() => (buttonLoading.value = false));
  proxy?.$modal.msgSuccess('修改成功');
  dialog.visible = false;
  await getList();
};

onMounted(() => {
  getList();
  getexpertList();
  getdoctorList();
});
</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: 20px;
    // color: blue;
    // text-decoration: underline;
    display: flex;

    .text_right_icon {
      margin-left: 10px;
    }
  }

  .notice-tips{
    margin-bottom:10px;
  }
  .text-wrap{
    position: relative;

    :deep .el-textarea__inner{
      padding-right:20px;
    }

    .svg-icon{
      position: absolute;
      right:5px;
      top:5px;
    }
  }
}
:deep(.el-textarea__inner) {
  height: 200px;
}
</style>
