<template>
  <!-- 移动端布局 -->
  <el-drawer
    v-if="isMobile"
    v-model="dialogVisible"
    title="选择请购单"
    direction="rtl"
    size="100%"
    :close-on-press-escape="true"
    :destroy-on-close="true"
  >
    <div class="mobile-requisition-select">
      <!-- 搜索栏 -->
      <div class="mobile-requisition-select__search">
        <el-input
          v-model="queryParams.no"
          placeholder="搜索请购单编号"
          clearable
          @keyup.enter="handleQuery"
          :prefix-icon="Search"
        />
        <el-button :icon="Filter" circle @click="filterVisible = true" />
      </div>

      <!-- 卡片列表 -->
      <div class="mobile-requisition-select__body" v-loading="loading">
        <el-empty v-if="list.length === 0 && !loading" description="暂无请购单" />
        <div
          v-for="item in list"
          :key="item.id"
          class="mobile-requisition-select__card"
          @click="handleSingleSelected(item)"
        >
          <div class="mobile-requisition-select__card-header">
            <span class="mobile-requisition-select__card-no">{{ item.no }}</span>
            <div class="mobile-requisition-select__card-tags">
              <el-tag size="small" :type="getTypeTagType(item.type)">{{ getTypeLabel(item.type) }}</el-tag>
              <el-tag size="small" :type="getPriorityTagType(item.priority)">{{ getPriorityLabel(item.priority) }}</el-tag>
            </div>
          </div>
          <div class="mobile-requisition-select__card-body">
            <div class="mobile-requisition-select__card-row">
              <span class="mobile-requisition-select__card-label">请购人</span>
              <span>{{ item.requesterNickname || '-' }}</span>
            </div>
            <div class="mobile-requisition-select__card-row">
              <span class="mobile-requisition-select__card-label">请购部门</span>
              <span>{{ item.requesterDeptName || '-' }}</span>
            </div>
            <div class="mobile-requisition-select__card-row">
              <span class="mobile-requisition-select__card-label">请购时间</span>
              <span>{{ formatDate2(item.requestTime) }}</span>
            </div>
            <div class="mobile-requisition-select__card-nums">
              <div class="mobile-requisition-select__card-num">
                <div class="mobile-requisition-select__card-num-val">{{ item.totalCount || 0 }}</div>
                <div class="mobile-requisition-select__card-num-label">合计数量</div>
              </div>
              <div class="mobile-requisition-select__card-num">
                <div class="mobile-requisition-select__card-num-val mobile-requisition-select__card-num-val--price">
                  {{ item.totalPrice ? '¥' + item.totalPrice.toFixed(2) : '-' }}
                </div>
                <div class="mobile-requisition-select__card-num-label">合计金额</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="mobile-requisition-select__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>
    </div>

    <!-- 筛选抽屉 -->
    <el-drawer v-model="filterVisible" title="筛选条件" direction="btt" size="60%" :append-to-body="true">
      <el-form ref="filterFormRef" :model="queryParams" label-position="top">
        <el-form-item label="请购人" prop="requesterName">
          <el-input v-model="queryParams.requesterName" clearable placeholder="请输入请购人姓名" />
        </el-form-item>
        <el-form-item label="请购时间" prop="requestTime">
          <el-date-picker
            v-model="queryParams.requestTime"
            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="filterVisible = false; handleQuery()">确认筛选</el-button>
      </template>
    </el-drawer>
  </el-drawer>

  <!-- PC端布局 -->
  <Dialog v-else title="选择请购单" v-model="dialogVisible" :appendToBody="true" :scroll="true" width="1080">
    <ContentWrap>
      <el-form :model="queryParams" ref="filterFormRef" :inline="true" label-width="68px" class="-mb-15px">
        <el-form-item label="请购单号" prop="no"><el-input v-model="queryParams.no" placeholder="请输入请购单号" clearable @keyup.enter="handleQuery" class="!w-160px" /></el-form-item>
        <el-form-item label="请购人" prop="requesterName"><el-input v-model="queryParams.requesterName" placeholder="请输入请购人" clearable class="!w-160px" /></el-form-item>
        <el-form-item label="请购时间" prop="requestTime"><el-date-picker v-model="queryParams.requestTime" 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-160px" /></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" :show-overflow-tooltip="true" :stripe="true">
        <el-table-column align="center" width="65"><template #default="{ row }"><el-radio :value="row.id" v-model="selectedId" @change="handleSingleSelected(row)">&nbsp;</el-radio></template></el-table-column>
        <el-table-column label="请购单号" align="center" prop="no" min-width="180" />
        <el-table-column label="类型" align="center" prop="type" width="80"><template #default="scope"><el-tag size="small" :type="getTypeTagType(scope.row.type)">{{ getTypeLabel(scope.row.type) }}</el-tag></template></el-table-column>
        <el-table-column label="优先级" align="center" prop="priority" width="80"><template #default="scope"><el-tag size="small" :type="getPriorityTagType(scope.row.priority)">{{ getPriorityLabel(scope.row.priority) }}</el-tag></template></el-table-column>
        <el-table-column label="请购人" align="center" prop="requesterNickname" width="100" />
        <el-table-column label="请购部门" align="center" prop="requesterDeptName" width="120" />
        <el-table-column label="请购时间" align="center" prop="requestTime" :formatter="dateFormatter2" width="120px" />
        <el-table-column label="合计数量" align="center" prop="totalCount" :formatter="erpCountTableColumnFormatter" />
        <el-table-column label="合计金额" align="center" prop="totalPrice" :formatter="erpPriceTableColumnFormatter" />
      </el-table>
      <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </ContentWrap>
    <template #footer>
      <el-button :disabled="!currentRow" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { computed } from 'vue'
