<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
    :disabled="disabled"
  >
    <el-table :data="formData" class="-mt-10px">
      <el-table-column label="序号" type="index" align="center" width="60" />
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="产品类型" align="center" prop="category" width="160">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CRM_PRODUCT_CATEGORY" :value="scope.row.category" />
        </template>
      </el-table-column>

      <el-table-column label="产品明细类型" align="center" prop="detailType" width="160">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CRM_PRODUCT_DETAIL_TYPE" :value="scope.row.detailType" />
        </template>
      </el-table-column>

      <el-table-column label="单位" align="center" prop="productUnit">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CRM_PRODUCT_UNIT" :value="scope.row.productUnit" />
        </template>
      </el-table-column>
      <el-table-column label="产品票据" fixed="right" min-width="140">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.productInvoice`" :rules="formRules.productInvoice" class="mb-0px!">
            <el-select v-model="row.productInvoice" placeholder="请选择状态" clearable class="!w-240px">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.CRM_PRODUCT_INVOICE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="产品开具项目" fixed="right" min-width="140">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.productInvoiceItems`" class="mb-0px!">
            <el-select v-model="row.productInvoiceItems" placeholder="请选择状态" clearable class="!w-240px">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.CRM_PRODUCT_INVOICE_ITEMS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="服务费票据" prop="serviceFeeInvoice" fixed="right" min-width="140">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.serviceFeeInvoice`" class="mb-0px!">
            <el-select v-model="row.serviceFeeInvoice" placeholder="请选择状态" clearable class="!w-240px">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.CRM_SERVICE_FEE_INVOICE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="服务开具项目" prop="serviceFeeInvoiceItems" fixed="right" min-width="140">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.serviceFeeInvoiceItems`" class="mb-0px!">
            <el-select v-model="row.serviceFeeInvoiceItems" placeholder="请选择状态" clearable class="!w-240px">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.CRM_SERVICE_FEE_INVOICE_ITEMS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="60">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" link>—</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
  <el-row justify="center" class="mt-3" v-if="!disabled">
    <el-button @click="handleAdd" type="primary" round>+ 添加产品</el-button>
  </el-row>

  <!-- 表单弹窗：添加/修改 -->
  <ProductForm ref="productRef" @success="getList" />
</template>
<script setup lang="ts">
import * as ProductApi from '@/api/crm/product'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { erpPriceInputFormatter, erpPriceMultiply } from '@/utils'
import ProductForm from '@/components/product/index.vue'

const props = defineProps<{
  products: undefined
  disabled: false
}>()
const formLoading = ref(false) // 表单的加载中
const formData = ref([])
const formRules = reactive({
  productInvoice: [{ required: true, message: '产品票据不能为空', trigger: 'change' }],
  getIntDictOptions: [{ required: true, message: '产品开具项目不能为空', trigger: 'change' }],
  serviceFeeInvoice: [{ required: true, message: '服务费票据不能为空', trigger: 'change' }],
  serviceFeeInvoiceItems: [{ required: true, message: '服务开具项目不能为空', trigger: 'change' }]
})
const formRef = ref([]) // 表单 Ref
const productList = ref<ProductApi.ProductVO[]>([]) // 产品列表

/** 初始化设置产品项 */
watch(
  () => props.products,
  async (val) => {
    formData.value = val
  },
  { immediate: true }
)

const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const getList = (val: []) => {
  for(let i = formData.value.length - 1; i >= 0; i--) {
    let obj = formData.value[i]
    if(!val.some(v => v.id === obj.productId)) formData.value.splice(i, 1)
  }
  val.forEach(item => {
    if(!formData.value.some(v => v.productId === item.id)) {
      formData.value.push({
        "productId": item.id,
        "category": item.category,
        "productName": item.name,
        "detailType": item.detailType,
        "productUnit": item.unit,
        "onlinePrice": '',
        "offlinePrice": '',
        "count": ''
      })
    }
  })
  emit('success', formData.value)

}

// /** 新增按钮操作 */
// const handleAdd = () => {
//   const row = {
//     id: undefined,
//     productId: undefined,
//     productName: undefined,
//     productUnit: undefined, // 产品单位
//     productNo: undefined, // 产品条码
//     productPrice: undefined, // 产品价格
//     onlinePrice: undefined, // 产品价格
//     offlinePrice: undefined, // 产品价格
//     totalPrice: undefined,
//     businessPrice: undefined,
//     count: 1
//   }
//   formData.value.push(row)
// }
const productRef = ref() // 表单 Ref
const handleAdd = () => {
  productRef.value.open(formData.value)
}

/** 删除按钮操作 */
const handleDelete = (index: number) => {
  formData.value.splice(index, 1)
}

/** 处理产品变更 */
const onChangeProduct = (productId, row) => {
  const product = productList.value.find((item) => item.id === productId)
  if (product) {
    row.productId = product.id
    row.productName = product.name
    row.productCategoryId = 1
    row.productUnit = product.unit
    row.onlinePrice = product.onlinePrice
    row.offlinePrice = product.offlinePrice
    row.totalPrice = product.totalPrice
    row.productNo = product.no
    row.productPrice = product.price
    row.businessPrice = product.price
  }
}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}
defineExpose({ validate })

/** 初始化 */
onMounted(async () => {
  productList.value = await ProductApi.getProductSimpleList()
})
</script>
