<template>
  <div>
    <!--查询区域-->
    <div class="jeecg-basic-table-form-container">
      <a-form ref="formRef" @keyup.enter.native="searchQuery" :model="queryParam" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-row :gutter="24">
          <!--          <a-col :lg="8">
                      <a-form-item label="年度" name="annualId">
                        <a-input placeholder="请输入年度"
                                 v-model:value="queryParam.annualId"></a-input>
                      </a-form-item>
                    </a-col>-->
          <!--          <a-col :lg="8">
                      <a-form-item label="比赛名称" name="compId">
                        <a-input placeholder="请输入比赛名称"
                                 v-model:value="queryParam.compId"></a-input>
                      </a-form-item>
                    </a-col>-->
          <a-col :lg="8" v-if="!isStu">
            <a-form-item label="报名编号" name="applyCode">
              <a-input placeholder="请输入报名编号" v-model:value="queryParam.applyCode" />
            </a-form-item>
          </a-col>
          <a-col :lg="8">
            <a-form-item label="作品名称" name="topicName">
              <a-input placeholder="请输入作品名称" v-model:value="queryParam.topicName" />
            </a-form-item>
          </a-col>
          <a-col :lg="8">
            <a-form-item label="状态" name="status">
              <a-select ref="select" v-model:value="queryParam.status" style="width: 100%" @focus="focus" placeholder="请选择作品状态">
                <a-select-option value="0">待评分</a-select-option>
                <a-select-option value="1">已评分</a-select-option>
                <a-select-option value="2">待驳回</a-select-option>
                <a-select-option value="3">已驳回</a-select-option>
                <a-select-option value="4">待提交</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <!--          <template v-if="toggleSearchStatus">
          &lt;!&ndash;            <a-col :lg="8">
                        <a-form-item label="年度比赛名称" name="annualCompId">
                          <a-input placeholder="请输入年度比赛名称"
                                   v-model:value="queryParam.annualCompId"></a-input>
                        </a-form-item>
                      </a-col>&ndash;&gt;
          &lt;!&ndash;            <a-col :lg="8">
                        <a-form-item label="驳回原因" name="backInfo">
                          <a-input placeholder="请输入驳回原因"
                                   v-model:value="queryParam.backInfo"></a-input>
                        </a-form-item>
                      </a-col>&ndash;&gt;
                    </template>-->
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-col :lg="6">
                <a-button type="primary" preIcon="ant-design:search-outlined" @click="searchQuery">查询</a-button>
                <a-button type="primary" preIcon="ant-design:reload-outlined" @click="searchReset" style="margin-left: 8px">重置</a-button>
                <!--                <a @click="toggleSearchStatus = !toggleSearchStatus"
                                   style="margin-left: 8px">
                                  {{ toggleSearchStatus ? '收起' : '展开' }}
                                  <Icon
                                      :icon="toggleSearchStatus ? 'ant-design:up-outlined' : 'ant-design:down-outlined'"/>
                                </a>-->
              </a-col>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <!--插槽:table标题-->
      <template #tableTitle v-if="isStu">
        <a-button type="primary" @click="handleWorkUpload"> 上传作品 </a-button>
        <a-button type="primary" @click="handleBack"> 申请驳回 </a-button>
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" />
      </template>
      <!--字段回显插槽-->
      <template #htmlSlot="{ text }">
        <div v-html="text"></div>
      </template>
      <!--省市区字段回显插槽-->
      <template #pcaSlot="{ text }">
        {{ getAreaTextByCode(text) }}
      </template>
      <!--      <template #fileSlot="{text}">
              <span v-if="!text"
                    style="font-size: 12px;font-style: italic;">无文件</span>
              <a-button v-else :ghost="true" type="primary"
                        preIcon="ant-design:download-outlined" size="small"
                        @click="downloadFile(text)">下载
              </a-button>
            </template>-->
    </BasicTable>
    <!-- 表单区域 -->
    <UpfilePersionModal ref="registerModal" @success="handleSuccess" />
  </div>
  <AddScore @score-finish="scoreFinish" ref="addScoreRef" />
  <WorkUpload ref="workUploadRef" />
  <work-info-modal ref="workInfoModalRef" />
  <a-modal v-model:visible="modalVisible" title="驳回原因" @cancel="clearBackInfo" @ok="submitBackInfo">
    <a-row>
      <a-col :span="4" :offset="1">
        <span>驳回原因：</span>
      </a-col>
      <a-col :span="18">
        <a-textarea v-model:value="backInfo" placeHolder="请输入驳回原因" aallowClear :autosize="{ minRows: 5 }" />
      </a-col>
    </a-row>
  </a-modal>
</template>

