<template>
  <!-- 移动端布局 -->
  <div v-if="isMobile" class="mobile-approved">
    <div class="mobile-header">
      <div class="mobile-header__search">
        <el-select v-model="queryParams.bizTableName" placeholder="业务类型" clearable style="width: 100%" @change="handleQuery"><el-option v-for="item in bizTableOptions" :key="item.value" :label="item.label" :value="item.value" /></el-select>
      </div>
      <div class="mobile-header__actions"><el-button :icon="Filter" circle @click="filterVisible = true" /></div>
    </div>
    <div class="mobile-list" v-loading="loading">
      <div v-if="list.length === 0 && !loading" class="mobile-empty"><el-empty description="暂无已审批记录" /></div>
      <div v-for="item in list" :key="item.id" class="mobile-card" @click="handleViewRecords(item)">
        <div class="mobile-card__header"><span class="mobile-card__no">{{ item.bizId }}</span><el-tag :type="getResultTagType(item.approvalResult)" size="small">{{ getApprovalResultText(item.approvalResult) }}</el-tag></div>
        <div class="mobile-card__body">
          <div class="mobile-card__row"><span class="mobile-card__label">业务类型</span><span class="mobile-card__value">{{ getBizTableLabel(item.bizTableName) }}</span></div>
          <div class="mobile-card__row"><span class="mobile-card__label">申请人</span><span class="mobile-card__value">{{ item.applicantName || '-' }}</span></div>
          <div class="mobile-card__row"><span class="mobile-card__label">审批层级</span><span class="mobile-card__value">第{{ item.approvalLevel }}级</span></div>
          <div class="mobile-card__row"><span class="mobile-card__label">审批意见</span><span class="mobile-card__value mobile-card__value--ellipsis">{{ item.comment || '-' }}</span></div>
          <div class="mobile-card__row"><span class="mobile-card__label">审批时间</span><span class="mobile-card__value">{{ formatDate2(item.approvalTime) }}</span></div>
        </div>
        <div class="mobile-card__footer"><el-button size="small" type="info" @click.stop="handleViewRecords(item)">审批记录</el-button></div>
      </div>
    </div>
    <div class="mobile-pagination" v-if="total > 0"><Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize" :page-sizes="[10, 20]" layout="total, prev, pager, next" :pager-count="5" @pagination="getList" /></div>
    <el-drawer v-model="filterVisible" title="筛选条件" direction="btt" size="50%">
      <el-form :model="queryParams" ref="queryFormRef" label-position="top">
        <el-form-item label="审批结果" prop="approvalResult"><el-select v-model="queryParams.approvalResult" placeholder="请选择审批结果" clearable style="width: 100%"><el-option label="已通过" :value="1" /><el-option label="已驳回" :value="2" /><el-option label="已转审" :value="3" /></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')]" style="width: 100%" /></el-form-item>
      </el-form>
      <template #footer><el-button @click="resetQuery">重置</el-button><el-button type="primary" @click="handleFilterConfirm">确认筛选</el-button></template>
    </el-drawer>
    <ApprovalRecordsDialog ref="approvalDialogRef" />
  </div>

  <!-- PC端布局 -->
  <template v-else>
    <ContentWrap>
      <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
        <el-form-item label="业务类型" prop="bizTableName"><el-select v-model="queryParams.bizTableName" placeholder="请选择业务类型" clearable class="!w-240px"><el-option v-for="item in bizTableOptions" :key="item.value" :label="item.label" :value="item.value" /></el-select></el-form-item>
        <el-form-item label="审批结果" prop="approvalResult"><el-select v-model="queryParams.approvalResult" placeholder="请选择审批结果" clearable class="!w-240px"><el-option label="已通过" :value="1" /><el-option label="已驳回" :value="2" /><el-option label="已转审" :value="3" /></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-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-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="bizId" min-width="120" />
        <el-table-column label="业务类型" align="center" prop="bizTableName" min-width="150"><template #default="scope">{{ getBizTableLabel(scope.row.bizTableName) }}</template></el-table-column>
        <el-table-column label="申请人" align="center" prop="applicantName" min-width="100" />
        <el-table-column label="审批层级" align="center" prop="approvalLevel" min-width="100"><template #default="scope">第{{ scope.row.approvalLevel }}级</template></el-table-column>
        <el-table-column label="审批结果" align="center" prop="approvalResult" min-width="100"><template #default="scope"><el-tag :type="getResultTagType(scope.row.approvalResult)">{{ getApprovalResultText(scope.row.approvalResult) }}</el-tag></template></el-table-column>
        <el-table-column label="审批意见" align="center" prop="comment" min-width="150" />
        <el-table-column label="审批时间" align="center" prop="approvalTime" :formatter="dateFormatter" width="180px" sortable />
        <el-table-column label="操作" align="center" fixed="right" width="120"><template #default="scope"><el-button link type="info" @click="handleViewRecords(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>
    <ApprovalRecordsDialog ref="approvalDialogRef" />
  </template>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { Filter } from '@element-plus/icons-vue'
