<template>
  <!-- 移动端布局 -->
  <el-drawer v-if="isMobile" v-model="dialogVisible" :title="dialogTitle" direction="rtl" size="100%" :close-on-press-escape="true" :destroy-on-close="true" :append-to-body="true" class="mobile-form-drawer">
    <div class="mobile-form" v-loading="formLoading">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-position="top" :disabled="disabled">
        <div class="mobile-form__section">
          <div class="mobile-form__section-title">基本信息</div>
          <el-form-item label="比价单号" prop="no"><el-input disabled v-model="formData.no" placeholder="保存时自动生成" /></el-form-item>
          <el-form-item label="询价时间" prop="inquiryTime"><el-date-picker v-model="formData.inquiryTime" type="date" value-format="x" placeholder="选择询价时间" style="width: 100%" /></el-form-item>
          <el-form-item label="截止日期" prop="deadline"><el-date-picker v-model="formData.deadline" type="date" value-format="x" placeholder="选择截止日期" style="width: 100%" /></el-form-item>
          <el-form-item label="产品" prop="productId"><el-select v-model="formData.productId" clearable filterable placeholder="请选择产品" style="width: 100%" @change="onChangeProduct"><el-option v-for="item in productList" :key="item.id" :label="item.name" :value="item.id" /></el-select></el-form-item>
          <div class="mobile-form__input-group">
            <el-form-item label="需求数量" prop="requireCount"><el-input-number v-model="formData.requireCount" controls-position="right" :min="0.0001" :precision="4" placeholder="需求数量" style="width: 100%" /></el-form-item>
            <el-form-item label="预算金额" prop="budgetPrice"><el-input-number v-model="formData.budgetPrice" controls-position="right" :min="0" :precision="2" placeholder="预算金额" style="width: 100%" /></el-form-item>
          </div>
          <el-form-item label="备注" prop="remark"><el-input type="textarea" v-model="formData.remark" :rows="2" placeholder="请输入备注" /></el-form-item>
        </div>
        <div class="mobile-form__section">
          <div class="mobile-form__section-title">供应商报价</div>
          <InquiryQuoteForm ref="quoteFormRef" :quotes="formData.quotes" :disabled="disabled" :require-count="formData.requireCount" />
        </div>
        <div class="mobile-form__section" v-if="formData.quotes && formData.quotes.length > 0">
          <div class="mobile-form__section-title">比价汇总</div>
          <div class="mobile-form__info-row"><span class="mobile-form__info-label">报价数量</span><span class="mobile-form__info-value">{{ formData.quotes.length }}</span></div>
          <div class="mobile-form__info-row"><span class="mobile-form__info-label">最低报价</span><span class="mobile-form__info-value" style="color: #67c23a">{{ erpPriceInputFormatter(minQuotePrice) }}</span></div>
          <div class="mobile-form__info-row"><span class="mobile-form__info-label">最高报价</span><span class="mobile-form__info-value" style="color: #e6a23c">{{ erpPriceInputFormatter(maxQuotePrice) }}</span></div>
        </div>
      </el-form>
      <div class="mobile-form__footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button @click="submitForm" type="primary" :disabled="formLoading" v-if="!disabled">确 定</el-button>
      </div>
    </div>
  </el-drawer>

  <!-- PC端布局 -->
  <Dialog v-else :title="dialogTitle" v-model="dialogVisible" width="1200">
    <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="inquiryTime"><el-date-picker v-model="formData.inquiryTime" type="date" value-format="x" placeholder="选择询价时间" class="!w-1/1" /></el-form-item></el-col>
        <el-col :span="8"><el-form-item label="截止日期" prop="deadline"><el-date-picker v-model="formData.deadline" type="date" value-format="x" placeholder="选择截止日期" class="!w-1/1" /></el-form-item></el-col>
        <el-col :span="8"><el-form-item label="产品" prop="productId"><el-select v-model="formData.productId" clearable filterable placeholder="请选择产品" class="!w-1/1" @change="onChangeProduct"><el-option v-for="item in productList" :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="requireCount"><el-input-number v-model="formData.requireCount" controls-position="right" :min="0.0001" :precision="4" placeholder="请输入需求数量" class="!w-1/1" /></el-form-item></el-col>
        <el-col :span="8"><el-form-item label="预算金额" prop="budgetPrice"><el-input-number v-model="formData.budgetPrice" controls-position="right" :min="0" :precision="2" placeholder="请输入预算金额" class="!w-1/1" /></el-form-item></el-col>
        <el-col :span="24"><el-form-item label="备注" prop="remark"><el-input type="textarea" v-model="formData.remark" :rows="2" placeholder="请输入备注" /></el-form-item></el-col>
      </el-row>
      <ContentWrap>
        <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px">
          <el-tab-pane label="供应商报价" name="quote"><InquiryQuoteForm ref="quoteFormRef" :quotes="formData.quotes" :disabled="disabled" :require-count="formData.requireCount" /></el-tab-pane>
        </el-tabs>
      </ContentWrap>
      <el-row :gutter="20" v-if="formData.quotes && formData.quotes.length > 0">
        <el-col :span="8"><el-form-item label="报价数量"><el-input disabled :value="formData.quotes.length" /></el-form-item></el-col>
        <el-col :span="8"><el-form-item label="最低报价"><el-input disabled :value="minQuotePrice" :formatter="erpPriceInputFormatter" /></el-form-item></el-col>
        <el-col :span="8"><el-form-item label="最高报价"><el-input disabled :value="maxQuotePrice" :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>
