<template>
  <ArtTableFullScreen>
    <div class="order-package-invalidate-task-page" id="table-full-screen">
      <ArtSearchBar
        v-model:filter="searchForm"
        :items="searchFormItems"
        :show-expand="false"
        @reset="handleReset"
        @search="handleSearch"
      />

      <ElCard shadow="never" class="art-table-card">
        <ArtTableHeader
          :columnList="columnOptions"
          v-model:columns="columnChecks"
          @refresh="handleRefresh"
        >
          <template #left>
            <ElButton
              type="primary"
              :icon="Upload"
              @click="createDialogVisible = true"
              v-permission="'order_package_invalidate_task:create'"
            >
              新建作废任务
            </ElButton>
          </template>
        </ArtTableHeader>

        <ArtTable
          ref="tableRef"
          row-key="id"
          :loading="loading"
          :data="taskList"
          :currentPage="pagination.page"
          :pageSize="pagination.page_size"
          :total="pagination.total"
          :marginTop="10"
          :actions="getActions"
          :actionsWidth="180"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
          <template #default>
            <ElTableColumn v-for="col in columns" :key="col.prop || col.type" v-bind="col" />
          </template>
        </ArtTable>
      </ElCard>

      <ElDialog
        v-model="createDialogVisible"
        title="新建订单套餐作废任务"
        width="560px"
        @closed="handleCreateDialogClosed"
      >
        <ElForm ref="createFormRef" :model="createForm" :rules="createRules" label-width="100px">
          <ElFormItem label="CSV文件" prop="file">
            <ElUpload
              ref="uploadRef"
              drag
              :auto-upload="false"
              :limit="1"
              accept=".csv,text/csv"
              :on-change="handleFileChange"
              :on-remove="handleFileRemove"
            >
              <ElIcon class="el-icon--upload"><UploadFilled /></ElIcon>
              <div class="el-upload__text">将 CSV 文件拖到此处，或<em>点击选择</em></div>
              <template #tip>
                <div class="el-upload__tip">仅支持 .csv 文件，必填列：order_no</div>
              </template>
            </ElUpload>
          </ElFormItem>
          <ElFormItem label="凭证附件">
            <VoucherUpload
              ref="voucherUploadRef"
              v-model="createForm.voucher_keys"
              voucher-name="凭证附件"
              @uploading-change="voucherUploading = $event"
            />
          </ElFormItem>
          <ElFormItem label="运营备注" prop="remark">
            <ElInput
              v-model="createForm.remark"
              type="textarea"
              :rows="3"
              maxlength="1000"
              show-word-limit
              placeholder="请输入运营备注（可选）"
            />
          </ElFormItem>
        </ElForm>
        <template #footer>
          <ElButton @click="createDialogVisible = false">取消</ElButton>
          <ElButton
            type="primary"
            :loading="creating || voucherUploading"
            :disabled="voucherUploading"
            @click="handleCreateTask"
          >
            {{ voucherUploading ? '凭证上传中...' : '确认创建' }}
          </ElButton>
        </template>
      </ElDialog>

      <PaymentVoucherDialog :file-keys="voucherPreviewKeys" @close="voucherPreviewKeys = []" />
    </div>
  </ArtTableFullScreen>
</template>