<script lang="ts" name="upfile_persion-upfilePersion" setup>
  import { reactive, ref } from 'vue';
  import { BasicTable, TableAction } from '/@/components/Table';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { columns } from './UpfilePersion.data';
  import {
    applyWorkBack,
    batchDelete,
    canScore,
    canUpload,
    deleteOne,
    getDownWork,
    getExportUrl,
    getImportUrl,
    judgeReg,
    judgeRoles,
    list,
    saveOrUpdate,
    startScore,
    startScoreWithFile,
    updateAnnualCompPointStatus,
    updateStatus,
    workBack,
    works,
  } from './UpfilePersion.api';
  import UpfilePersionModal from './components/UpfilePersionModal.vue';
  import { getAreaTextByCode } from '/@/components/Form/src/utils/Area';
  import AddScore from '/@/views/UpfilePersion/components/AddScore.vue';
  import { useUserStore } from '/@/store/modules/user';
  import { message } from 'ant-design-vue';
  import { useRoute } from 'vue-router';
  import WorkUpload from '/@/views/UpfilePersion/components/WorkUpload.vue';
  import WorkInfoModal from '/@/views/UpfilePersion/components/WorkInfoModal.vue';
  import { downloadFile } from '/@/api/common/api';
  import { router } from '/@/router';
  import { useGlobSetting } from '/@/hooks/setting';

  const globalSetting = useGlobSetting();
  const formRef = ref();
  const queryParam = reactive<any>({});
  const toggleSearchStatus = ref<boolean>(false);
  const registerModal = ref();
  const addScoreRef = ref();
  const workUploadRef = ref();
  const workInfoModalRef = ref();
  const userStore = useUserStore();
  const modalVisible = ref(false);
  // 路由信息
  const route = useRoute();
  if (!route.query.annualCompPointId) {
    router.replace('/page-demo/exception/404');
  }
  // 角色判断+是否报名
  const isStu = ref(false);
  const isCommittee = ref(false);
  const isSuperAdmin = ref(false);
  const isReg = ref(false);
  (async (router) => {
    isCommittee.value = await judgeRoles({ roles: 'committee' });
    isSuperAdmin.value = await judgeRoles({ roles: 'superAdmin' });
    isStu.value = await judgeRoles({ roles: 'xs' });
    isReg.value = await judgeReg({ annualCompPointId: route.query.annualCompPointId });
    // 学生是否报名
    if (isStu.value && !isReg.value) {
      router.back();
      message.error('报名信息不存在，请报名后查看作品');
    }
  })(router);
  //注册table数据
  const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
    tableProps: {
      title: '作品集',
      api: () => list({ annualCompPointId: route.query.annualCompPointId, ...queryParam }),
      columns,
      canResize: false,
      useSearchForm: false,
      actionColumn: {
        width: 250,
        fixed: 'right',
      },
      beforeFetch: (params) => {
        queryParam.pageNo = params.pageNo;
        queryParam.pageSize = params.pageSize;
        return Object.assign(params, queryParam);
      },
    },
    exportConfig: {
      name: 'upfile_persion',
      url: getExportUrl,
      params: queryParam,
    },
    importConfig: {
      url: getImportUrl,
      success: handleSuccess,
    },
  });
  const [registerTable, { reload, collapseAll, updateTableDataRecord, getDataSource }, { rowSelection, selectedRowKeys }] = tableContext;
  const labelCol = reactive({
    xs: { span: 24 },
    sm: { span: 7 },
  });
  const wrapperCol = reactive({
    xs: { span: 24 },
    sm: { span: 16 },
  });

  /**
   * 新增事件
   */
  function handleAdd() {
    registerModal.value.disableSubmit = false;
    registerModal.value.add();
  }

  /**
   * 编辑事件
   */
  function handleEdit(record: Recordable) {
    registerModal.value.disableSubmit = false;
    registerModal.value.edit(record);
  }

  /**
   * 详情
   */
  function handleDetail(record: Recordable) {
    registerModal.value.disableSubmit = true;
    registerModal.value.edit(record);
  }

  /**
   * 删除事件
   */
  async function handleDelete(record) {
    if (record.status !== 4 && record.status !== 3) {
      return message.error('当前状态下无法删除作品');
    }
    await deleteOne({ id: record.id }, handleSuccess);
  }

  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
  }

  /**
   * 成功回调
   */
  function handleSuccess() {
    (selectedRowKeys.value = []) && reload();
  }

  // 准备评分
  async function handleScore(record) {
    await canScore(record);
    addScoreRef.value.modalShow(true, record);
  }

  // 开始评分
  async function scoreFinish(payload) {
    payload.applyCode = payload.enrollCode;
    /*    await startScore(payload);
    // 修改作品状态为已评分
    await updateStatus(payload);
    // 修改年度比赛项目状态
    await updateAnnualCompPointStatus(payload);*/
    await startScoreWithFile(payload);
    await reload();
  }

  // 上传作品
  const isCanUpload = ref(false);

  async function handleWorkUpload() {
    console.log(123, route.query.annualCompPointId);
    isCanUpload.value = false;
    await canUpload({ annualCompPointId: route.query.annualCompPointId });
    isCanUpload.value = true;
    if (isCanUpload.value) {
      workUploadRef.value.modalShow(true, route.query.annualCompPointId, reload);
    }
  }

  async function handleWorkSubmit(record) {
    if (record.status !== 4 && record.status !== 3) {
      return message.error('作品禁止重复提交');
    } else {
      record.status = 0;
      record.backInfo = '';
      const resp = await saveOrUpdate(record, true);
      if (resp.success) {
        await reload();
        message.success('提交成功');
      } else {
        message.error('提交失败');
      }
    }
  }

  const backInfo = ref('');
  let backRecord: any = null;

  function clearBackInfo() {
    backInfo.value = '';
    modalVisible.value = false;
  }

  function submitBackInfo() {
    backRecord.backInfo = backInfo.value;
    startBack(backRecord);
    modalVisible.value = false;
  }

  // 驳回
  async function handleBack(record) {
    backInfo.value = '';
    modalVisible.value = true;
    backRecord = record;
  }

  async function startBack(record) {
    if (await judgeRoles({ roles: 'user' })) {
      await applyWorkBack({
        annualCompPointId: route.query.annualCompPointId,
        backInfo: backInfo.value,
      });
    } else {
      await workBack({ ...record });
    }
    await reload();
  }

  function handlePreview(record) {
    const previewServerUrl = 'http://127.0.0.1:8012/onlinePreview?url=';
    const fileUrl = `${globalSetting.domainUrl}${getDownWork}?id=${record.id}`;
    const extName = record.url.substring(record.url.lastIndexOf('.'));
    const previewUrl = `${fileUrl}&fullfilename=${new Date().getTime()}${extName}`;
    window.open(previewServerUrl + encodeURIComponent(Base64.encode(previewUrl)));
  }

  function handleDown(record) {
    const extName = record.url.substring(record.url.lastIndexOf('.'));
    message.info('开始下载...');
    downloadFile(getDownWork, new Date().getTime() + extName, { ...record });
  }

  // 作品详情
  async function handleWorkInfo(record) {
    console.log(11111);
    const dataSource = await works({ applyCode: record.applyCode });
    workInfoModalRef.value.modalShow(true, dataSource);
  }

  /**
   * 操作栏
   */
  function getTableAction(record) {
    const tableAction = [];
    tableAction.unshift({
      label: '详情',
      onClick: handleDetail.bind(null, record),
    });
    if (isStu.value) {
      // 学生独有的按钮
      tableAction.unshift(
        {
          label: '提交',
          popConfirm: {
            title: '是否提交当前作品',
            confirm: handleWorkSubmit.bind(null, record),
          },
        },
        {
          label: '下载',
          onClick: handleDown.bind(null, record),
        },
        {
          label: '预览',
          onClick: handlePreview.bind(null, record),
        },
        {
          label: '删除',
          popConfirm: {
            title: '是否删除当前作品',
            confirm: handleDelete.bind(null, record),
          },
        }
      );
    } else if (isCommittee.value) {
      tableAction.unshift(
        {
          label: '评分',
          onClick: handleScore.bind(null, record),
        },
        {
          label: '驳回',
          popConfirm: {
            title: '是否驳回当前作品？',
            confirm: handleBack.bind(null, record),
          },
        }
      );
    } else if (isSuperAdmin.value) {
      tableAction.unshift(
        {
          label: '下载',
          onClick: handleDown.bind(null, record),
        },
        {
          label: '预览',
          onClick: handlePreview.bind(null, record),
        }
      );
    }
    return tableAction;
  }

  /**
   * 下拉操作栏
   */
  function getDropDownAction(record) {
    return [
      {
        label: '详情',
        onClick: handleDetail.bind(null, record),
      },
      {
        label: '删除',
        popConfirm: {
          title: '是否确认删除',
          confirm: handleDelete.bind(null, record),
        },
      },
    ];
  }

  /**
   * 查询
   */
  function searchQuery() {
    reload();
  }

  /**
   * 重置
   */
  function searchReset() {
    formRef.value.resetFields();
    selectedRowKeys.value = [];
    //刷新数据
    reload();
  }
</script>

<style lang="less" scoped>
  .jeecg-basic-table-form-container {
    .table-page-search-submitButtons {
      display: block;
      margin-bottom: 24px;
      white-space: nowrap;
    }

    .query-group-cust {
      width: calc(50% - 15px);
      min-width: 100px !important;
    }

    .query-group-split-cust {
      width: 30px;
      display: inline-block;
      text-align: center;
    }
  }
</style>
