<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="120px"
    >
      <el-form-item label="销售订单" prop="orderId">
        <el-select
          v-model="queryParams.orderId"
          placeholder="请选择销售订单"
          clearable
          filterable
          class="!w-240px"
        >
          <el-option
            v-for="item in saleOrderOptions"
            :key="item.id"
            :label="item.no"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="售后类型" prop="afterSaleType">
        <el-select
          v-model="queryParams.afterSaleType"
          placeholder="请选择售后类型"
          clearable
          filterable
          class="!w-240px"
        >
          <el-option
            v-for="item in afterSaleTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="申请原因" prop="applyReason">
        <el-input
          v-model="queryParams.applyReason"
          placeholder="请输入申请原因"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="申请状态" prop="applyStatus">
        <el-select
          v-model="queryParams.applyStatus"
          placeholder="请选择申请状态"
          clearable
          filterable
          class="!w-240px"
        >
          <el-option
            v-for="item in applyStatusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="申请人" prop="applicant">
        <el-input
          v-model="queryParams.applicant"
          placeholder="请输入申请人"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="审核人" prop="auditUser">
        <el-input
          v-model="queryParams.auditUser"
          placeholder="请输入审核人"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </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="openForm('create')"
          v-hasPermi="['erp:after-sale-register:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['erp:after-sale-register:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
            type="danger"
            plain
            :disabled="isEmpty(checkedIds)"
            @click="handleDeleteBatch"
            v-hasPermi="['erp:after-sale-register:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
        row-key="id"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleRowCheckboxChange"
    >
    <el-table-column type="selection" width="55" />
      <el-table-column label="序号" align="center" type="index" width="80" />
      <el-table-column
        label="售后类型"
        align="center"
        prop="afterSaleType"
        :formatter="formatAfterSaleType"
      />
      <el-table-column
        label="申请状态"
        align="center"
        prop="applyStatus"
        :formatter="formatApplyStatus"
      />
      <el-table-column label="申请人" align="center" prop="applicant" />
      <el-table-column label="审核人" align="center" prop="auditUser" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="200px">
        <template #default="scope">
          <el-button link type="primary" @click="openDetail(scope.row)">详情</el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['erp:after-sale-register:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="success"
            @click="handleAudit(scope.row)"
            v-if="scope.row.applyStatus === 1"
            v-hasPermi="['erp:after-sale-register:update']"
          >
            审核通过
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['erp:after-sale-register:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

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

  <!-- 详情弹窗 -->
  <el-dialog v-model="detailVisible" title="售后登记详情" width="560px">
    <el-descriptions v-if="detailRow" :column="2" border>
      <el-descriptions-item label="销售订单">{{ detailRow.orderId }}</el-descriptions-item>
      <el-descriptions-item label="售后类型">{{ formatAfterSaleType(detailRow, null as any, detailRow.afterSaleType as any) }}</el-descriptions-item>
      <el-descriptions-item label="申请原因">{{ detailRow.applyReason ?? '-' }}</el-descriptions-item>
      <el-descriptions-item label="联系人">{{ detailRow.contactName ?? '-' }}</el-descriptions-item>
      <el-descriptions-item label="联系电话">{{ detailRow.contactPhone ?? '-' }}</el-descriptions-item>
      <el-descriptions-item label="申请状态">{{ formatApplyStatus(detailRow, null as any, detailRow.applyStatus as any) }}</el-descriptions-item>
      <el-descriptions-item label="驳回原因">{{ detailRow.rejectReason ?? '-' }}</el-descriptions-item>
      <el-descriptions-item label="申请人">{{ detailRow.applicant ?? '-' }}</el-descriptions-item>
      <el-descriptions-item label="审核人">{{ detailRow.auditUser ?? '-' }}</el-descriptions-item>
      <el-descriptions-item label="审核时间">{{ dateFormatter(detailRow, null as any, detailRow.auditTime as any) }}</el-descriptions-item>
      <el-descriptions-item label="创建时间">{{ dateFormatter(detailRow, null as any, (detailRow as any).createTime) }}</el-descriptions-item>
    </el-descriptions>
    <template #footer>
      <el-button @click="detailVisible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { AfterSaleRegisterApi, AfterSaleRegister } from '@/api/erp/aftersale/aftersaleregister'
import { SaleOrderApi, SaleOrderVO } from '@/api/erp/sale/order'
import { useUserStoreWithOut } from '@/store/modules/user'
import AfterSaleRegisterForm from './AfterSaleRegisterForm.vue'

const afterSaleTypeOptions = [
  { label: '退货', value: 1 },
  { label: '换货', value: 2 },
  { label: '维修', value: 3 },
  { label: '退款', value: 4 }
]

const applyStatusOptions = [
  { label: '待审核', value: 1 },
  { label: '审核通过', value: 2 },
  { label: '审核驳回', value: 3 },
  { label: '已取消', value: 4 }
]

const optionLabel = (options: { label: string; value: number }[], value?: number | string) => {
  if (value === undefined || value === null || value === '') return '-'
  const match = options.find((item) => item.value === value || item.value === Number(value))
  return match?.label ?? String(value)
}

const formatAfterSaleType = (_row: AfterSaleRegister, _column: any, value: number) =>
  optionLabel(afterSaleTypeOptions, value)
const formatApplyStatus = (_row: AfterSaleRegister, _column: any, value: number) =>
  optionLabel(applyStatusOptions, value)

const saleOrderOptions = ref<SaleOrderVO[]>([])
const fetchSaleOrderOptions = async () => {
  const data = await SaleOrderApi.getSaleOrderPage({ pageNo: 1, pageSize: 100 })
  saleOrderOptions.value = data.list || []
}

/** ERP 售后登记 列表 */
defineOptions({ name: 'AfterSaleRegister' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const userStore = useUserStoreWithOut()

const loading = ref(true) // 列表的加载中
const list = ref<AfterSaleRegister[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  orderId: undefined,
  orderItemId: undefined,
  afterSaleType: undefined,
  applyReason: undefined,
  contactName: undefined,
  contactPhone: undefined,
  applyStatus: undefined,
  rejectReason: undefined,
  applicant: undefined,
  auditUser: undefined,
  auditTime: [],
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await AfterSaleRegisterApi.getAfterSaleRegisterPage(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 openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

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

/** 审核通过操作 */
const handleAudit = async (row: AfterSaleRegister) => {
  try {
    // 审核确认
    await message.confirm('确认审核通过该售后登记吗？')
    // 更新状态为审核通过
    const updateData = {
      ...row,
      applyStatus: 2,
      auditUser: userStore.getUser?.nickname || '',
      auditTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
    }
    await AfterSaleRegisterApi.updateAfterSaleRegister(updateData)
    message.success('审核通过成功')
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除ERP 售后登记 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await AfterSaleRegisterApi.deleteAfterSaleRegisterList(checkedIds.value);
    message.success(t('common.delSuccess'))
    await getList();
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: AfterSaleRegister[]) => {
  checkedIds.value = records.map((item) => item.id);
}

const detailVisible = ref(false)
const detailRow = ref<AfterSaleRegister | null>(null)
const openDetail = (row: AfterSaleRegister) => {
  detailRow.value = row
  detailVisible.value = true
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await AfterSaleRegisterApi.exportAfterSaleRegister(queryParams)
    download.excel(data, 'ERP 售后登记.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
  fetchSaleOrderOptions()
})
</script>
