<template>
  <el-dialog
    title="设置显示页面"
    v-model="dialogVisible"
    width="560px"
    @open="onOpen"
  >
    <el-form :model="form" label-width="140px" label-position="left">
      <el-form-item label="权益首页/列表页">
        <el-radio-group v-model="form.showOnHome">
          <el-radio label="显示">显示</el-radio>
          <el-radio label="不显示">不显示</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="组装页">
        <el-radio-group v-model="form.showOnAssembly">
          <el-radio label="显示">显示</el-radio>
          <el-radio label="不显示">不显示</el-radio>
        </el-radio-group>
        <div
          v-if="form.showOnAssembly === '显示'"
          style="background: #f1f2f5;padding: 16px;margin-top: 10px;"
        >
          <el-select
            v-model="form.assemblyPages"
            multiple
            filterable
            placeholder="请选择组装页"
            style="width: 100%"
          >
            <el-option
              v-for="page in assemblyPageOptions"
              :key="page.id"
              :label="page.name"
              :value="page.name"
            />
          </el-select>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <span>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'ShowPagesDialog',
  props: {
    modelValue: { type: Boolean, default: false },
    row: { type: Object, default: null }
  },
  emits: ['update:modelValue', 'confirm'],
  data() {
    return {
      assemblyPageOptions: [],
      form: {
        showOnHome: '显示',
        showOnAssembly: '不显示',
        assemblyPages: []
      }
    }
  },
  computed: {
    dialogVisible: {
      get() { return this.modelValue },
      set(val) { this.$emit('update:modelValue', val) }
    }
  },
  methods: {
    async fetchAssemblyPages() {
      try {
        const res = await request.get('/api/assembly/list')
        this.assemblyPageOptions = res.data || []
      } catch {
        this.assemblyPageOptions = []
      }
    },
    onOpen() {
      this.fetchAssemblyPages()
      if (this.row) {
        this.form.showOnHome = this.row.showOnHome || '显示'
        this.form.showOnAssembly = this.row.showOnAssembly || '不显示'
        this.form.assemblyPages = Array.isArray(this.row.assemblyPages)
          ? [...this.row.assemblyPages]
          : []
      } else {
        this.form.showOnHome = '显示'
        this.form.showOnAssembly = '不显示'
        this.form.assemblyPages = []
      }
    },
    handleConfirm() {
      this.$emit('confirm', { ...this.form, assemblyPages: [...this.form.assemblyPages] })
      this.dialogVisible = false
    }
  }
}
</script>
