<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.enabled">
          <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.showOnHome">
          <el-radio label="显示">显示</el-radio>
          <el-radio label="不显示">不显示</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="组装页" class="assembly-item">
        <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 === '显示'"
          class="assembly-select-box"
        >
          <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-item label="白名单客群">
        <el-select
          v-model="form.whitelistCrowds"
          multiple
          filterable
          collapse-tags
          placeholder="请选择客群（可多选）"
          style="width: 100%"
        >
          <el-option
            v-for="item in crowdOptions"
            :key="item.id"
            :label="`${item.name} (${item.id})`"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="权益名称" required>
        <el-input
          v-model="form.equityName"
          maxlength="40"
          placeholder="请输入权益名称"
          style="width: 100%"
        ></el-input>
      </el-form-item>
      <el-form-item label="权益图标" required>
        <el-upload
          action=""
          :auto-upload="false"
          :file-list="form.listIcon"
          :on-change="file => handleUpload(file, 'listIcon')"
          :on-preview="handlePreviewImage"
          :on-remove="() => form.listIcon = []"
          :class="{ 'upload-hide-trigger': form.listIcon.length >= 1 }"
          :limit="1"
          list-type="picture-card"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
        <div class="upload-size-tip">建议尺寸：80x80px</div>
      </el-form-item>
    </el-form>

    <el-dialog v-model="previewVisible" title="预览" width="400px" append-to-body>
      <img v-if="previewImageUrl" :src="previewImageUrl" style="width: 100%" />
    </el-dialog>

    <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'
import { ElMessage } from 'element-plus'
import crowdTaskStore from '@/store/crowdTaskStore'

export default {
  name: 'ShowPagesDialog',
  props: {
    modelValue: { type: Boolean, default: false },
    row: { type: Object, default: null }
  },
  emits: ['update:modelValue', 'confirm'],
  data() {
    return {
      assemblyPageOptions: [],
      previewVisible: false,
      previewImageUrl: '',
      form: {
        enabled: '不启用',
        showOnHome: '显示',
        showOnAssembly: '不显示',
        assemblyPages: [],
        whitelistCrowds: [],
        equityName: '',
        listIcon: []
      }
    }
  },
  computed: {
    dialogVisible: {
      get() { return this.modelValue },
      set(val) { this.$emit('update:modelValue', val) }
    },
    crowdOptions() {
      return crowdTaskStore.list
    }
  },
  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.enabled = this.row.enabled || '不启用'
        this.form.showOnHome = this.row.showOnHome || '显示'
        this.form.showOnAssembly = this.row.showOnAssembly || '不显示'
        this.form.assemblyPages = Array.isArray(this.row.assemblyPages)
          ? [...this.row.assemblyPages]
          : []
        this.form.whitelistCrowds = Array.isArray(this.row.whitelistCrowds)
          ? [...this.row.whitelistCrowds]
          : []
        this.form.equityName = this.row.equityName || ''
        this.form.listIcon = this.row.equityIcon
          ? [{ name: '权益图标', url: this.row.equityIcon }]
          : []
      } else {
        this.form.enabled = '不启用'
        this.form.showOnHome = '显示'
        this.form.showOnAssembly = '不显示'
        this.form.assemblyPages = []
        this.form.whitelistCrowds = []
        this.form.equityName = ''
        this.form.listIcon = []
      }
    },
    handleUpload(file, field) {
      if (!file || !file.raw) return
      const reader = new FileReader()
      reader.onload = (e) => {
        this.form[field] = [{ name: file.name, url: e.target.result, uid: file.uid }]
      }
      reader.readAsDataURL(file.raw)
    },
    handlePreviewImage(file) {
      this.previewImageUrl = file.url || ''
      this.previewVisible = !!this.previewImageUrl
    },
    handleConfirm() {
      if (!this.form.equityName) {
        ElMessage.warning('请填写权益名称')
        return
      }
      if (!this.form.listIcon.length) {
        ElMessage.warning('请上传权益图标')
        return
      }
      const equityIcon = this.form.listIcon.length ? this.form.listIcon[0].url : ''
      this.$emit('confirm', {
        ...this.form,
        assemblyPages: [...this.form.assemblyPages],
        whitelistCrowds: [...this.form.whitelistCrowds],
        equityIcon
      })
      this.dialogVisible = false
    }
  }
}
</script>

<style scoped>
.assembly-item >>> .el-form-item__content { flex-wrap: wrap; }
.assembly-select-box {
  width: 100%;
  box-sizing: border-box;
  background: #f1f2f5;
  padding: 16px;
  margin-top: 10px;
}
.upload-hide-trigger >>> .el-upload--picture-card { display: none; }
.upload-size-tip {
  width: 100%;
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
}
</style>