</template>
<script setup lang="ts">
import { nextTick, computed } from 'vue'
import { PurchaseInquiryApi, PurchaseInquiryVO } from '@/api/erp/purchase/inquiry'
import InquiryQuoteForm from './components/InquiryQuoteForm.vue'
import { ProductApi, ProductVO } from '@/api/erp/product/product'
import { erpPriceInputFormatter } from '@/utils'
import { useWindowSize } from '@vueuse/core'

/** ERP 采购比价表单 */
defineOptions({ name: 'InquiryForm' })

const { width } = useWindowSize()
const isMobile = computed(() => width.value < 768)

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

// 类型声明
interface InquiryFormModel {
  id?: number
  productId?: number
  requireCount: number
  budgetPrice: number
  inquiryTime?: number
  deadline?: number
  remark?: string
  quotes: PurchaseInquiryQuoteVO[]
  no?: string
}

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中
const formType = ref('') // 表单的类型：create - 新增；update - 修改；detail - 详情
const formData = ref<InquiryFormModel>({
  id: undefined,
  productId: undefined,
  requireCount: 1,
  budgetPrice: 0,
  inquiryTime: Date.now(),
  deadline: undefined,
  remark: undefined,
  quotes: [],
  no: undefined
})
const formRules = reactive({
  productId: [{ required: true, message: '产品不能为空', trigger: 'blur' }],
  requireCount: [{ required: true, message: '需求数量不能为空', trigger: 'blur' }],
  inquiryTime: [{ required: true, message: '询价时间不能为空', trigger: 'blur' }]
})
const disabled = computed(() => formType.value === 'detail')
const formRef = ref() // 表单 Ref
const productList = ref<ProductVO[]>([]) // 产品列表
const subTabsName = ref('quote') // PC端子表标签
const quoteFormRef = ref()

/** 计算最低报价 */
const minQuotePrice = computed(() => {
  if (!formData.value.quotes || formData.value.quotes.length === 0) {
    return 0
  }
  const prices = formData.value.quotes
    .filter((q) => q.unitPrice != null && q.unitPrice > 0)
    .map((q) => q.unitPrice)
  return prices.length > 0 ? Math.min(...prices) : 0
})

/** 计算最高报价 */
const maxQuotePrice = computed(() => {
  if (!formData.value.quotes || formData.value.quotes.length === 0) {
    return 0
  }
  const prices = formData.value.quotes
    .filter((q) => q.unitPrice != null && q.unitPrice > 0)
    .map((q) => q.unitPrice)
  return prices.length > 0 ? Math.max(...prices) : 0
})

/** 处理产品变更 */
const onChangeProduct = (productId: number) => {
  const product = productList.value.find((item) => item.id === productId)
  if (product) {
    // 可以根据产品设置默认值
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  await nextTick()
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = (await PurchaseInquiryApi.getPurchaseInquiry(id)) as unknown as InquiryFormModel
    } finally {
      formLoading.value = false
    }
  }
  // 加载产品列表
  productList.value = await ProductApi.getProductSimpleList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  await quoteFormRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as PurchaseInquiryVO
    if (formType.value === 'create') {
      await PurchaseInquiryApi.createPurchaseInquiry(data)
      message.success(t('common.createSuccess'))
    } else {
      await PurchaseInquiryApi.updatePurchaseInquiry(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    productId: undefined,
    requireCount: 1,
    budgetPrice: 0,
    inquiryTime: Date.now(),
    deadline: undefined,
    remark: undefined,
    quotes: []
  }
  formRef.value?.resetFields()
}
</script>

<style lang="scss" scoped>
.mobile-form {
  padding: 12px;
}
.mobile-form__section {
  background: #fff;
  border-radius: 10px;
  padding: 14px;
  margin-bottom: 12px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
}
.mobile-form__section-title {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}
.mobile-form__input-group {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
}
.mobile-form__info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 0;
  font-size: 14px;
}
.mobile-form__info-label {
  color: #909399;
}
.mobile-form__info-value {
  font-weight: 600;
  color: #303133;
}
.mobile-form__footer {
  position: sticky;
  bottom: 0;
  background: #fff;
  padding: 12px 16px;
  padding-bottom: calc(12px + constant(safe-area-inset-bottom));
  padding-bottom: calc(12px + env(safe-area-inset-bottom));
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  z-index: 10;
  margin: 0 -12px -12px;

  .el-button {
    flex: 1;
    height: 40px;
    font-size: 15px;
  }
}
</style>
