<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1440">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
      :disabled="disabled"
    >
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="换货单号" prop="no">
            <el-input disabled v-model="formData.no" placeholder="保存时自动生成" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="换货时间" prop="exchangeTime">
            <el-date-picker
              v-model="formData.exchangeTime"
              type="date"
              value-format="x"
              placeholder="选择换货时间"
              class="!w-1/1"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="关联出库单" prop="outNo">
            <el-input readonly>
              <template #prefix>
                <el-link
                  v-if="formData.outNo && formData.outId"
                  type="primary"
                  :underline="false"
                  @click.stop="openSaleOutDetail"
                  class="order-link"
                >
                  {{ formData.outNo }}
                </el-link>
              </template>
              <template #append>
                <el-button @click="openSaleOutEnableList">
                  <Icon icon="ep:search" /> 选择
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="客户" prop="customerId">
            <el-select
              v-model="formData.customerId"
              clearable
              filterable
              disabled
              placeholder="请选择客户"
              class="!w-1/1"
            >
              <el-option
                v-for="item in customerList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="销售人员" prop="saleUserId">
            <el-select
              v-model="formData.saleUserId"
              clearable
              filterable
              placeholder="请选择销售人员"
              class="!w-1/1"
            >
              <el-option
                v-for="item in userList"
                :key="item.id"
                :label="item.nickname"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="备注" prop="remark">
            <el-input
              type="textarea"
              v-model="formData.remark"
              :rows="1"
              placeholder="请输入备注"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="附件" prop="fileUrl">
            <UploadFile :is-show-tip="false" v-model="formData.fileUrl" :limit="1" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 换货商品清单 -->
      <ContentWrap>
        <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px">
          <el-tab-pane label="换入商品清单" name="inItems">
            <SaleExchangeInItemForm
              ref="inItemFormRef"
              :items="formData.inItems"
              :disabled="disabled"
              @change="calculateTotals"
            />
          </el-tab-pane>
          <el-tab-pane label="换出商品清单" name="outItems">
            <SaleExchangeOutItemForm
              ref="outItemFormRef"
              :items="formData.outItems"
              :disabled="disabled"
              @change="calculateTotals"
            />
          </el-tab-pane>
        </el-tabs>
      </ContentWrap>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="换出商品总数">
            <el-input disabled v-model="formData.totalOutCount" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="换入商品总数">
            <el-input disabled v-model="formData.totalInCount" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="差价金额">
            <el-input
              disabled
              v-model="formData.totalPrice"
              :formatter="erpPriceInputFormatter"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="其它费用" prop="otherPrice">
            <el-input-number
              v-model="formData.otherPrice"
              controls-position="right"
              :min="0"
              :precision="4"
              placeholder="请输入其它费用"
              class="!w-1/1"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="结算账户" prop="accountId">
            <el-select
              v-model="formData.accountId"
              clearable
              filterable
              placeholder="请选择结算账户"
              class="!w-1/1"
            >
              <el-option
                v-for="item in accountList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="实际结算金额">
            <el-input
              disabled
              :model-value="formData.totalPrice + formData.otherPrice"
              :formatter="erpPriceInputFormatter"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading" v-if="!disabled">
        确 定
      </el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <!-- 可选择的销售出库单列表 -->
  <SaleOutEnableList ref="saleOutEnableListRef" @success="handleSaleOutChange" />

  <!-- 销售出库单详情弹窗 -->
  <SaleOutForm ref="saleOutFormRef" />
</template>

<script setup lang="ts">
import { getSaleExchange, createSaleExchange, updateSaleExchange, SaleExchangeVO } from '@/api/erp/sale/exchange'
import SaleExchangeOutItemForm from './components/SaleExchangeOutItemForm.vue'
import SaleExchangeInItemForm from './components/SaleExchangeInItemForm.vue'
import { CustomerApi, CustomerVO } from '@/api/erp/sale/customer'
import { AccountApi, AccountVO } from '@/api/erp/finance/account'
import { getSimpleUserList, UserVO } from '@/api/system/user'
import { StockApi } from '@/api/erp/stock/stock'
import { erpPriceInputFormatter, erpPriceMultiply } from '@/utils'
import SaleOutEnableList from './components/SaleOutEnableList.vue'
import SaleOutForm from '../out/SaleOutForm.vue'

defineOptions({ name: 'SaleExchangeForm' })

const { t } = useI18n()
const message = useMessage()

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const formData = ref({
  id: undefined,
  no: undefined,
  exchangeTime: undefined,
  outId: undefined,
  outNo: undefined,
  customerId: undefined,
  customerName: undefined,
  saleUserId: undefined,
  accountId: undefined,
  totalOutCount: 0,
  totalInCount: 0,
  totalPrice: 0,
  otherPrice: 0,
  remark: undefined,
  fileUrl: undefined,
  status: 10,
  outItems: [],
  inItems: []
})
const formRules = reactive({
  exchangeTime: [{ required: true, message: '换货时间不能为空', trigger: 'blur' }],
  outId: [{ required: true, message: '关联出库单不能为空', trigger: 'blur' }],
  saleUserId: [{ required: true, message: '销售人员不能为空', trigger: 'blur' }]
})
const formRef = ref()
const disabled = computed(() => formType.value === 'detail')

