<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="commentStatus">
            <el-select v-model="queryParams.commentStatus" placeholder="全部状态" clearable @clear="handleQuery" @change="handleQuery">
              <el-option v-for="item in _business_caseBaseInfo_type_commentStatus" :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 label="点评专家" prop="commentUserIds">
            <el-select v-model="commentUserIds" multiple placeholder="请选择点评专家" clearable @clear="handleQuery" @change="handleQuery">
              <el-option v-for="item in expertIdoptions" :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="commentManageList" :cellStyle="cellStyle" empty-text="未找到搜索内容，请重新尝试">
        <el-table-column label="课件编号" align="center" prop="caseId" />
        <el-table-column label="课件名称" align="center" prop="caseName" />
        <el-table-column label="所有者" align="center" prop="userName" />
        <el-table-column label="点评专家" align="center" prop="commentUseName">
          <template #default="scope">
            {{scope.row.commentUseName  || '/'}}
          </template>
        </el-table-column>
        <el-table-column label="点评时间" align="center" prop="commentTime">
          <template #default="scope">
            {{scope.row.commentTime  || '/'}}
          </template>
        </el-table-column>
        <el-table-column label="等待点评时长" align="center" prop="commentWaitingHours">
          <template #default="scope">
            {{scope.row.commentWaitingHours ?  scope.row.commentWaitingHours + 'h' : '/'}}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="commentStatus">
          <template #default="scope">
            {{scope.row.commentStatus === '0'?'已点评' :(scope.row.commentStatus === '1'?'待点评': '重新点评')}}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="205">
          <template #default="scope">
            <!-- 点评状态 0已点评 1待点评 2重新点评 -->
            <el-tooltip :content="scope.row.commentStatus == '2' ? '重新点评' : '点评'" placement="top">
              <el-button
                v-if="scope.row.commentStatus == '2'"
                v-hasPermi="['business:commentManage:recomment']"
                link
                type="primary"
                style="font-size: 12px;"
                @click="handleComment(scope.row)"
                >重新点评</el-button
              >
              <el-button
                v-else
                v-hasPermi="['business:commentManage:comment']"
                link
                type="primary"
                style="font-size: 12px;"
                @click="handleComment(scope.row)"
                >点评</el-button
              >
            </el-tooltip>
            <el-tooltip content="下载课件" placement="top">
              <el-button
                v-hasPermi="['business:commentManage:download']"
                @click="handleDown(scope.$index)"
                style="font-size: 12px;"
                link
                type="primary"
                >下载课件</el-button
              >
            </el-tooltip>
            <el-tooltip v-if="scope.row.commentStatus != '0'" content="分配专家" placement="top">
              <el-button
                v-hasPermi="['business:commentManage:expertAllocation']"
                style="font-size: 12px;"
                @click="assignExpert(scope.row)"
                link
                type="primary"
                >分配专家</el-button
              >
            </el-tooltip>
            <el-tooltip v-if="scope.row.commentStatus == '2'" content="查看原因" placement="top">
              <el-button
                v-hasPermi="['business:commentManage:viewRejectReason']"
                @click="viewReason(scope.$index, true)"
                style="font-size: 12px;"
                link
                type="primary"
                >查看原因</el-button
              >
            </el-tooltip>
            <el-tooltip v-if="scope.row.commentStatus == '0'" content="查看点评" placement="top">
              <el-button
                v-hasPermi="['business:commentManage:query']"
                @click="viewReason(scope.$index, false)"
                style="font-size: 12px;"
                link
                type="primary"
                >查看点评</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="commentDialog.title" v-model="commentDialog.visible" width="800px" append-to-body>
      <div class="comment-dialog">
        <div class="score" v-if="commentSettingData?.caseCommentScore == '0'">
          <div>评分：</div>
          <div style="width: 60%;margin-left: 20px;">
            <el-slider v-model="score" :min="0" :max="100" show-input></el-slider>
          </div>
        </div>
        <div class="tips">
          {{ commentSettingData?.commentTips || '请填写点评信息，避免出现不良反应相关信息' }}
        </div>
        <div v-if="commentDialog.isReComment" class="suggest">修改意见:{{ commentRejectReason }}</div>
        <el-input type="textarea" placeholder="请填写您对该课件的点评" show-word-limit v-model="commentContent" />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="() => (commentDialog.visible = false) ">取 消</el-button>
          <el-button type="primary" @click="submitCommentContent">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看原因、查看点评对话框 -->
    <el-dialog :title="viewContentDialog.title" v-model="viewContentDialog.visible" width="800px" append-to-body>
      <div class="view_url">
        <el-row :gutter="20" align="middle" v-if="!viewContentDialog.isReComment && commentManageList[viewUrlIndex].commentScore">
          <el-col :span="6" class="text_left">分数</el-col>
          <el-col :span="18">
            <el-slider v-model="score" show-input disabled></el-slider>
          </el-col>
        </el-row>
        <el-row :gutter="20" align="middle">
          <el-col :span="6" class="text_left">{{ viewContentDialog.isReComment ? '审核拒绝原因' : '点评内容' }}</el-col>
          <el-col :span="18" class="text_right">
            {{ viewContentDialog.isReComment ? commentManageList[viewUrlIndex].commentRejectReason :  commentManageList[viewUrlIndex].commentContent}}
          </el-col>
        </el-row>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="() => (viewContentDialog.visible = false)">取 消</el-button>
          <el-button type="primary" @click="() => (viewContentDialog.visible = false)">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配专家对话框 -->
    <el-dialog :title="assignExpertDialog.title" v-model="assignExpertDialog.visible" width="800px" append-to-body>
      <div class="view_url">
        <el-row :gutter="20" align="middle">
          <el-col :span="6" class="text_left">请选择点评专家</el-col>
          <el-col :span="18">
            <el-select v-model="expertId" placeholder="请选择点评专家" clearable>
              <el-option v-for="item in allocationExpertList" :key="item.userId" :label="item.userName" :value="item.userId"> </el-option>
            </el-select>
          </el-col>
        </el-row>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="() => (assignExpertDialog.visible = false)">取 消</el-button>
          <el-button type="primary" @click="submitAssignExpert">确 定</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 commentManageList[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>
  </div>
</template>

<script setup name="commentManage" lang="ts">
import { listDoctor, listExpert } from '@/api/business/caseBaseInfo';
import { Doctoroption } from '@/api/business/caseBaseInfo/types';
import { listCommentManageInfo, updateAssignExpert, updateCommentContent, allocationListExpert } from '@/api/business/commentManage';
import { auditCommonVO, commentManageQuery, usualDialogOption } from '@/api/business/commentManage/types';
import { listCommentSettingInfo } from '@/api/system/commentSetting';
import { commentSettingForm } from '@/api/system/commentSetting/types';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { _business_caseBaseInfo_type_commentStatus } = toRefs<any>(proxy?.canSearchDict('/business/caseBaseInfo/type/commentStatus'));

const commentManageList = ref<auditCommonVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const userIds = ref<Array<string | number>>([]);
const commentUserIds = ref<Array<string | number>>([]);
const total = ref(0);
const commentDoctorIdoptions = ref<Doctoroption[]>([]);
const expertIdoptions = ref<Doctoroption[]>([]);
const allocationExpertList = ref<Doctoroption[]>([]);
const viewUrlIndex = ref(-1);
const downviewUrlIndex = ref(-1);
const queryFormRef = ref<ElFormInstance>();
const commentSettingData = ref<commentSettingForm>()
const score = ref(0)
const commentContent = ref<string>('');
const commentRejectReason = ref<string>('');
const id = ref<string | number>();

const expertId = ref<string>('');

const commentDialog = reactive<usualDialogOption>({
  visible: false,
  title: '课件点评',
  isReComment:false
});

const viewContentDialog = reactive<usualDialogOption>({
  visible: false,
  title: '',
  isReComment:false
});

const downDialog = reactive<DialogOption>({
  visible: false,
  title: '已上传课件'
});

const assignExpertDialog = reactive<DialogOption>({
  visible: false,
  title: '分配专家'
});

const data = reactive<PageData<any, commentManageQuery>>({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userIds: undefined,
    commentUserIds: undefined,
    caseName: undefined,
    commentStatus: undefined,
    params: {}
  },
  rules: {}
});

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

