<template>
  <el-dialog title="发货" v-model="show" width="700px">
    <el-form :model="form" ref="formRef" :rules="rules" label-width="85px">
      <el-row :gutter="20">
        <el-col :span="8" :offset="0">
          <el-form-item label="待发数量">
            <span class="font-bold">：{{ form.sendTotalNum }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="16" :offset="0">
          <el-form-item label="发货方式">
            <el-radio-group v-model="form.sendType" :disabled="autoAuditPurchase == 'false'">
              <el-radio :label="1">
                <Tooltip
                  message="必须在进销存的“通用配置-常规配置”中，将 ’采购申请自动通过‘ 设置为“是”"
                />
                立即采购发货
              </el-radio>
              <el-radio :label="2"> 使用库存发货 </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <template v-if="form.sendType == 1">
        <el-row :gutter="20">
          <el-col :span="12" :offset="0">
            <el-form-item label="供应商" prop="supplier">
              <el-select v-model="form.supplier" placeholder="选择供应商" filterable>
                <el-option
                  v-for="item in supplierOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="采购数量" prop="num">
              <el-input-number
                :min="form.sendTotalNum"
                v-model="form.num"
                :controls="false"
                placeholder="请输入"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" :offset="0">
            <el-form-item label="采购单价" prop="unitPrice">
              <el-input-number
                :min="0"
                :controls="false"
                v-model="form.unitPrice"
                placeholder="请输入"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="存放仓库" prop="warehouseId">
              <el-select
                v-model="form.warehouseId"
                placeholder="请选择"
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="item in warehouseOptions"
                  :key="item.warehouseId"
                  :label="item.warehouseName"
                  :value="item.warehouseId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" :offset="0">
            <el-form-item label="其他支出">
              <el-select v-model="extraPay.extraPayType" placeholder="其他支出类型" filterable>
                <el-option
                  v-for="item in extraPayOptions"
                  :key="item.id"
                  :label="item.extraPayName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="支出金额">
              <el-input-number v-model="extraPay.extraPayMoney" :controls="false" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24" :offset="0">
            <el-form-item label="支出备注">
              <el-input v-model="extraPay.remark" placeholder="备注信息" />
            </el-form-item>
          </el-col>
        </el-row>
      </template>
      <template v-else>
        <el-table :data="inventoryList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="batchNo" label="入库批次号" width="150px" />
          <el-table-column prop="warehouseName" label="存放仓库" width="120px" />
          <el-table-column prop="price" label="采购价" width="90px" />
          <el-table-column prop="num" label="剩余库存" width="90px" />
          <el-table-column label="发货数量">
            <template #default="{ row }">
              <el-input-number
                v-model="row.sendNum"
                size="small"
                :min="1"
                :max="row.num"
                :controls="false"
              />
            </template>
          </el-table-column>
        </el-table>
      </template>
      <el-form-item label="发货备注">
        <Editor v-model:modelValue="form.remark" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span>
        <el-button @click="show = false">取 消</el-button>
        <el-button :disabled="formLoading" type="primary" @click="onSubmit">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup name="DialogDelivery">
import { getSimpleWarehouseList, getRemainInventoryList } from '@/api/mall/warehouse'
import { createDelivery } from '@/api/clue/delivery'
import { getConfigList } from '@/api/system/set'
import { getDictOptions } from '@/utils/dict'
import { getExtraFeeSimpleList } from '@/api/clue/extraFee'

const message = useMessage() // 消息弹窗

const warehouseOptions = ref([])
const extraPayOptions = ref([])
const supplierOptions = getDictOptions('erp_supplier')
function getOptions() {
  getSimpleWarehouseList().then((data) => {
    warehouseOptions.value = data
  })
  getExtraFeeSimpleList().then((data) => {
    extraPayOptions.value = data
  })
}

function getRemainInventory(signProductId) {
  getRemainInventoryList({ signProductId }).then((data) => {
    inventoryList.value = data
  })
}

const show = ref(false)
function open(row) {
  show.value = true
  resetForm(row)
  getRemainInventory(row.id)
}
defineExpose({
  open
})

const form = ref({})
const extraPay = ref({})
const rules = ref({
  supplier: { required: true, message: '供应商不可为空', trigger: 'change' },
  warehouseId: { required: true, message: '仓库不可为空', trigger: 'change' },
  num: { required: true, message: '采购数量不可为空', trigger: 'change,blur' },
  unitPrice: { required: true, message: '采购单价不可为空', trigger: 'change,blur' },
  warehouseId: { required: true, message: '仓库不可为空', trigger: 'change' }
})
function resetForm(row) {
  form.value = {
    sendType: 2,
    sendTotalNum: row.signNum,
    signProductId: row.id,
    productId: row.productId,
    specsId: row.specsId,
    warehouseId: undefined,
    supplier: undefined,
    num: row.signNum,
    unitPrice: undefined,
    remark: undefined
  }
  extraPay.value = {
    extraPayType: undefined,
    extraPayMoney: undefined,
    remark: undefined
  }
}

const emit = defineEmits(['success'])
const formLoading = ref(false)
const formRef = ref()
async function onSubmit() {
  // 校验表单
  if (!formRef.value) return

  if (form.value.sendType == 1) {
    const valid = await formRef.value.validate()
    if (!valid) return
  } else {
    if (!deliveryArr.value.length) {
      message.info('请选择库存发货！')
      return
    } else {
      const deliveryCount = deliveryArr.value.reduce((pre, cur) => pre + cur.sendNum, 0)
      if (deliveryCount < form.value.sendTotalNum) {
        message.info('所选发货库存少于待发货数量，请重新选择后再发货！')
        return
      } else if (deliveryCount > form.value.sendTotalNum) {
        message.info('所选发货库存多于待发货数量，请重新选择后再发货！')
        return
      }
    }
  }

  // 提交请求
  formLoading.value = true
  try {
    let params = {
      signProductId: form.value.signProductId,
      sendType: form.value.sendType,
      remark: form.value.remark
    }
    if (params.sendType == 1) {
      params.purchaseOrder = {
        productId: form.value.productId,
        specsId: form.value.specsId,
        supplier: form.value.supplier,
        num: form.value.num,
        unitPrice: form.value.unitPrice,
        warehouseId: form.value.warehouseId
      }
      if (extraPay.value.extraPayMoney) {
        params.purchaseOrder.extraPay = [extraPay.value]
      }
    } else {
      params.detailList = deliveryArr.value
    }

    await createDelivery(params)
    message.success('发货成功！')
    show.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const inventoryList = ref([])

const deliveryArr = ref([])
function handleSelectionChange(val) {
  deliveryArr.value = val
}

const autoAuditPurchase = ref('false')
onMounted(() => {
  getOptions()
  getConfigList({ module: 3 }).then((data) => {
    // 获取所有配置项
    autoAuditPurchase.value = data.find(
      (it) => it.configKey == 'purchaseAuditAutoCompleteConfig'
    ).configValue
  })
})
</script>

<style lang="scss" scoped></style>
