<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="120px"
    >
      <el-form-item label="售后登记号" prop="afterSaleId">
        <el-input
          v-model="queryParams.afterSaleId"
          placeholder="请输入售后登记号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="处理类型" prop="processType">
        <el-select
          v-model="queryParams.processType"
          placeholder="请选择处理类型"
          clearable
          filterable
          class="!w-240px"
        >
          <el-option
            v-for="item in processTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="处理结果" prop="processResult">
        <el-input
          v-model="queryParams.processResult"
          placeholder="请输入处理结果"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="处理状态" prop="processStatus">
        <el-select
          v-model="queryParams.processStatus"
          placeholder="请选择处理状态"
          clearable
          filterable
          class="!w-240px"
        >
          <el-option
            v-for="item in processStatusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="处理人" prop="processUser">
        <el-input
          v-model="queryParams.processUser"
          placeholder="请输入处理人"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="处理完成时间" prop="finishTime">
        <el-date-picker
          v-model="queryParams.finishTime"
          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="openForm('create')"
          v-hasPermi="['erp:after-sale-process:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['erp:after-sale-process: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-process: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="processType"
        :formatter="formatProcessType"
      />
      <el-table-column
        label="处理状态"
        align="center"
        prop="processStatus"
        :formatter="formatProcessStatus"
      />
      <el-table-column label="处理人" align="center" prop="processUser" />
      <el-table-column label="用户评价" align="center" prop="userRating">
        <template #default="scope">
          <el-tooltip :content="`${scope.row.userRating || 0} 分`" placement="top">
            <el-icon size="20" :style="{ color: getRatingColor(scope.row.userRating) }">
              <Star />
            </el-icon>
          </el-tooltip>
        </template>
      </el-table-column>
      <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-process:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="success"
            @click="handleProcessComplete(scope.row)"
            v-if="scope.row.processStatus === 1"
            v-hasPermi="['erp:after-sale-process:update']"
          >
            处理完成
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['erp:after-sale-process: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>

  <!-- 表单弹窗：添加/修改 -->
  <AfterSaleProcessForm 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.afterSaleId }}</el-descriptions-item>
      <el-descriptions-item label="处理类型">{{ formatProcessType(detailRow, null as any, detailRow.processType as any) }}</el-descriptions-item>
      <el-descriptions-item label="处理数量">{{ detailRow.processCount ?? '-' }}</el-descriptions-item>
      <el-descriptions-item label="业务订单号">{{ detailRow.relatedOrderId ?? '-' }}</el-descriptions-item>
      <el-descriptions-item label="处理结果">{{ detailRow.processResult ?? '-' }}</el-descriptions-item>
      <el-descriptions-item label="失败原因">{{ detailRow.processFailReason ?? '-' }}</el-descriptions-item>
      <el-descriptions-item label="处理状态">{{ formatProcessStatus(detailRow, null as any, detailRow.processStatus as any) }}</el-descriptions-item>
      <el-descriptions-item label="处理人">{{ detailRow.processUser ?? '-' }}</el-descriptions-item>
      <el-descriptions-item label="处理时间">{{ dateFormatter(detailRow, null as any, detailRow.processTime as any) }}</el-descriptions-item>
      <el-descriptions-item label="处理完成时间">{{ dateFormatter(detailRow, null as any, detailRow.finishTime as any) }}</el-descriptions-item>
      <el-descriptions-item label="用户评价">
        <el-tooltip :content="`${detailRow.userRating || 0} 分`" placement="top">
          <el-icon size="20" :style="{ color: getRatingColor(detailRow.userRating) }">
            <Star />
          </el-icon>
        </el-tooltip>
      </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 { AfterSaleProcessApi, AfterSaleProcess } from '@/api/erp/aftersale/aftersaleprocess'
import { useUserStoreWithOut } from '@/store/modules/user'
import AfterSaleProcessForm from './AfterSaleProcessForm.vue'
import { Star } from '@element-plus/icons-vue'

const processTypeOptions = [
  { label: '退货入库', value: 1 },
  { label: '换货出库', value: 2 },
  { label: '维修处理', value: 3 },
  { label: '退款处理', value: 4 },
  { label: '取消处理', value: 5 },
  { label: '其他', value: 6 }
]

const processStatusOptions = [
  { label: '处理中', value: 1 },
  { label: '处理完成', value: 2 },
  { label: '处理失败', value: 3 }
]

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 formatProcessType = (_row: AfterSaleProcess, _column: any, value: number) =>
  optionLabel(processTypeOptions, value)
const formatProcessStatus = (_row: AfterSaleProcess, _column: any, value: number) =>
  optionLabel(processStatusOptions, value)

/** ERP 售后处理 列表 */
defineOptions({ name: 'AfterSaleProcess' })

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

const loading = ref(true) // 列表的加载中
const list = ref<AfterSaleProcess[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  afterSaleId: undefined,
  processType: undefined,
  processCount: undefined,
  processResult: undefined,
  processEvidence: undefined,
  relatedOrderId: undefined,
  processStatus: undefined,
  processFailReason: undefined,
  processUser: undefined,
  processTime: [],
  finishTime: [],
  createTime: [],
  userRating: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await AfterSaleProcessApi.getAfterSaleProcessPage(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 AfterSaleProcessApi.deleteAfterSaleProcess(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 处理完成操作 */
const handleProcessComplete = async (row: AfterSaleProcess) => {
  try {
    // 处理完成的二次确认
    await message.confirm('确认处理完成吗？')
    // 更新状态为处理完成
    const updateData = {
      ...row,
      processStatus: 2,
      processUser: userStore.getUser?.nickname || row.processUser,
      finishTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
    }
    await AfterSaleProcessApi.updateAfterSaleProcess(updateData)
    message.success('处理完成')
    // 刷新列表
    await getList()
  } catch {}
}

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

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

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

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

/** 根据评分获取颜色 */
const getRatingColor = (rating?: number) => {
  if (!rating || rating === 0) return '#cccccc' // 灰色表示无评价
  if (rating < 4) return '#ff4d4f' // 红色表示差评
  if (rating < 7) return '#ffa940' // 橙色表示一般
  if (rating < 9) return '#52c41a' // 绿色表示好评
  return '#1890ff' // 蓝色表示优秀
}

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