const hidedownViewUrlDialog = () => {
  downDialog.visible = false;
};

//批量导入-用户状态 文字颜色
const cellStyle = ({ row, column }) => {
  let controlStatusStyle
  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 controlStatusStyle
  }
}

/** 查询点评管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listCommentManageInfo(queryParams.value);
  commentManageList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};
const getCommentSettingData = async () => {
  const res = await listCommentSettingInfo()
  commentSettingData.value = res.rows[0];
}

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

/** 获取专家列表 */
const getExpertList = async () => {
  const res = await listExpert();
  expertIdoptions.value = res.data;
};

/** 获取专家列表 */
const getAllocationExpertList = async () => {
  const res = await allocationListExpert();
  allocationExpertList.value = res.data;
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  queryParams.value.userIds = userIds.value.join(',')
  queryParams.value.commentUserIds = commentUserIds.value.join(',')
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  userIds.value = []
  commentUserIds.value = []
  handleQuery();
};

// 打开点评弹框
const handleComment = async (row: auditCommonVO) => {
  commentContent.value = row.commentContent || ''
  commentRejectReason.value = row.commentRejectReason || ''
  id.value = row.id
  if(row.commentStatus == '1'){
    commentDialog.isReComment = false
  }else if(row.commentStatus == '2'){
    commentDialog.isReComment = true
  }
  commentDialog.visible = true;
};

