<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>
      </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, ElMessageBox, ElLoading } from 'element-plus'
import BigNumber from 'bignumber.js'
import { pickCompleteByIdsDataApi } from '@/api/factoryOrderNew'
import type { PickCompleteData } from '@/types/api/factoryOrderNew'
import TableView from '@/components/TableView.vue'
import _ from 'lodash'
import CreateOutboundDialog from './CreateOutboundDialog.vue'

/** 当前可用库存 = 当前库存数量 − 占用 − 冻结 */
function getCurrentAvailableInventory(row: PickCompleteData): BigNumber {
  return new BigNumber(row.inventory ?? 0)
    .minus(row.occupyInventory ?? 0)
    .minus(row.freezeInventory ?? 0)
}

/** 建议出库数量 = 当前库存 − 生产中数量 */
function getSuggestOutQuantity(row: PickCompleteData): BigNumber {
  return new BigNumber(row.inventory ?? 0).minus(row.producingQuantity ?? 0)
}

/** 出库后库存数量 = 当前库存 − 建议出库数量 */
function getAfterOutStock(row: PickCompleteData): BigNumber {
  return new BigNumber(row.inventory ?? 0).minus(getSuggestOutQuantity(row))
}

/** 出库后可用库存 = 出库后库存 − 占用 − 冻结 */
function getAfterOutAvailable(row: PickCompleteData): BigNumber {
  return getAfterOutStock(row)
    .minus(row.occupyInventory ?? 0)
    .minus(row.freezeInventory ?? 0)
}

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

const visible = ref(false)
const tableData = ref<PickCompleteData[]>([])
const orderIds = ref<(number | string)[]>([])
const dialogTitle = ref('拣胚失败')
const selections = ref<PickCompleteData[]>([])
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,
  },
  {
    prop: 'supplierProductNo',
    label: '款号',
    width: 140,
    align: 'center',
  },
  {
    key: 'thirdSkuCode',
    prop: 'thirdSkuCode',
    label: '库存SKU',
    minWidth: 160,
  },
  {
    prop: 'inventory',
    label: '当前库存数量',
    minWidth: 120,
    align: 'right',
  },
  {
    prop: 'occupyInventory',
    label: '占用数量',
    minWidth: 90,
    align: 'right',
  },
  {
    key: 'currentAvailableInventory',
    prop: 'currentAvailableInventory',
    label: '当前可用库存',
    minWidth: 120,
    align: 'right',
    render: (row: PickCompleteData) => {
      return <span>{getCurrentAvailableInventory(row).toNumber()}</span>
    },
  },
  {
    prop: 'producingQuantity',
    label: '生产中数量',
    minWidth: 110,
    align: 'right',
    slot: 'producingQuantity',
  },
  {
    key: 'suggestOutQuantity',
    prop: 'suggestOutQuantity',
    label: '建议出库数量',
    minWidth: 120,
    align: 'right',
    render: (row: PickCompleteData) => {
      return (
        <span style="color: #f56c6c; font-weight: bold">
          {getSuggestOutQuantity(row).toNumber()}
        </span>
      )
    },
  },
  {
    key: 'afterOutStock',
    prop: 'afterOutStock',
    label: '出库后库存数量',
    minWidth: 130,
    align: 'right',
    render: (row: PickCompleteData) => {
      return (
        <span style="color: #e6a23c; font-weight: bold">
          {getAfterOutStock(row).toNumber()}
        </span>
      )
    },
  },
  {
    prop: 'occupyInventory',
    label: '出库后占用数量',
    minWidth: 130,
    align: 'right',
  },
  {
    prop: 'afterOutAvailable',
    label: '出库后可用库存',
    minWidth: 130,
    align: 'right',
    render: (row: PickCompleteData) => {
      return (
        <span style="color: #f56c6c; font-weight: bold">
          {getAfterOutAvailable(row).toNumber()}
        </span>
      )
    },
  },
]

const handleSelectionChange = (selection: PickCompleteData[]) => {
  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 pickCompleteByIdsDataApi(ids)
    tableData.value = res.data?.pickingSituationList || []
  } 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 PickCompleteData & {
    warehouseName?: string
  }
  const warehouseName = firstSelection.warehouseName

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

      return {
        thirdSkuCode: row.thirdSkuCode || '',
        suggestOutQuantity: getSuggestOutQuantity(row).toNumber(),
      }
    })
    .filter((item) => item.suggestOutQuantity !== 0)

  if (items.length === 0) {
    ElMessageBox.alert('建议出库数量=0，无法快速创建出库单！', '提示', {
      type: 'warning',
    })
    return
  }

  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>
