<template>
  <ElDialog
    v-model="visible"
    title="供应商发货"
    width="1400px"
    top="15vh"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <div class="supplier-dispatch-order-page">
      <div class="form-section">
        <ElForm ref="formRef" :model="formData" label-width="110px" inline>
          <div class="form-row">
            <ElFormItem label="备货单号" class="form-item">
              <ElInput
                v-model="formData.stockingUpManageNo"
                disabled
                placeholder="系统自动带出"
                style="width: 100%"
              />
            </ElFormItem>
            <ElFormItem
              label="备货仓库"
              prop="warehouseId"
              class="form-item"
              :rules="[
                {
                  required: true,
                  message: '请选择备货仓库',
                  trigger: 'change',
                },
              ]"
            >
              <ElSelect
                v-model="formData.warehouseId"
                placeholder="请选择"
                filterable
                clearable
                style="width: 100%"
              >
                <ElOption
                  v-for="item in warehouseList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </ElSelect>
            </ElFormItem>
            <ElFormItem
              label="预计到货日期"
              prop="expectDeliveryTime"
              class="form-item"
              :rules="[
                {
                  required: true,
                  message: '请选择预计到货日期',
                  trigger: 'change',
                },
              ]"
            >
              <ElDatePicker
                v-model="formData.expectDeliveryTime"
                type="datetime"
                placeholder="请选择"
                value-format="YYYY-MM-DD HH:mm:ss"
                clearable
                style="width: 100%"
              />
            </ElFormItem>
          </div>
        </ElForm>
      </div>

      <div class="table-section">
        <TableView
          ref="tableViewRef"
          :paginated-data="formData.detailsList ?? []"
          :serial-numberable="true"
          :columns="tableColumns"
          :selectionable="true"
          @selection-change="handleSelectionChange"
        >
          <template #currentShipQuantity="{ row }">
            <ElInput
              v-model="row.currentShipQuantity"
              clearable
              size="small"
              style="width: 100px"
              @blur="validateField(row, 'currentShipQuantity')"
            />
            <div v-if="row._currentShipQuantityError" class="field-error">
              {{ row._currentShipQuantityError }}
            </div>
          </template>
        </TableView>
      </div>

      <div class="action-section">
        <ElButton type="success" @click="handleAutoFillQuantity">
          剩余待发货数量>>本次发货数量
        </ElButton>
        <ElButton type="danger" @click="handleDeleteSelected">删除</ElButton>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <ElButton size="large" @click="visible = false">取消</ElButton>
        <ElButton size="large" type="danger" @click="handleDispatch">
          发货
        </ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="tsx">
import { ref } from 'vue'
import type { FormInstance } from 'element-plus'
import type {
  TableData,
  StockingOrderProduct,
  AddStockingOrderForm,
} from '@/types/api/supply/stockingOrder'
import type { WarehouseListData } from '@/types'
import {
  getStockingOrderDetailByIdApi,
  supplierDispatchApi,
} from '@/api/supplier/stockingOrder'
import TableView from '@/components/TableView.vue'
import { BigNumber } from 'bignumber.js'

const props = defineProps<{
  warehouseList: WarehouseListData[]
}>()

const emit = defineEmits<{
  (e: 'refresh'): void
}>()

const visible = ref(false)
const currentRow = ref<TableData | null>(null)

const formRef = ref<FormInstance>()
const formData = ref<AddStockingOrderForm>({
  stockingUpManageNo: '',
  warehouseId: undefined as number | undefined,
  expectDeliveryTime: '',
  detailsList: [],
})
const selectedProducts = ref<StockingOrderProduct[]>([])

const tableColumns = computed(() => [
  {
    label: 'SKU图片',
    prop: 'skuImage',
    width: 100,
    align: 'center',
    render: (item: StockingOrderProduct) => (
      <el-image
        preview-teleported
        src={item.warehouseSkuImage}
        preview-src-list={[item.warehouseSkuImage]}
        z-index={9999}
        style="width: 60px;height: 60px;text-align: center;"
      />
    ),
  },
  {
    label: '商品名称',
    prop: 'warehouseSkuName',
    minWidth: 150,
    align: 'left',
    showOverflowTooltip: true,
  },
  {
    label: '款号',
    prop: 'productNo',
    width: 120,
    align: 'center',
  },
  {
    label: '库存SKU',
    prop: 'warehouseSku',
    width: 180,
    align: 'center',
  },
  {
    label: '备货数量',
    prop: 'buyAmount',
    width: 100,
    align: 'right',
  },
  {
    label: '已入库数量',
    prop: 'buyStored',
    width: 100,
    align: 'right',
    render: (item: StockingOrderProduct) => (
      <span style="color: #409EFF; font-weight: 500;">
        {item.buyStored ?? 0}
      </span>
    ),
  },
  {
    label: '已发货数量',
    prop: 'shipmentQuantity',
    width: 100,
    align: 'right',
    render: (item: StockingOrderProduct) => (
      <span style="color: #E6A23C; font-weight: 500;">
        {item.shipmentQuantity ?? 0}
      </span>
    ),
  },
  {
    label: '剩余待发货数量',
    prop: 'remainingQuantity',
    width: 140,
    align: 'right',
    render: (item: StockingOrderProduct) => (
      <span style="color: #F56C6C; font-weight: 500;">
        {item.remainingQuantity ?? 0}
      </span>
    ),
  },
  {
    label: '本次发货数量',
    slot: 'currentShipQuantity',
    width: 140,
    align: 'center',
  },
])

const handleAutoFillQuantity = () => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请选择要自动填充的商品')
    return
  }
  selectedProducts.value.forEach((item) => {
    if (item.remainingQuantity && item.remainingQuantity > 0) {
      item.currentShipQuantity = item.remainingQuantity
    }
  })
}
const handleSelectionChange = (selection: StockingOrderProduct[]) => {
  selectedProducts.value = selection
}