/** 点评、重新点评操作按钮 */
const submitCommentContent = async () => {
  if(!commentContent.value){
    proxy?.$modal.msgWarning('请填写点评内容');
    return
  }else if(commentContent.value.length < 100){
    proxy?.$modal.msgWarning('点评内容不能少于100个中英文字符');
    return
  }

  let params = {
    id:id.value,
    commentContent:commentContent.value,
    commentScore:commentSettingData.value?.caseCommentScore == '0' ? score.value : ''
  };
  await updateCommentContent(params).finally(() => (buttonLoading.value = false));
  proxy?.$modal.msgSuccess('点评内容提交成功');
  commentDialog.visible = false;
  await getList();
};

/** 查看拒绝原因 */
const viewReason = async (index: any, isReComment:boolean) => {
  viewUrlIndex.value = index;
  viewContentDialog.isReComment = isReComment
  viewContentDialog.title = isReComment ? '查看原因' : '查看点评';
  viewContentDialog.visible = true;
  score.value = parseInt(commentManageList.value[index].commentScore)
};

/** 下载按钮操作 */
const handleDown = async (index: any) => {
  downviewUrlIndex.value = index;
  downDialog.visible = true;
};

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

/** 分配专家 */
const assignExpert = (row: auditCommonVO) => {
  id.value = row.id
  assignExpertDialog.visible = true
};

const submitAssignExpert = async () =>{
  if(!expertId.value){
    proxy?.$modal.msgWarning('请选择专家');
    return
  }
  let params = {
    id: id.value,
    commentUserId: expertId.value
  };
  await updateAssignExpert(params).finally(() => (buttonLoading.value = false));
  assignExpertDialog.visible = false;
  proxy?.$modal.msgSuccess('专家分配成功');
  await getList();
}

onMounted(() => {
  getdoctorList();
  getExpertList();
  getAllocationExpertList();
  getList();
  getCommentSettingData();
});
</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;
  }

  .text_right {
    display: flex;

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

.comment-dialog{

  .score{
    height: 40px;
    display: flex;
    align-items: center;
    margin: 10px 0px;
  }
  .tips{
    margin-bottom:40px;
    line-height: 25px;
    color: black;
    white-space: pre;
  }

  .suggest{
    margin-bottom:30px;
    line-height: 30px;
    color: black;
  }
}

:deep(.el-textarea__inner) {
  height: 200px;
}
</style>
