<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <!-- <el-form-item label="审批状态" prop="auditStatus">
        <el-select
          v-model="queryParams.auditStatus"
          placeholder="请选择审批状态"
          clearable
          class="!w-240px"
        >
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="填报人员" prop="creator">
        <el-select v-model="queryParams.creator" placeholder="请选择申请人" class="!w-240px">
              <el-option
                v-for="dict in userOptions"
                :key="dict.id"
                :label="dict.nickname"
                :value="dict.id"
              />
            </el-select>
      </el-form-item>
      <el-form-item label="简报日期" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openFormAdd('create')"
          v-hasPermi="['tts:brief-work:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['tts:brief-work:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column
        label="简报日期"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="填报人员" align="center" prop="creator">
        <template #default="scope">
          {{getName(userOptions, scope.row.creator, 'id', 'nickname')}}
        </template>
      </el-table-column>
      <el-table-column label="本周完成工作" align="center" prop="workComplate" />
      <el-table-column label="下周工作计划" align="center" prop="workPlan" />
      <el-table-column label="工作困难及协助" align="center" prop="workAssistance" />
      <el-table-column label="上传附件" align="center" prop="attachment">
        <template #default="scope">
          <el-link
            v-if="scope.row.attachment"
            :underline="false"
            type="primary"
            @click="previewFile(scope.row.attachment)"
          >
            预览
          </el-link>
          <span v-else>无附件</span>
        </template>
      </el-table-column>
      <el-table-column label="审批状态" align="center" prop="auditStatus" width="110">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.TTS_APPLY_STATUS" :value="scope.row.auditStatus" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
             v-if="scope.row.auditStatus !== 0"
              link
              type="primary"
              @click="handleProcessDetail(scope.row)"
            >
              进度
            </el-button>
            <el-button
              link
              type="primary"
              @click="openFormDetail(scope.row)"
              
            >
              详情
            </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <!-- <BriefWorkForm ref="formRef" @success="getList" /> -->
</template>

<script setup lang="ts">
import { getIntDictOptions, getBoolDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { BriefWorkApi, BriefWorkVO } from '@/api/task/briefWork'
// import BriefWorkForm from './BriefWorkForm.vue'
import * as UserApi from '@/api/system/user'


/** 工作简报 列表 */
defineOptions({ name: 'BriefWork' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const userOptions = ref<UserApi.UserVO[]>([]) // 用户列表

const loading = ref(true) // 列表的加载中
const list = ref<BriefWorkVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  briefType: 2,
  briefCount: undefined,
  briefStartDate: [],
  briefEndDate: [],
  selectCustomer: undefined,
  workComplate: undefined,
  workPlan: undefined,
  workAssistance: undefined,
  workExperience: undefined,
  attachment: undefined,
  processInstanceId: undefined,
  auditStatus: undefined,
  creator: undefined,
  createTime: [],
  updater: undefined,
  updateTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await BriefWorkApi.getBriefWorkPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const { push } = useRouter()
const router = useRouter() // 路
//新增
const openFormAdd =  () => {
  push({ name: 'WeekReportAdd' })
}

//详情
const openFormDetail = (row: Object) => {
  router.push({ name: 'WeekReportDetail', query: { id: row.id} })
}

/** 查看审批 */
const handleProcessDetail = (row) => {
  router.push({ name: 'BpmProcessInstanceDetail', query: { id: row.processInstanceId } })
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await BriefWorkApi.deleteBriefWork(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await BriefWorkApi.exportBriefWork(queryParams)
    download.excel(data, '周工作简报.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

//预览
const previewFile = (fileUrls) => {
  // // 假设 fileUrls 是一个字符串，包含文件的完整 URL
  if (!fileUrls) {
    message.error('没有附件');
    return;
  }

  // 检查文件类型
  const fileExtension = fileUrls.split('.').pop().toLowerCase();
  router.push({
    name: 'FileTemplatePreview',
    query: {
      src: encodeURIComponent(fileUrls),
      type: fileExtension
    }
  })
}

const getName = (opt, val, id, name) => {
  const arr = opt.filter(v => v[id] == val)
  return arr.length ? arr[0][name] : ''
}

const route = useRoute();
onMounted(async () => {
  // 获得用户列表
  userOptions.value = await UserApi.getSimpleUserList()
  getList()
})
onActivated(()=>{
  getList()
})
</script>