const handleDeleteSelected = () => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请先选择要删除的商品')
    return
  }

  const selectedSkus = selectedProducts.value.map((item) => item.warehouseSku)
  formData.value.detailsList = formData.value.detailsList?.filter(
    (item) => !selectedSkus.includes(item.warehouseSku),
  )
  selectedProducts.value = []
}
const validateDetailsList = (): boolean => {
  if (!formData.value.detailsList?.length) {
    return true
  }

  let isValid = true
  formData.value.detailsList.forEach((row) => {
    const extendedRow = row as StockingOrderProductWithError
    validateField(extendedRow, 'currentShipQuantity')
    if (extendedRow._currentShipQuantityError) {
      isValid = false
    }
  })
  return isValid
}

const handleDispatch = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
  } catch {
    return
  }

  if (formData.value.detailsList?.length === 0) {
    ElMessage.warning('没有可发货的商品')
    return
  }

  if (!validateDetailsList()) {
    ElMessage.warning('请检查本次发货数量是否正确填写')
    return
  }

  const overQuantitySkus = (formData.value.detailsList || [])
    .filter(
      (item) =>
        Number(item.currentShipQuantity) > (item.remainingQuantity ?? 0),
    )
    .map((item) => item.warehouseSku)

  if (overQuantitySkus.length > 0) {
    try {
      await ElMessageBox.alert(
        `<div style="line-height: 1.6;"><span style="white-space: nowrap; flex-shrink: 0;">库存SKU:</span><span style="word-break: break-all; margin-left: 4px;">${overQuantitySkus.join(
          ',',
        )}</span><span style="margin-top: 12px;">本次发货数量大于剩余待发货数量，是否确认发货?</span></div>`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          customClass: 'over-quantity-alert-box',
          dangerouslyUseHTMLString: true,
        },
      )
    } catch {
      return
    }
  }
  const loading = ElLoading.service({
    lock: true,
    text: '正在提交...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  const {
    stockingUpManageNo,
    warehouseId,
    expectDeliveryTime,
    currencyCode,
    detailsList,
  } = formData.value
  const warehouseName = props.warehouseList.find(
    (item) => item.id === warehouseId,
  )?.name
  try {
    const res = await supplierDispatchApi({
      manageId: currentRow.value?.id as number,
      manageNo: stockingUpManageNo as string,
      warehouseId: warehouseId as number,
      warehouseName: warehouseName as string,
      expectDeliveryTime: expectDeliveryTime as string,
      currencyCode: currencyCode as string,
      detailsList:
        detailsList?.map((e) => ({
          ...e,
          shipmentQuantity: Number(e.currentShipQuantity ?? 0),
          currentShipQuantity: undefined,
          remainingQuantity: undefined,
        })) || [],
    })
    if (res.code !== 200) return
    ElMessage.success('发货成功')
    emit('refresh')
    visible.value = false
  } catch (error) {
    console.error(error)
  } finally {
    loading.close()
  }
}

const open = async (row: TableData) => {
  if (!row?.id) return
  selectedProducts.value = []
  const loading = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  try {
    const res = await getStockingOrderDetailByIdApi(row.id)
    if (res.code !== 200) {
      ElMessage.warning(res.message)
      return
    }
    const {
      stockingUpManageNo,
      warehouseId,
      detailsList,
      warehouseName,
      currencyCode,
    } = res.data
    formData.value = {
      stockingUpManageNo,
      warehouseId,
      warehouseName,
      currencyCode,
      detailsList: detailsList?.map((item) => ({
        ...item,
        remainingQuantity: new BigNumber(item.buyAmount || 0)
          .minus(item.shipmentQuantity || 0)
          .toNumber(),
        currentShipQuantity: undefined,
      })),
    }
    currentRow.value = row
    visible.value = true
  } catch (error) {
    console.error(error)
  } finally {
    loading.close()
  }
}
type StockingOrderProductWithError = StockingOrderProduct & {
  _currentShipQuantityError?: string
}
const validateField = (
  row: StockingOrderProductWithError,
  field: 'currentShipQuantity',
) => {
  const value = row[field]
  const strValue = value === 0 || value === '0' ? '0' : String(value ?? '')
  // const fieldLabel = '本次发货数量'

  if (!strValue) {
    if (field === 'currentShipQuantity')
      row._currentShipQuantityError = '必填项'
  } else if (!/^\d+$/.test(strValue)) {
    if (field === 'currentShipQuantity')
      row._currentShipQuantityError = '只能输入正整数'
  } else {
    if (field === 'currentShipQuantity') row._currentShipQuantityError = ''
  }
}

defineExpose({ open })
</script>

<style lang="scss" scoped>
.supplier-dispatch-order-page {
  .form-section {
    margin-bottom: 16px;

    .form-row {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
    }

    .form-item {
      flex: 1;
      min-width: 280px;
      max-width: 350px;
    }

    :deep(.el-select),
    :deep(.el-input),
    :deep(.el-date-editor) {
      width: 100%;
    }
  }

  .table-section {
    height: 450px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
  }

  .action-section {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-top: 16px;
  }
}

.dialog-footer {
  text-align: center;
}

.field-error {
  color: #f56c6c;
  font-size: 12px;
  line-height: 1;
  margin-top: 2px;
}
</style>

<style>
.over-quantity-alert-box {
  width: 1000px !important;
  max-width: 90vw !important;
}

.over-quantity-alert-box .el-message-box__message {
  word-break: break-all;
  line-height: 1.6;
  padding: 10px 0;
}
</style>
