<template>
  <ElDialog
    v-model="visible"
    :title="dialogTitle"
    width="1400px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div v-if="pickData" class="pick-order-data">
      <div class="pick-order-data-message">
        <Icon style="width: 24px; height: 24px" name="tishi" />
        <span> {{ pickData.overallMessage }}! </span>
      </div>
      <div class="pick-complete-actions" style="margin-bottom: 10px">
        <span class="item">
          <ElButton type="success" @click="handleCreateInbound">
            创建入库单
          </ElButton>
        </span>
      </div>
      <div class="table-view">
        <TableView
          :paginated-data="pickData.pickingSituationList"
          :columns="columns"
          serial-numberable
          selectionable
          @selection-change="handleSelectionChange"
        >
          <template #skuImage="{ row }">
            <el-image
              v-if="row.skuImage"
              :src="row.skuImage"
              style="width: 50px; height: 50px"
              fit="contain"
              :preview-src-list="[row.skuImage]"
              preview-teleported
            />
          </template>
          <template #pickQuantity="{ row }">
            <span style="color: #e6a23c; font-weight: bold">{{
              row.selectedQuantity
            }}</span>
          </template>
          <template #pickStatus="{ row }">
            <span
              v-if="row.pickingStatus === 'fail'"
              style="color: #f56c6c; font-weight: 500"
            >
              ✕ 无法拣胚
            </span>
            <span v-else-if="row.pickingStatus === 'partial'" class="item">
              <ElButton
                type="warning"
                size="small"
                @click="handleAdjustPickOrder(row)"
                >调整拣胚顺序</ElButton
              >
            </span>
            <span
              v-else-if="row.pickingStatus === 'success'"
              style="color: #67c23a; font-weight: 500"
            >
              ✓ 直接拣胚
            </span>
            <span v-else style="color: #999; font-weight: 500">未知状态</span>
          </template>
        </TableView>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer" style="text-align: center">
        <span class="item">
          <ElButton @click="visible = false">取消</ElButton>
        </span>
        <span class="item">
          <ElButton type="primary" @click="handleSubmit"> 确定 </ElButton>
        </span>
      </div>
    </template>
  </ElDialog>
  <OperateDetailsDialog
    ref="operateDetailsDialogRef"
    title="调整拣胚顺序"
    :pickable="true"
    @adjust-pick-order-success="open"
  />
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import {
  pickCompleteByIdsDataApi,
  pickCompleteApi,
  replenishmentCompleteApi,
} from '@/api/factoryOrderNew'
import type { PickCompleteData } from '@/types/api/factoryOrderNew'
import type { BaseRespData } from '@/types/api'
import TableView from '@/components/TableView.vue'
import Icon from '@/components/Icon.vue'
import OperateDetailsDialog from './OperateDetailsDialog.vue'
interface PickData {
  overallMessage?: string
  pickingSituationList?: PickCompleteData[]
  allAvailableOrderIds?: number[]
  partialAvailableOrderIds?: number[]
  unavailableOrderIds?: number[]
}
const emit = defineEmits<{
  success: []
}>()

const visible = ref(false)
const pickData = ref<PickData | null>(null)
const selections = ref<PickCompleteData[]>([])
const dialogTitle = ref('拣胚完成')
const submitApi = ref<(ids: (number | string)[]) => Promise<BaseRespData<void>>>(
  pickCompleteApi,
)

const columns = [
  {
    prop: 'warehouseName',
    label: '仓库名称',
    minWidth: 120,
  },
  {
    key: 'skuImage',
    label: 'SKU图片',
    width: 100,
    align: 'center',
    slot: 'skuImage',
  },
  {
    key: 'productName',
    prop: 'productName',
    label: '商品名称',
    minWidth: 120,
    showOverflowTooltip: true,
  },
  {
    prop: 'supplierProductNo',
    label: '款号',
    width: 100,
    align: 'center',
  },
  {
    key: 'thirdSkuCode',
    prop: 'thirdSkuCode',
    label: '库存SKU',
    align: 'center',
    width: 180,
  },
  {
    key: 'selectedQuantity',
    prop: 'selectedQuantity',
    label: '本次拣胚数量',
    width: 110,
    align: 'right',
    slot: 'pickQuantity',
  },
  {
    prop: 'availableInventory',
    label: '可调配库存',
    width: 100,
    align: 'right',
  },
  {
    prop: 'inventory',
    label: '库存数量',
    width: 90,
    align: 'right',
  },
  {
    prop: 'producingQuantity',
    label: '生产中数量',
    width: 100,
    align: 'right',
  },
  {
    prop: 'occupyInventory',
    label: '占用数量',
    width: 90,
    align: 'right',
  },
  {
    key: 'pickStatus',
    label: '拣胚情况',
    width: 130,
    align: 'center',
    fixed: 'right',
    slot: 'pickStatus',
  },
]

const open = async (
  ids: (number | string)[],
  adjustOrderIds?: number[],
  selectedRow?: PickCompleteData,
  options?: {
    title?: string
    submitType?: 'pick' | 'replenish'
  },
) => {
  const previousPickList = pickData.value?.pickingSituationList ?? []
  selections.value = []
  pickData.value = null
  dialogTitle.value = options?.title || '拣胚完成'
  submitApi.value =
    options?.submitType === 'replenish' ? replenishmentCompleteApi : pickCompleteApi
  const loading = ElLoading.service({
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    let pickIds
    if (selectedRow && adjustOrderIds && adjustOrderIds.length > 0 && !ids) {
      const adjustPickData = previousPickList.find(
        (item: PickCompleteData) =>
          item.thirdSkuCode === selectedRow.thirdSkuCode,
      )
      if (adjustPickData) {
        adjustPickData.allOrderIds = adjustOrderIds
      }
      pickIds = previousPickList
        .map((item: PickCompleteData) => item.allOrderIds)
        .flat()
    }
    const res = await pickCompleteByIdsDataApi(ids || pickIds)
    if (res.code !== 200) return
    pickData.value = res.data || null
    visible.value = true
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}

const handleClose = () => {
  pickData.value = null
}

const handleCreateInbound = () => {
  ElMessage.info('创建入库单功能待实现')
}
const operateDetailsDialogRef = ref()
const handleSelectionChange = (selection: PickCompleteData[]) => {
  selections.value = selection
}
const handleAdjustPickOrder = async (row: PickCompleteData) => {
  operateDetailsDialogRef.value?.open({
    row,
    ids: row.allOrderIds as (number | string)[],
    url: 'factory/podOrderOperation/listByIds',
  })
}

const handleSubmit = async () => {
  const loading = ElLoading.service({
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  const orderIds = pickData.value?.pickingSituationList
    ?.map((item) => item.availableOrderIds)
    .flat()
  try {
    const res = await submitApi.value(orderIds as (number | string)[])
    if (res.code !== 200) return
    ElMessage.success(dialogTitle.value)
    visible.value = false
    emit('success')
  } catch (e) {
    console.error(e)
  } finally {
    loading.close()
  }
}

defineExpose({ open })
</script>

<style scoped lang="scss">
.table-view {
  height: 600px;
}
.pick-order-data-message {
  font-size: 14px;
  color: #f56c6c;
  margin-bottom: 10px;
  font-weight: bold;
  display: flex;
  align-items: center;
}
</style>