import { formatDate, dateFormatter } from '@/utils/formatTime'
import { ApprovalRecordApi, ApprovalRecordVO } from '@/api/erp/approval'
import { ApprovalRecordsDialog } from '@/components/Approval'
import { useUserStore } from '@/store/modules/user'
import { useWindowSize } from '@vueuse/core'

defineOptions({ name: 'ErpApprovalApproved' })

const { width } = useWindowSize()
const isMobile = computed(() => width.value < 768)

const userStore = useUserStore()
const loading = ref(true)
const list = ref<ApprovalRecordVO[]>([])
const total = ref(0)
const filterVisible = ref(false)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  approver: undefined as string | undefined,
  bizTableName: undefined as string | undefined,
  approvalResult: undefined as number | undefined,
  createTime: [] as string[]
})
const queryFormRef = ref()

const formatDate2 = (date: any) => {
  if (!date) return '-'
  return formatDate(new Date(date), 'YYYY-MM-DD HH:mm')
}

// 业务类型选项
const bizTableOptions = [
  { label: '库存盘点', value: 'erp_stock_check' },
  { label: '入库单', value: 'erp_stock_in' },
  { label: '出库单', value: 'erp_stock_out' },
  { label: '调拨单', value: 'erp_stock_move' },
  { label: '组装拆卸', value: 'erp_assembly_disassembly' },
  { label: '销售订单', value: 'erp_sale_order' },
  { label: '销售出库', value: 'erp_sale_out' },
  { label: '销售退货', value: 'erp_sale_return' },
  { label: '采购订单', value: 'erp_purchase_order' },
  { label: '采购退货', value: 'erp_purchase_return' },
  { label: '收款单', value: 'erp_finance_receipt' },
  { label: '付款单', value: 'erp_finance_payment' },
  { label: '生产计划', value: 'mes_production_plan' },
  { label: '采购计划', value: 'erp_purchase_requisition' }
]

// 获取业务类型标签
const getBizTableLabel = (value: string) => {
  const option = bizTableOptions.find(item => item.value === value)
  return option ? option.label : value
}

// 获取审批结果文本
const getApprovalResultText = (result: number) => {
  const map: Record<number, string> = {
    1: '已通过',
    2: '已驳回',
    3: '已转审'
  }
  return map[result] || '未知'
}

// 获取审批结果标签类型
const getResultTagType = (result: number) => {
  const map: Record<number, string> = {
    1: 'success',
    2: 'danger',
    3: 'info'
  }
  return map[result] || ''
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    queryParams.approver = String(userStore.getUser.id)
    const data = await ApprovalRecordApi.getApprovedApprovalPage(queryParams)
    list.value = data.list
    total.value = data.total
  } catch (error) {
    console.error('获取已审批列表失败', error)
  } finally {
    loading.value = false
  }
}

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

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

/** 筛选确认 */
const handleFilterConfirm = () => {
  filterVisible.value = false
  handleQuery()
}

/** 查看审批记录 */
const approvalDialogRef = ref()
const handleViewRecords = (row: ApprovalRecordVO) => {
  approvalDialogRef.value.open(row.bizId, row.bizTableName)
}

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

<style lang="scss" scoped>
.mobile-approved {
  padding: 12px;
  background: #f5f5f5;
  min-height: 100vh;
}

.mobile-header {
  display: flex;
  gap: 8px;
  align-items: center;
  margin-bottom: 12px;

  &__search {
    flex: 1;
  }

  &__actions {
    display: flex;
    gap: 4px;
    flex-shrink: 0;
  }
}

.mobile-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.mobile-empty {
  padding: 40px 0;
}

.mobile-card {
  background: #fff;
  border-radius: 10px;
  padding: 14px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);

  &__header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
  }

  &__no {
    font-weight: 600;
    font-size: 15px;
    color: #303133;
  }

  &__body {
    font-size: 13px;
  }

  &__row {
    display: flex;
    justify-content: space-between;
    padding: 3px 0;
  }

  &__label {
    color: #909399;
    flex-shrink: 0;
    margin-right: 12px;
  }

  &__value {
    color: #606266;
    text-align: right;

    &--ellipsis {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      max-width: 200px;
    }
  }

  &__footer {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
    margin-top: 10px;
    padding-top: 10px;
    border-top: 1px solid #f0f0f0;
  }
}

.mobile-pagination {
  margin-top: 12px;
  display: flex;
  justify-content: center;

  :deep(.el-pagination) {
    flex-wrap: wrap;
    justify-content: center;
  }
}
</style>
