<script setup lang="tsx">
import { ref, reactive, onMounted } from 'vue'
import {
  ElForm,
  ElFormItem,
  ElRadioGroup,
  ElRadio,
  ElInput,
  ElCascader,
  FormInstance,
  ElMessage,
  ElSelect,
  ElOption
} from 'element-plus'
import { getProductCategory, getProduct } from '@/api/goods'

const coupon = ref({
  type: 0,
  title: '',
  coupon_price: 0,
  use_min_price: 0,
  coupon_time: 0,
  sort: 0,
  status: 1,
  category_id: '',
  product_id: []
})

const rules = reactive({
  title: [{ required: true, message: '请输入优惠券名称', trigger: 'blur' }],
  coupon_price: [{ required: true, message: '请输入优惠券面值', trigger: 'blur' }],
  category_id: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
  product_id: [{ required: true, message: '请选择商品', trigger: 'change' }]
})
const cateIdsProps = {
  checkStrictly: false,
  // emitPath: false,
  multiple: false,
  lazy: true,
  lazyLoad: (node, resolve) => {
    getProductCategory({ page: 1, limit: 100, pid: node.value || 0 })
      .then((res) => {
        if (res) {
          const nodes = res.data.list.map((item) => {
            return {
              value: item.id,
              label: item.cate_name,
              leaf: item.children.length == 0
            }
          })
          resolve(nodes)
        }
      })
      .catch((e) => {
        console.log(e)
      })
  }
}
const formRef = ref<FormInstance>()
const emits = defineEmits(['addCoupon'])
// defineExpose({
//   submit
// })
const save = async (elRef) => {
  await elRef.validate((valid, fields) => {
    if (valid) {
      console.log('submit!', valid)
      emits('addCoupon', coupon.value)
    } else {
      for (const key in fields) {
        ElMessage.error(fields[key][0].message)
        return
      }
    }
  })
}

interface opt {
  label: string
  value: string
}
const goodOptions = ref<opt[]>([])
const loading = ref(false)
const remoteMethod = (query: string) => {
  if (query) {
    loading.value = true
    getProduct({
      page: 1,
      limit: 1000,
      store_name: query
    }).then((res) => {
      loading.value = false
      goodOptions.value = res.data.list.map((item) => {
        return {
          label: '( ' + item.id + ')' + item.store_name,
          value: item.id
        }
      })
    }).catch(() => {
      loading.value = false
    })
  } else {
    goodOptions.value = []
  }
}
</script>

<template>
  <ElForm label-width="100px" :rules="rules" ref="formRef" :model="coupon">
    <ElFormItem label="优惠券类型">
      <ElRadioGroup v-model="coupon.type" class="ml-4">
        <ElRadio :label="0" size="large">通用券</ElRadio>
        <ElRadio :label="1" size="large">品类券</ElRadio>
        <ElRadio :label="2" size="large">商品券</ElRadio>
      </ElRadioGroup>
    </ElFormItem>
    <ElFormItem label="商品分类" prop="category_id" v-if="coupon.type == 1">
      <ElCascader
        v-model="coupon.category_id"
        :show-all-levels="false"
        clearable
        class="w-full"
        :props="cateIdsProps"
        placeholder="请选择商品分类"
      />
    </ElFormItem>
    <ElFormItem label="优惠券名称" prop="title">
      <ElInput v-model="coupon.title" placeholder="请输入优惠券名称" />
    </ElFormItem>
    <ElFormItem label="商品" prop="product_id" v-if="coupon.type == 2">
      <ElSelect
        v-model="coupon.product_id"
        multiple
        filterable
        remote
        reserve-keyword
        :remote-method="remoteMethod"
        :loading="loading"
        placeholder="请选择商品"
      >
        <ElOption
          v-for="item in goodOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </ElSelect>
    </ElFormItem>
    <ElFormItem label="优惠券面值" prop="coupon_price">
      <ElInput type="number" v-model="coupon.coupon_price" placeholder="请输入优惠券面值" />
    </ElFormItem>
    <ElFormItem label="最低消费">
      <ElInput type="number" v-model="coupon.use_min_price" placeholder="请输入最低消费金额" />
    </ElFormItem>
    <!-- 有效期限 -->
    <ElFormItem label="有效期限">
      <ElInput type="number" v-model="coupon.coupon_time" placeholder="请输入有效期限" />
      <div class="text-xs text-gray-400 mt-5px">温馨提醒：0 即为永久有效</div>
    </ElFormItem>
    <!-- 排序 -->
    <ElFormItem label="排序">
      <ElInput type="number" v-model="coupon.sort" placeholder="请输入排序" />
    </ElFormItem>
    <ElFormItem label="状态">
      <ElRadioGroup v-model="coupon.status" class="ml-4">
        <ElRadio :label="0" size="large">关闭</ElRadio>
        <ElRadio :label="1" size="large">开启</ElRadio>
      </ElRadioGroup>
    </ElFormItem>
    <div
      class="text-right border-gray-200 py-10px mt-10px position-sticky bottom-0 left-0 right-0 bg-white"
    >
      <BaseButton type="primary" @click="save(formRef)"> 保存 </BaseButton>
      <BaseButton> 取消 </BaseButton>
    </div>
  </ElForm>
</template>
