<template>
  <div class="edit-popup">
    <popup
        ref="popupRef"
        :title="popupTitle"
        :async="true"
        width="550px"
        @confirm="handleSubmit"
        @close="handleClose"
    >
      <el-form ref="formRef" :model="formData" label-width="120px" :rules="formRules">
        <el-form-item label="权益名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入权益名称" :maxlength="10" clearable/>
        </el-form-item>
        <el-form-item label="权益图标" prop="icon">
          <material-picker v-model="formData.icon" :limit="1" />
        </el-form-item>
        <el-form-item label="权益价值" prop="value">
            <el-input v-model="formData.value" type="number" placeholder="请输入权益价值" clearable />
        </el-form-item>
        <el-form-item label="使用方式" prop="useMethod">
          <el-select v-model="formData.useMethod" placeholder="请选择权益使用方式">
            <el-option label="仅展示" :value="0"/>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea" clearable />
        </el-form-item>
      </el-form>
    </popup>
  </div>
</template>
<script lang="ts" setup>
import type {FormInstance} from 'element-plus'
import Popup from '@/components/popup/index.vue'
import feedback from '@/utils/feedback'
import {addPrinter, editPrinter, getPrinterDetail} from '@/api/shop'
import {saveBenefits} from "@/api/membership";

const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const popupTitle = computed(() => {
  return mode.value == 'edit' ? '编辑' : '新增'
})
const formData = reactive({
  id: '',
  name: '',
  icon: '',
  value: '',
  useMethod: 0,
  remark: ''
})

const formRules = {
  name: [
    {
      required: true,
      message: '请输入名称',
      trigger: ['blur']
    }
  ],
  icon: [
    {
      required: true,
      message: '请上传图标',
      trigger: ['blur']
    }
  ],
  useMethod: [
    {
      required: true,
      message: '请选择使用方式',
      trigger: ['blur']
    }
  ]
}

const handleSubmit = async () => {
  await formRef.value?.validate()
  await saveBenefits(formData)
  feedback.msgSuccess('操作成功')
  popupRef.value?.close()
  emit('success')
}

const open = (type = 'add') => {
  mode.value = type
  popupRef.value?.open()
}

const setFormData = (data: Record<any, any>) => {
  for (const key in formData) {
    if (data[key] != null && data[key] != undefined) {
      //@ts-ignore
      formData[key] = data[key]
    }
  }
}

const getDetail = async (row: Record<string, any>) => {
  // const data = await getPrinterDetail({
  //   id: row.id
  // })
  setFormData(row)
}

const handleClose = () => {
  emit('close')
}

defineExpose({
  open,
  setFormData,
  getDetail
})
</script>
