<template>
  <el-dialog v-model="visible" title="选择套餐" width="700px" append-to-body @close="handleClose">
    <div class="selector-toolbar">
      <el-button :icon="Refresh" @click="loadList" :loading="loading">刷新</el-button>
      <el-button type="primary" :icon="Plus" @click="showCreate = true">新建套餐</el-button>
      <span style="color:#909399;font-size:13px" v-if="goodId">商品 ID: {{ goodId }}</span>
    </div>
    <el-table :data="list" v-loading="loading" highlight-current-row @current-change="row => selected = row" :height="300" stripe size="small">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="套餐名称" min-width="160" show-overflow-tooltip />
      <el-table-column prop="note" label="说明" min-width="160" show-overflow-tooltip>
        <template #default="{ row }">{{ row.note || '-' }}</template>
      </el-table-column>
      <el-table-column label="状态" width="80">
        <template #default="{ row }">
          <el-tag :type="row.disable ? 'danger' : 'success'" size="small">{{ row.disable ? '禁用' : '启用' }}</el-tag>
        </template>
      </el-table-column>
    </el-table>
    <el-empty v-if="!list.length && !loading" :image-size="60" description="暂无套餐" />
    <div class="selector-footer-bar">
      <span v-if="selected" style="color:#606266;font-size:13px">已选：{{ selected.name }} (ID: {{ selected.id }})</span>
      <el-pagination v-model:current-page="page" v-model:page-size="pageSize" :page-sizes="[10,20]" :total="total"
        layout="total,sizes,prev,pager,next" small background
        @size-change="s => { pageSize = s; page = 1; loadList() }" @current-change="p => { page = p; loadList() }" />
    </div>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :disabled="!selected" @click="handleConfirm">确定选择</el-button>
    </template>
  </el-dialog>

  <!-- 新建套餐弹窗 -->
  <el-dialog v-model="showCreate" title="新建套餐" width="680px" append-to-body destroy-on-close class="scrollable-dialog">
    <el-form :model="createForm" label-width="90px">
      <el-form-item label="套餐名称" required><el-input v-model="createForm.name" placeholder="请输入套餐名称" /></el-form-item>
      <el-form-item label="说明"><el-input v-model="createForm.note" type="textarea" :rows="2" placeholder="请输入套餐说明" /></el-form-item>
      <el-form-item label="参数配置">
        <div style="width:100%">
          <div v-if="!goodId" style="color:#c0c4cc;font-size:13px">请先选择商品</div>
          <div v-else-if="createSpecLoading" style="color:#909399;font-size:13px">加载参数中...</div>
          <div v-else-if="createSpecList.length === 0" style="color:#909399;font-size:13px">该商品暂无参数</div>
          <div v-else>
            <div v-for="spec in createSpecList" :key="spec.id" style="margin-bottom:14px;padding-bottom:14px;border-bottom:1px solid #f5f5f5">
              <div style="font-size:13px;font-weight:500;color:#303133;margin-bottom:6px">
                {{ spec.name }}
                <el-tag v-if="spec.must" size="small" type="danger" style="margin-left:4px">必填</el-tag>
              </div>
              <template v-if="spec.type === 'select' && spec.attrs && spec.attrs.length > 0">
                <el-radio-group v-model="createSpecValues[spec.id]" size="small" @change="buildCreateArgsJson">
                  <el-radio-button v-for="attr in spec.attrs" :key="attr.id" :value="attr.id">{{ attr.name }}</el-radio-button>
                </el-radio-group>
              </template>
              <template v-else-if="spec.type === 'number'">
                <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap">
                  <el-input-number
                    v-model="createDisplayValues[spec.id]"
                    :min="hasUnit(spec) ? fromBaseUnit(spec.min ?? 0, createDisplayUnits[spec.id], getArgKey(spec)) : (spec.min ?? 0)"
                    :max="hasUnit(spec) ? fromBaseUnit(spec.max ?? 0, createDisplayUnits[spec.id], getArgKey(spec)) : (spec.max ?? 0)"
                    :step="hasUnit(spec) ? (fromBaseUnit(spec.step ?? 1, createDisplayUnits[spec.id], getArgKey(spec)) || 1) : (spec.step ?? 1)"
                    :step-strictly="true"
                    size="small"
                    @change="onCreateNumberChange(spec)"
                    style="width:180px"
                  />
                  <el-select v-if="hasUnit(spec)" :model-value="createDisplayUnits[spec.id]" size="small" style="width:90px" @change="(newUnit) => onCreateUnitChange(spec, newUnit)">
                    <el-option v-for="u in getParamUnits(spec)" :key="u" :label="u" :value="u" />
                  </el-select>
                  <span style="font-size:12px;color:#909399">范围: {{ spec.min ?? 0 }} ~ {{ spec.max ?? 0 }}
                    <template v-if="hasUnit(spec)"> {{ getBaseUnit(getArgKey(spec)) }}</template>，步长: {{ spec.step ?? 1 }}</span>
                </div>
              </template>
              <template v-else>
                <el-input v-model="createSpecValues[spec.id]" placeholder="请输入值" size="small" style="width:200px" @input="buildCreateArgsJson" />
              </template>
            </div>
            <div v-if="createForm.args" style="margin-top:8px">
              <div style="font-size:12px;color:#909399;margin-bottom:4px">参数 JSON：</div>
              <el-input v-model="createForm.args" type="textarea" :rows="3" readonly style="font-family:monospace;font-size:12px" />
            </div>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="排序"><el-input-number v-model="createForm.index" :min="0" controls-position="right" style="width:120px" /></el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="showCreate = false">取消</el-button>
      <el-button type="primary" :loading="createLoading" @click="submitCreate">创建</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { Refresh, Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getProductPlanList, createProductPlan, getProductParameterList } from '@/api/admin/product'