<script setup lang="ts">
  import { h, onMounted, reactive, ref } from 'vue'
  import { useRouter } from 'vue-router'
  import {
    ElButton,
    ElCard,
    ElForm,
    ElFormItem,
    ElIcon,
    ElInput,
    ElMessage,
    ElTag,
    ElUpload
  } from 'element-plus'
  import { Upload, UploadFilled } from '@element-plus/icons-vue'
  import type { FormInstance, FormRules, UploadFile, UploadInstance } from 'element-plus'
  import { OrderPackageInvalidateTaskService, StorageService } from '@/api/modules'
  import type {
    CreateOrderPackageInvalidateTaskRequest,
    OrderPackageInvalidateTask,
    OrderPackageInvalidateTaskQueryParams,
    OrderPackageInvalidateTaskStatus
  } from '@/types/api'
  import type { SearchFormItem } from '@/types'
  import { useCheckedColumns } from '@/composables/useCheckedColumns'
  import { useAuth } from '@/composables/useAuth'
  import { formatDateTime } from '@/utils/business/format'
  import { getErrorMessage, hasVoucherKeys, toVoucherKeyList } from '@/utils/business'
  import { RoutesAlias } from '@/router/routesAlias'
  import PaymentVoucherDialog from '@/components/business/PaymentVoucherDialog.vue'
  import VoucherUpload from '@/components/business/VoucherUpload.vue'

  defineOptions({ name: 'OrderPackageInvalidateTask' })

  const router = useRouter()
  const { hasAuth } = useAuth()

  const loading = ref(false)
  const creating = ref(false)
  const voucherUploading = ref(false)
  const tableRef = ref()
  const uploadRef = ref<UploadInstance>()
  const voucherUploadRef = ref<InstanceType<typeof VoucherUpload>>()
  const createFormRef = ref<FormInstance>()
  const createDialogVisible = ref(false)
  const selectedFile = ref<File | null>(null)
  const taskList = ref<OrderPackageInvalidateTask[]>([])
  const voucherPreviewKeys = ref<string[]>([])

  const searchForm = reactive<OrderPackageInvalidateTaskQueryParams>({
    page: 1,
    page_size: 20,
    status: undefined
  })

  const pagination = reactive({
    page: 1,
    page_size: 20,
    total: 0
  })

  const createForm = reactive({
    file: '',
    voucher_keys: [] as string[],
    remark: ''
  })

  const createRules = reactive<FormRules>({
    file: [{ required: true, message: '请选择 CSV 文件', trigger: 'change' }],
    remark: [{ max: 1000, message: '运营备注最多1000字', trigger: 'blur' }]
  })

  const searchFormItems: SearchFormItem[] = [
    {
      label: '任务状态',
      prop: 'status',
      type: 'select',
      config: { clearable: true, placeholder: '全部' },
      options: [
        { label: '待处理', value: 1 },
        { label: '处理中', value: 2 },
        { label: '已完成', value: 3 },
        { label: '失败', value: 4 }
      ]
    }
  ]

  const columnOptions = [
    { label: '任务编号', prop: 'task_no' },
    { label: '任务状态', prop: 'status' },
    { label: '总数', prop: 'total_count' },
    { label: '成功数', prop: 'success_count' },
    { label: '失败数', prop: 'fail_count' },
    { label: '跳过数', prop: 'skip_count' },
    { label: '文件名', prop: 'file_name' },
    { label: '凭证', prop: 'voucher_keys' },
    { label: '运营备注', prop: 'remark' },
    { label: '操作人', prop: 'creator_name' },
    { label: '错误信息', prop: 'error_message' },
    { label: '创建时间', prop: 'created_at' },
    { label: '开始时间', prop: 'started_at' },
    { label: '完成时间', prop: 'completed_at' }
  ]

  const getStatusType = (status: OrderPackageInvalidateTaskStatus) => {
    const statusMap: Record<number, 'info' | 'warning' | 'success' | 'danger'> = {
      1: 'info',
      2: 'warning',
      3: 'success',
      4: 'danger'
    }
    return statusMap[status] || 'info'
  }

  const getStatusName = (task: OrderPackageInvalidateTask) =>
    task.status_text || task.status_name || '-'

  const handleNameClick = (row: OrderPackageInvalidateTask) => {
    if (!hasAuth('order_package_invalidate_task:detail')) {
      ElMessage.warning('您没有查看详情的权限')
      return
    }
    router.push({
      path: RoutesAlias.OrderPackageInvalidateTaskDetail,
      query: { id: row.id }
    })
  }

  const { columnChecks, columns } = useCheckedColumns(() => [
    {
      prop: 'task_no',
      label: '任务编号',
      width: 220,
      showOverflowTooltip: true,
      formatter: (row: OrderPackageInvalidateTask) =>
        h(
          'span',
          {
            style: 'color: var(--el-color-primary); cursor: pointer; text-decoration: underline;',
            onClick: (event: MouseEvent) => {
              event.stopPropagation()
              handleNameClick(row)
            }
          },
          row.task_no
        )
    },
    {
      prop: 'status',
      label: '任务状态',
      width: 100,
      formatter: (row: OrderPackageInvalidateTask) =>
        h(ElTag, { type: getStatusType(row.status) }, () => getStatusName(row))
    },
    { prop: 'total_count', label: '总数', width: 80 },
    {
      prop: 'success_count',
      label: '成功数',
      width: 80,
      formatter: (row: OrderPackageInvalidateTask) =>
        h('span', { style: { color: 'var(--el-color-success)' } }, row.success_count)
    },
    {
      prop: 'fail_count',
      label: '失败数',
      width: 80,
      formatter: (row: OrderPackageInvalidateTask) =>
        h('span', { style: { color: 'var(--el-color-danger)' } }, row.fail_count)
    },
    {
      prop: 'skip_count',
      label: '跳过数',
      width: 80,
      formatter: (row: OrderPackageInvalidateTask) => row.skip_count ?? 0
    },
    { prop: 'file_name', label: '文件名', minWidth: 180, showOverflowTooltip: true },
    {
      prop: 'voucher_keys',
      label: '凭证',
      width: 100,
      formatter: (row: OrderPackageInvalidateTask) =>
        hasVoucherKeys(row.voucher_keys)
          ? h(
              ElButton,
              {
                link: true,
                type: 'primary',
                onClick: () => (voucherPreviewKeys.value = toVoucherKeyList(row.voucher_keys))
              },
              () => '查看'
            )
          : '-'
    },
    {
      prop: 'remark',
      label: '运营备注',
      minWidth: 180,
      showOverflowTooltip: true,
      formatter: (row: OrderPackageInvalidateTask) => row.remark || '-'
    },
    {
      prop: 'creator_name',
      label: '操作人',
      width: 140,
      showOverflowTooltip: true,
      formatter: (row: OrderPackageInvalidateTask) => row.creator_name || '-'
    },
    {
      prop: 'error_message',
      label: '错误信息',
      minWidth: 200,
      showOverflowTooltip: true,
      formatter: (row: OrderPackageInvalidateTask) => row.error_message || '-'
    },
    {
      prop: 'created_at',
      label: '创建时间',
      width: 180,
      formatter: (row: OrderPackageInvalidateTask) => formatDateTime(row.created_at)
    },
    {
      prop: 'started_at',
      label: '开始时间',
      width: 180,
      formatter: (row: OrderPackageInvalidateTask) =>
        row.started_at ? formatDateTime(row.started_at) : '-'
    },
    {
      prop: 'completed_at',
      label: '完成时间',
      width: 180,
      formatter: (row: OrderPackageInvalidateTask) =>
        row.completed_at ? formatDateTime(row.completed_at) : '-'
    }
  ])

  const getTableData = async () => {
    loading.value = true
    try {
      const res = await OrderPackageInvalidateTaskService.getTasks({
        page: pagination.page,
        page_size: pagination.page_size,
        status: searchForm.status
      })
      if (res.code === 0) {
        taskList.value = res.data.items || []
        pagination.total = res.data.total || 0
      }
    } catch (error) {
      console.error('加载订单套餐作废任务失败:', error)
    } finally {
      loading.value = false
    }
  }

  const handleSearch = () => {
    pagination.page = 1
    getTableData()
  }

  const handleReset = () => {
    searchForm.status = undefined
    pagination.page = 1
    getTableData()
  }

  const handleRefresh = () => getTableData()
  const handleSizeChange = (pageSize: number) => {
    pagination.page_size = pageSize
    getTableData()
  }
  const handleCurrentChange = (page: number) => {
    pagination.page = page
    getTableData()
  }

  const handleFileChange = (uploadFile: UploadFile) => {
    const file = uploadFile.raw
    if (!file) return
    if (!/\.csv$/i.test(file.name)) {
      ElMessage.error('仅支持 CSV 文件')
      uploadRef.value?.clearFiles()
      selectedFile.value = null
      createForm.file = ''
      return
    }
    selectedFile.value = file
    createForm.file = file.name
    createFormRef.value?.validateField('file')
  }

  const handleFileRemove = () => {
    selectedFile.value = null
    createForm.file = ''
    createFormRef.value?.validateField('file')
  }

  const uploadCsvFile = async (file: File) => {
    const contentType = file.type || 'text/csv'
    const uploadUrlRes = await StorageService.getUploadUrl({
      file_name: file.name,
      content_type: contentType,
      purpose: 'attachment'
    })
    if (uploadUrlRes.code !== 0) {
      throw new Error(uploadUrlRes.msg || '获取上传地址失败')
    }

    await StorageService.uploadFile(uploadUrlRes.data.upload_url, file, contentType)
    return uploadUrlRes.data.file_key
  }

  const handleCreateTask = async () => {
    if (!createFormRef.value) return
    if (voucherUploading.value) {
      ElMessage.warning('凭证上传中，请稍候')
      return
    }

    const valid = await createFormRef.value.validate().catch(() => false)
    if (!valid || !selectedFile.value) return

    creating.value = true
    try {
      const fileKey = await uploadCsvFile(selectedFile.value)
      const data: CreateOrderPackageInvalidateTaskRequest = {
        file_key: fileKey,
        file_name: selectedFile.value.name,
        voucher_keys: toVoucherKeyList(createForm.voucher_keys),
        remark: createForm.remark || undefined
      }
      await OrderPackageInvalidateTaskService.createTask(data)
      ElMessage.success('任务创建成功')
      createDialogVisible.value = false
      await getTableData()
    } catch (error) {
      console.error('创建订单套餐作废任务失败:', error)
      ElMessage.error(getErrorMessage(error, '任务创建失败'))
    } finally {
      creating.value = false
    }
  }

  const handleCreateDialogClosed = () => {
    createFormRef.value?.resetFields()
    uploadRef.value?.clearFiles()
    voucherUploadRef.value?.clearFiles(false)
    selectedFile.value = null
    createForm.file = ''
    createForm.voucher_keys = []
    createForm.remark = ''
    voucherUploading.value = false
  }

  const getActions = (row: OrderPackageInvalidateTask) => {
    const actions: any[] = []
    if (hasAuth('order_package_invalidate_task:detail')) {
      actions.push({ label: '详情', handler: () => handleNameClick(row), type: 'primary' })
    }
    return actions
  }

  onMounted(() => {
    getTableData()
  })
</script>
