<template>
  <el-dialog
    v-model="dialogVisible"
    :title="`扩展设置 - ${goodsTitle}`"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div v-loading="loading">
      <!-- 盒子基本信息 -->
      <el-descriptions :column="2" border class="goods-info">
        <el-descriptions-item label="盒子ID">{{ goodsId }}</el-descriptions-item>
        <el-descriptions-item label="盒子名称">{{ goodsTitle }}</el-descriptions-item>
      </el-descriptions>

      <!-- 继承状态提示 -->
      <el-alert
        v-if="extendData?.isInherited"
        type="info"
        :closable="false"
        show-icon
        class="inherit-alert"
      >
        <template #title>
          当前使用盒子类型的默认支付配置，修改后将创建独立配置
        </template>
      </el-alert>

      <el-alert
        v-else
        type="success"
        :closable="false"
        show-icon
        class="inherit-alert"
      >
        <template #title>
          当前使用独立支付配置，可点击"删除扩展设置"恢复使用类型默认配置
        </template>
      </el-alert>

      <!-- 支付方式配置表单 -->
      <el-form
        ref="formRef"
        :model="formData"
        label-width="100px"
        class="extend-form"
      >
        <el-form-item label="支付方式">
          <el-checkbox-group v-model="payMethods">
            <el-checkbox label="wechat">微信支付</el-checkbox>
            <el-checkbox label="balance">余额支付</el-checkbox>
            <el-checkbox label="currency">积分支付</el-checkbox>
            <el-checkbox label="currency2">积分2支付</el-checkbox>
            <el-checkbox label="coupon">优惠券支付</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="支付类型">
          <el-radio-group v-model="formData.isDeduction">
            <el-radio :value="0">支付模式</el-radio>
            <el-radio :value="1">抵扣模式</el-radio>
          </el-radio-group>
          <div class="form-tip">
            <el-text type="info" size="small">
              支付模式：用户选择一种支付方式完成支付；抵扣模式：积分/优惠券可抵扣部分金额
            </el-text>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!extendData?.isInherited"
          type="danger"
          plain
          :loading="deleteLoading"
          @click="handleDelete"
        >
          删除扩展设置
        </el-button>
        <div class="footer-right">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
            保存
          </el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import {
  getGoodsExtend,
  updateGoodsExtend,
  deleteGoodsExtend,
  type GoodsExtendItem,
  type GoodsExtendUpdateRequest
} from '@/api/business/goods'

interface Props {
  modelValue: boolean
  goodsId: number
  goodsTitle: string
}

const props = defineProps<Props>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}>()

// 弹窗显示状态
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

// 加载状态
const loading = ref(false)
const submitLoading = ref(false)
const deleteLoading = ref(false)

// 表单引用
const formRef = ref<FormInstance>()

// 扩展设置数据
const extendData = ref<GoodsExtendItem | null>(null)

// 支付方式多选
const payMethods = ref<string[]>([])

// 表单数据
const formData = reactive<GoodsExtendUpdateRequest>({
  payWechat: 0,
  payBalance: 0,
  payCurrency: 0,
  payCurrency2: 0,
  payCoupon: 0,
  isDeduction: 0
})

// 监听支付方式变化，同步到表单数据
watch(payMethods, (methods) => {
  formData.payWechat = methods.includes('wechat') ? 1 : 0
  formData.payBalance = methods.includes('balance') ? 1 : 0
  formData.payCurrency = methods.includes('currency') ? 1 : 0
  formData.payCurrency2 = methods.includes('currency2') ? 1 : 0
  formData.payCoupon = methods.includes('coupon') ? 1 : 0
})

// 监听弹窗打开，加载数据
watch(() => props.modelValue, async (visible) => {
  if (visible && props.goodsId > 0) {
    await loadExtendData()
  }
})

// 加载扩展设置数据
const loadExtendData = async () => {
  loading.value = true
  try {
    const res = await getGoodsExtend(props.goodsId)
    if (res.code === 0 && res.data) {
      extendData.value = res.data
      // 初始化表单数据
      Object.assign(formData, {
        payWechat: res.data.payWechat,
        payBalance: res.data.payBalance,
        payCurrency: res.data.payCurrency,
        payCurrency2: res.data.payCurrency2,
        payCoupon: res.data.payCoupon,
        isDeduction: res.data.isDeduction
      })
      // 初始化支付方式多选
      const methods: string[] = []
      if (res.data.payWechat === 1) methods.push('wechat')
      if (res.data.payBalance === 1) methods.push('balance')
      if (res.data.payCurrency === 1) methods.push('currency')
      if (res.data.payCurrency2 === 1) methods.push('currency2')
      if (res.data.payCoupon === 1) methods.push('coupon')
      payMethods.value = methods
    }
  } catch (error) {
    console.error('加载扩展设置失败:', error)
    ElMessage.error('加载扩展设置失败')
  } finally {
    loading.value = false
  }
}

// 重置表单
const resetForm = () => {
  extendData.value = null
  payMethods.value = []
  Object.assign(formData, {
    payWechat: 0,
    payBalance: 0,
    payCurrency: 0,
    payCurrency2: 0,
    payCoupon: 0,
    isDeduction: 0
  })
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 保存扩展设置
const handleSubmit = async () => {
  submitLoading.value = true
  try {
    const res = await updateGoodsExtend(props.goodsId, formData)
    if (res.code === 0) {
      ElMessage.success('保存成功')
      emit('success')
      handleClose()
    } else {
      ElMessage.error(res.message || '保存失败')
    }
  } catch (error) {
    console.error('保存扩展设置失败:', error)
    ElMessage.error('保存失败')
  } finally {
    submitLoading.value = false
  }
}

// 删除扩展设置
const handleDelete = async () => {
  try {
    await ElMessageBox.confirm(
      '删除扩展设置后，该盒子将恢复使用盒子类型的默认支付配置，确定要删除吗？',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
  } catch {
    return
  }

  deleteLoading.value = true
  try {
    const res = await deleteGoodsExtend(props.goodsId)
    if (res.code === 0) {
      ElMessage.success('删除成功，已恢复使用类型默认配置')
      emit('success')
      handleClose()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    console.error('删除扩展设置失败:', error)
    ElMessage.error('删除失败')
  } finally {
    deleteLoading.value = false
  }
}
</script>

<style scoped>
.goods-info {
  margin-bottom: 16px;
}

.inherit-alert {
  margin-bottom: 16px;
}

.extend-form {
  margin-top: 16px;
}

.form-tip {
  margin-top: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.footer-right {
  display: flex;
  gap: 8px;
}
</style>
