<template>
  <ElDialog
    v-model="visible"
    :title="dialogTitle"
    width="1400px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="pick-fail-info">
      <span>
        您选择了
        <strong>{{ orderIds.length }}</strong>
        件操作单，如拣胚失败，库位没有实物库存，
        <strong style="color: #f56c6c"> 建议创建出库单 </strong>
        ，详细库存信息如下：
      </span>
    </div>
    <div class="table-view">
      <TableView
        :paginated-data="tableData"
        :columns="columns"
        selectionable
        serial-numberable
        @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 #producingQuantity="{ row }">
          <span style="color: #e6a23c; font-weight: bold">{{
            row.producingQuantity
          }}</span>
        </template>
        <template #suggestOutQuantity="{ row }">
          <span style="color: #f56c6c; font-weight: bold">{{
            row.suggestOutQuantity
          }}</span>
        </template>
        <template #afterOutStock="{ row }">
          <span style="color: #f56c6c">{{ row.afterOutStock }}</span>
        </template>
      </TableView>
    </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="handleCreateOutbound">
            快速创建出库单
          </ElButton>
        </span>
      </div>
    </template>
  </ElDialog>

  <CreateOutboundDialog
    ref="createOutboundDialogRef"
    @success="() => {
      visible = false
      emit('success')
    }"
  />
</template>

<script setup lang="tsx">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import {
  applyForReplenishByIdApi,
} from '@/api/factoryOrderNew'
import type { operateOrderListData } from '@/types/api/factoryOrderNew'
import TableView from '@/components/TableView.vue'
import _ from 'lodash'
import CreateOutboundDialog from './CreateOutboundDialog.vue'

const emit = defineEmits<{
  success: []
}>()

const visible = ref(false)
const tableData = ref<operateOrderListData[]>([])
const orderIds = ref<(number | string)[]>([])
const dialogTitle = ref('拣胚失败')
const selections = ref<operateOrderListData[]>([])
const columns = [
  {
    key: 'warehouseName',
    prop: 'warehouseName',
    label: '仓库名称',
    minWidth: 120,
  },
  {
    key: 'skuImage',
    label: 'SKU图片',
    width: 100,
    align: 'center',
    slot: 'skuImage',
  },
  {
    key: 'productName',
    prop: 'productName',
    label: '商品名称',
    minWidth: 160,
    showOverflowTooltip: true,
  },
  {
    key: 'batchArrangeNumber',
    prop: 'batchArrangeNumber',
    label: '款号',
    width: 100,
    align: 'center',
  },
  {
    key: 'thirdSkuCode',
    prop: 'thirdSkuCode',
    label: '库存SKU',
    minWidth: 160,
  },
  {
    prop: 'inventory',
    label: '当前库存数量',
    minWidth: 120,
    align: 'right',
  },
  {
    prop: 'occupyInventory',
    label: '占用数量',
    minWidth: 90,
    align: 'right',
  },
  {
    prop: 'inventory',
    label: '当前可用库存',
    minWidth: 120,
    align: 'right',
  },
  {
    prop: 'producingQuantity',
    label: '生产中数量',
    minWidth: 110,
    align: 'right',
    slot: 'producingQuantity',
  },
  {
    prop: 'suggestOutQuantity',
    label: '建议出库数量',
    minWidth: 120,
    align: 'right',
    slot: 'suggestOutQuantity',
    render: (row: operateOrderListData) => {
      return (
        <span style="color: #f56c6c; font-weight: bold">
          {_.subtract(
            Number(row.inventory ?? 0),
            Number(row.producingQuantity ?? 0),
          )}
        </span>
      )
    },
  },
  {
    prop: 'producingQuantity',
    label: '出库后库存数量',
    minWidth: 130,
    align: 'center',
    slot: 'right',
  },
  {
    prop: 'inventory',
    label: '出库后占用数量',
    minWidth: 130,
    align: 'right',
  },
  {
    prop: 'afterOutAvailable',
    label: '出库后可用库存',
    minWidth: 130,
    align: 'right',
    render: (row: operateOrderListData) => {
      return (
        <span style="color: #f56c6c; font-weight: bold">
          {_.subtract(
            _.subtract(
              Number(row.producingQuantity ?? 0),
              Number(row.inventory ?? 0),
            ),
            Number(row.freezeInventory ?? 0),
          )}
        </span>
      )
    },
  },
]

const handleSelectionChange = (selection: operateOrderListData[]) => {
  selections.value = selection
}

const open = async (
  ids: (number | string)[],
  options?: { title?: string; submitType?: string },
) => {
  dialogTitle.value = options?.title || '拣胚失败'
  orderIds.value = ids
  visible.value = true
  const loading = ElLoading.service({
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    const res = await applyForReplenishByIdApi(
      ids,
      'factory/podOrderOperation/listByIds',
    )
    tableData.value = res.data || []
  } catch (_e) {
    tableData.value = []
  } finally {
    loading.close()
  }
}

const handleClose = () => {
  tableData.value = []
}

const createOutboundDialogRef = ref<InstanceType<
  typeof CreateOutboundDialog
> | null>(null)

const handleCreateOutbound = () => {
  if (selections.value.length === 0) {
    ElMessage.warning('请至少选择一条数据')
    return
  }

  const warehouseIds = _.uniq(
    selections.value
      .map((item) => item.warehouseId)
      .filter((id) => id !== undefined && id !== null),
  )

  if (warehouseIds.length !== 1) {
    ElMessage.warning('请选择相同仓库的库存SKU！')
    return
  }

  const warehouseId = warehouseIds[0] as number | string
  const firstSelection = selections.value[0] as operateOrderListData & {
    warehouseName?: string
  }
  const warehouseName = firstSelection.warehouseName

  const items = selections.value.map((item) => {
    const row = item as operateOrderListData & {
      thirdSkuCode?: string
      inventory?: number
      producingQuantity?: number
    }

    return {
      thirdSkuCode: row.thirdSkuCode || '',
      suggestOutQuantity: _.subtract(
        Number(row.inventory ?? 0),
        Number(row.producingQuantity ?? 0),
      ),
    }
  })

  createOutboundDialogRef.value?.open({
    warehouseId,
    warehouseName,
    items,
  })
}

defineExpose({ open })
</script>

<style scoped lang="scss">
.pick-fail-info {
  font-size: 14px;
  color: #606266;
  line-height: 1.8;
}
.table-view {
  height: 600px;
}
</style>