const subTabsName = ref('outItems')
const outItemFormRef = ref()
const inItemFormRef = ref()

const customerList = ref<CustomerVO[]>([])
const userList = ref<UserVO[]>([])
const accountList = ref<AccountVO[]>([])

const saleOutEnableListRef = ref()
const saleOutFormRef = ref()

const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  if (id) {
    formLoading.value = true
    try {
      formData.value = await getSaleExchange(id)
      // 加载每个明细项的库存数量
      await loadItemsStockCount(formData.value.outItems)
      await loadItemsStockCount(formData.value.inItems)
    } finally {
      formLoading.value = false
    }
  }
}

const loadItemsStockCount = async (items: any[]) => {
  if (!items || items.length === 0) return
  for (const item of items) {
    if (item.productId && item.warehouseId) {
      try {
        const stock = await StockApi.getStock2(item.productId, item.warehouseId)
        item.stockCount = stock?.count || 0
      } catch {
        item.stockCount = 0
      }
    }
  }
}

const resetForm = () => {
  formData.value = {
    id: undefined,
    no: undefined,
    exchangeTime: new Date().getTime(),
    outId: undefined,
    outNo: undefined,
    customerId: undefined,
    customerName: undefined,
    saleUserId: undefined,
    accountId: undefined,
    totalOutCount: 0,
    totalInCount: 0,
    totalPrice: 0,
    otherPrice: 0,
    remark: undefined,
    fileUrl: undefined,
    status: 10,
    outItems: [],
    inItems: []
  }
  subTabsName.value = 'outItems'
}

const submitForm = async () => {
  await formRef.value.validate()
  await outItemFormRef.value?.validate()
  await inItemFormRef.value?.validate()

  formLoading.value = true
  try {
    const data = formData.value as unknown as SaleExchangeVO
    data.outItems = outItemFormRef.value?.getData() || []
    data.inItems = inItemFormRef.value?.getData() || []

    if (formType.value === 'create') {
      await createSaleExchange(data)
      message.success(t('common.createSuccess'))
    } else {
      await updateSaleExchange(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const openSaleOutEnableList = () => {
  saleOutEnableListRef.value.open()
}

const handleSaleOutChange = (out: any) => {
  formData.value.outId = out.id
  formData.value.outNo = out.no
  formData.value.customerId = out.customerId
  formData.value.customerName = out.customerName
  formData.value.saleUserId = out.saleUserId

  // 自动填充换入商品清单（原出库单的商品作为换入商品）
  formData.value.inItems = out.items?.map((item: any) => ({
    productId: item.productId,
    productName: item.productName,
    productBarCode: item.productBarCode,
    productUnitId: item.productUnitId,
    productUnitName: item.productUnitName,
    warehouseId: item.warehouseId,
    warehouseName: item.warehouseName,
    count: item.count,
    productPrice: item.productPrice || 0,
    totalPrice: item.totalProductPrice || (item.count * (item.productPrice || 0)),
    stockCount: item.stockCount || 0
  })) || []

  // 清空换出商品清单，让用户手动录入
  formData.value.outItems = []

  calculateTotals()
}

const calculateTotals = () => {
  const outItems = outItemFormRef.value?.getData() || formData.value.outItems || []
  const inItems = inItemFormRef.value?.getData() || formData.value.inItems || []

  formData.value.totalOutCount = outItems.reduce((sum: number, item: any) => sum + (item.count || 0), 0)
  formData.value.totalInCount = inItems.reduce((sum: number, item: any) => sum + (item.count || 0), 0)

  const outTotalPrice = outItems.reduce((sum: number, item: any) => sum + (item.totalPrice || 0), 0)
  const inTotalPrice = inItems.reduce((sum: number, item: any) => sum + (item.totalPrice || 0), 0)

  formData.value.totalPrice = inTotalPrice - outTotalPrice
}

const openSaleOutDetail = () => {
  saleOutFormRef.value.open('detail', formData.value.outId)
}

const emit = defineEmits(['success'])

if (onMounted) {
  onMounted(async () => {
    customerList.value = await CustomerApi.getCustomerSimpleList()
    userList.value = await getSimpleUserList()
    accountList.value = await AccountApi.getAccountSimpleList()
  })
}

defineExpose({ open })
</script>

<style scoped>
.order-link {
  color: var(--el-color-primary);
  cursor: pointer;
}
</style>