import { hasUnit, getArgKey, getBaseUnit, getParamUnits, getParamDefaultUnit, toBaseUnit, fromBaseUnit } from '@/utils/dynamicUnit'

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  goodId: { type: [Number, String], default: 0 }
})
const emit = defineEmits(['update:modelValue', 'confirm'])

const visible = ref(false)
const loading = ref(false)
const list = ref([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)
const selected = ref(null)
const showCreate = ref(false)
const createLoading = ref(false)
const createForm = reactive({ name: '', note: '', index: 0, args: '' })
const createSpecList = ref([])
const createSpecLoading = ref(false)
const createSpecValues = reactive({})
const createDisplayValues = reactive({})
const createDisplayUnits = reactive({})

watch(showCreate, (v) => {
  if (v && props.goodId) loadCreateSpec()
})

const loadCreateSpec = async () => {
  createSpecLoading.value = true
  try {
    const res = await getProductParameterList({ good_id: props.goodId })
    if (res?.data?.code === 200) {
      createSpecList.value = res.data.data || []
      for (const spec of createSpecList.value) {
        if (spec.type === 'number') {
          if (createSpecValues[spec.id] === undefined) createSpecValues[spec.id] = spec.min ?? 0
          if (hasUnit(spec)) {
            createDisplayUnits[spec.id] = getParamDefaultUnit(spec)
            createDisplayValues[spec.id] = fromBaseUnit(spec.min ?? 0, createDisplayUnits[spec.id], getArgKey(spec))
          } else {
            createDisplayValues[spec.id] = spec.min ?? 0
          }
        }
      }
    }
  } catch { createSpecList.value = [] } finally { createSpecLoading.value = false }
}

const onCreateNumberChange = (spec) => {
  if (hasUnit(spec)) {
    const argKey = getArgKey(spec)
    const unit = createDisplayUnits[spec.id]
    createSpecValues[spec.id] = Math.round(toBaseUnit(createDisplayValues[spec.id] || 0, unit, argKey))
  } else {
    createSpecValues[spec.id] = createDisplayValues[spec.id]
  }
  buildCreateArgsJson()
}

const onCreateUnitChange = (spec, newUnit) => {
  const argKey = getArgKey(spec)
  const oldUnit = createDisplayUnits[spec.id]
  const oldDisplay = createDisplayValues[spec.id] || 0
  const baseValue = oldUnit ? toBaseUnit(oldDisplay, oldUnit, argKey) : oldDisplay
  createDisplayUnits[spec.id] = newUnit
  createDisplayValues[spec.id] = fromBaseUnit(baseValue, newUnit, argKey)
  createSpecValues[spec.id] = Math.round(baseValue)
  buildCreateArgsJson()
}

const buildCreateArgsJson = () => {
  const result = []
  for (const spec of createSpecList.value) {
    const val = createSpecValues[spec.id]
    if (val === undefined || val === null || val === '') continue
    if (spec.type === 'select') {
      const attr = spec.attrs?.find(a => a.id === val)
      if (attr) result.push({ arg_id: spec.id, name: spec.name, attr_id: attr.id, value: attr.value, number: 0, key: getArgKey(spec) || undefined })
    } else if (spec.type === 'number') {
      result.push({ arg_id: spec.id, name: spec.name, attr_id: 0, value: '', number: val, key: getArgKey(spec) || undefined })
    } else {
      result.push({ arg_id: spec.id, name: spec.name, attr_id: 0, value: String(val), number: 0, key: getArgKey(spec) || undefined })
    }
  }
  createForm.args = result.length > 0 ? JSON.stringify(result) : ''
}

watch(() => props.modelValue, (v) => { visible.value = v; if (v) { selected.value = null; loadList() } })
watch(visible, (v) => emit('update:modelValue', v))

const loadList = async () => {
  loading.value = true
  try {
    const params = { page: page.value, count: pageSize.value }
    if (props.goodId) params.good_id = props.goodId
    const res = await getProductPlanList(params)
    if (res?.data?.code === 200 && res?.data?.data) {
      const d = res.data.data
      list.value = d.data || (Array.isArray(d) ? d : [])
      total.value = d.all_count ?? d.total ?? list.value.length
    }
  } catch { /* */ } finally { loading.value = false }
}

const submitCreate = async () => {
  if (!createForm.name) { ElMessage.warning('请输入套餐名称'); return }
  if (!props.goodId) { ElMessage.warning('请先选择商品'); return }
  createLoading.value = true
  try {
    const fd = new FormData()
    fd.append('good_id', props.goodId)
    fd.append('name', createForm.name)
    if (createForm.note) fd.append('note', createForm.note)
    fd.append('index', createForm.index)
    if (createForm.args) fd.append('args', createForm.args)
    const res = await createProductPlan(fd)
    if (res?.data?.code === 200) {
      ElMessage.success('创建成功')
      showCreate.value = false
      Object.assign(createForm, { name: '', note: '', index: 0, args: '' })
      for (const k in createSpecValues) delete createSpecValues[k]
      for (const k in createDisplayValues) delete createDisplayValues[k]
      for (const k in createDisplayUnits) delete createDisplayUnits[k]
      loadList()
    } else ElMessage.error(res?.data?.message || '创建失败')
  } catch { ElMessage.error('创建失败') } finally { createLoading.value = false }
}

const handleClose = () => { visible.value = false }
const handleConfirm = () => { if (selected.value) { emit('confirm', selected.value); handleClose() } }
</script>

<style scoped>
.selector-toolbar { display: flex; gap: 8px; margin-bottom: 12px; align-items: center; }
.selector-footer-bar { display: flex; justify-content: space-between; align-items: center; margin-top: 12px; }
</style>