import { Search, Filter } from '@element-plus/icons-vue'
import { formatDate, dateFormatter2 } from '@/utils/formatTime'
import { erpCountTableColumnFormatter, erpPriceTableColumnFormatter } from '@/utils'
import { PurchaseRequisitionApi, PurchaseRequisition } from '@/api/erp/purchaserequisition'
import { CHANGE_EVENT } from 'element-plus'
import { useWindowSize } from '@vueuse/core'

defineOptions({ name: 'PurchaseRequisitionTableSelect' })

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

const total = ref(0)
const list = ref<PurchaseRequisition[]>([])
const loading = ref(false)
const dialogVisible = ref(false)
const filterVisible = ref(false)
const filterFormRef = ref()
const queryParams = ref({
  pageNo: 1,
  pageSize: 10,
  status: 2,
  no: '',
  requesterName: '',
  requestTime: []
})
const selectedId = ref()
const currentRow = ref<PurchaseRequisition>()

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

/** 打开弹窗 */
const open = (currentNo?: string) => {
  dialogVisible.value = true
  selectedId.value = undefined
  currentRow.value = undefined
  if (currentNo) {
    queryParams.value.no = currentNo
  } else {
    queryParams.value.no = ''
  }
  resetQuery()
}
defineExpose({ open })

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

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value = {
    pageNo: 1,
    pageSize: 10,
    status: 2,
    no: '',
    requesterName: '',
    requestTime: []
  }
  getList()
}

/** 单选中时触发 */
const handleSingleSelected = (row: PurchaseRequisition) => {
  if (isMobile.value) {
    emits(CHANGE_EVENT, row)
    dialogVisible.value = false
  }
  selectedId.value = row.id
  currentRow.value = row
}

/** 提交选择 */
const submitForm = () => {
  if (currentRow.value) {
    emits(CHANGE_EVENT, currentRow.value)
  }
  dialogVisible.value = false
}

const emits = defineEmits<{
  change: [requisition: PurchaseRequisition]
}>()

const getTypeTagType = (type: number) => {
  switch (type) {
    case 1: return 'success'
    case 2: return 'warning'
    case 3: return 'info'
    default: return ''
  }
}

const getTypeLabel = (type: number) => {
  switch (type) {
    case 1: return '请购'
    case 2: return '补货'
    case 3: return '其他'
    default: return '未知'
  }
}

const getPriorityTagType = (priority: number) => {
  switch (priority) {
    case 1: return 'info'
    case 2: return ''
    case 3: return 'warning'
    case 4: return 'danger'
    default: return ''
  }
}

const getPriorityLabel = (priority: number) => {
  switch (priority) {
    case 1: return '低'
    case 2: return '中'
    case 3: return '高'
    case 4: return '紧急'
    default: return '未知'
  }
}
</script>

<style lang="scss" scoped>
.mobile-requisition-select {
  padding: 12px;
  &__search {
    display: flex;
    gap: 8px;
    align-items: center;
    margin-bottom: 12px;
  }
  &__body {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }
  &__card {
    background: #fff;
    border-radius: 10px;
    padding: 12px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
    cursor: pointer;
    transition: box-shadow 0.2s;
    &:active {
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
    }
  }
  &__card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
  }
  &__card-no {
    font-weight: 600;
    font-size: 14px;
    color: #303133;
  }
  &__card-tags {
    display: flex;
    gap: 4px;
  }
  &__card-body {
    font-size: 13px;
  }
  &__card-row {
    display: flex;
    justify-content: space-between;
    color: #606266;
    padding: 2px 0;
  }
  &__card-label {
    color: #909399;
    flex-shrink: 0;
    margin-right: 10px;
  }
  &__card-nums {
    display: flex;
    justify-content: space-around;
    margin-top: 8px;
    padding-top: 8px;
    border-top: 1px solid #f0f0f0;
  }
  &__card-num {
    text-align: center;
  }
  &__card-num-val {
    font-size: 14px;
    font-weight: 600;
    color: #303133;
    &--price {
      color: #e6a23c;
    }
  }
  &__card-num-label {
    font-size: 11px;
    color: #909399;
    margin-top: 2px;
  }
  &__pagination {
    margin-top: 12px;
    display: flex;
    justify-content: center;
    :deep(.el-pagination) {
      flex-wrap: wrap;
      justify-content: center;
    }
  }
}
</style>
