<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" v-loading="loading">
      <el-divider content-position="left">基本信息</el-divider>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="抽奖标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入抽奖标题" :disabled="viewMode" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="抽奖类型" prop="raffleType">
            <el-select
              v-model="form.raffleType"
              placeholder="请选择抽奖类型"
              :disabled="viewMode"
              style="width: 100%;"
            >
              <el-option
                v-for="item in raffleTypeList"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所需银币" prop="rafflePoint">
            <el-input-number v-model="form.rafflePoint" :min="0" :disabled="viewMode" />
            <span class="ml-2">用户抽奖需要消耗的银币</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="转发奖励银币" prop="forwardPoint">
            <el-input-number v-model="form.forwardPoint" :min="0" :disabled="viewMode" />
            <span class="ml-2">用户转发获得的银币</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="抽奖封面图" prop="image">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :headers="uploadHeaders"
              :show-file-list="false"
              :on-success="handleImageSuccess"
              :before-upload="beforeImageUpload"
              :disabled="viewMode"
            >
              <img v-if="form.image" :src="getImageUrl(form.image)" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="抽奖简介" prop="brief">
            <el-input v-model="form.brief" type="textarea" :rows="3" placeholder="请输入抽奖简介" :disabled="viewMode" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="详细描述" prop="description">
        <el-input v-model="form.description" type="textarea" :rows="4" placeholder="请输入详细描述" :disabled="viewMode" />
      </el-form-item>
      
      <el-divider content-position="left">特殊奖品设置</el-divider>
      
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="特殊奖品类型" prop="extraType">
            <el-select v-model="form.extraType" placeholder="请选择特殊奖品类型" :disabled="viewMode">
              <el-option label="普通奖(L)" value="L"></el-option>
              <el-option label="特殊奖(S)" value="S"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="特殊奖品" prop="extraPrize">
            <el-input v-model="form.extraPrize" placeholder="请输入特殊奖品名称" :disabled="viewMode" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="特殊奖品图" prop="extraImage">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :headers="uploadHeaders"
              :show-file-list="false"
              :on-success="handleExtraImageSuccess"
              :before-upload="beforeImageUpload"
              :disabled="viewMode"
            >
              <img v-if="form.extraImage" :src="getImageUrl(form.extraImage)" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-divider content-position="left">奖品配置</el-divider>
      
      <el-form-item label="奖品列表">
        <div v-if="viewMode">
          <el-table :data="raffleItems" border style="width: 100%">
            <el-table-column prop="title" label="奖品标题" width="120"></el-table-column>
            <el-table-column prop="prize" label="奖品名称" width="120"></el-table-column>
            <el-table-column prop="point" label="银币价值" width="100"></el-table-column>
            <el-table-column prop="num" label="数量" width="80"></el-table-column>
            <el-table-column label="图片" width="100">
              <template slot-scope="scope">
                <img :src="getImageUrl(scope.row.image)" class="table-img" v-if="scope.row.image" />
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-else>
          <el-button type="primary" size="small" icon="el-icon-plus" @click="addPrizeItem">添加奖品</el-button>
          <el-table :data="raffleItems" border style="width: 100%; margin-top: 10px">
            <el-table-column prop="title" label="奖品标题" width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.title" placeholder="如：A, B, C" size="small" />
              </template>
            </el-table-column>
            <el-table-column prop="prize" label="奖品名称" width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.prize" placeholder="奖品名称" size="small" />
              </template>
            </el-table-column>
            <el-table-column prop="point" label="银币价值" width="120">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.point" :min="0" size="small" />
              </template>
            </el-table-column>
            <el-table-column prop="num" label="数量" width="120">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.num" :min="1" size="small" />
              </template>
            </el-table-column>
            <el-table-column label="图片" width="150">
              <template slot-scope="scope">
                <el-upload
                  class="inline-uploader"
                  :action="uploadUrl"
                  :headers="uploadHeaders"
                  :show-file-list="false"
                  :on-success="(res) => handlePrizeImageSuccess(res, scope.$index)"
                  :before-upload="beforeImageUpload"
                >
                  <el-button size="small" type="primary">上传图片</el-button>
                </el-upload>
                <img v-if="scope.row.image" :src="getImageUrl(scope.row.image)" class="table-img" style="margin-top: 5px" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template slot-scope="scope">
                <el-button type="text" icon="el-icon-delete" @click="removePrizeItem(scope.$index)" style="color: #f56c6c">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form-item>
      
      <el-form-item v-if="!viewMode">
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getRaffleDetail, getRaffleRecords, saveRaffle, getRaffleTypeList } from '@/api/raffle'
import { resolveImageUrl } from '@/utils/image'
import { getToken } from '@/utils/auth'

export default {
  name: 'RaffleDetail',
  data() {
    return {
      loading: false,
      viewMode: false,
      form: {
        id: 0,
        title: '',
        brief: '',
        raffleType: '',
        image: '',
        rafflePoint: 0,
        forwardPoint: 0,
        description: '',
        extraType: 'L',
        extraPrize: '',
        extraImage: '',
        status: 'A',
      },
      raffleItems: [],
      rules: {
        title: [{ required: true, message: '请输入抽奖标题', trigger: 'blur' }],
        brief: [{ required: true, message: '请输入抽奖简介', trigger: 'blur' }],
        raffleType: [{ required: true, message: '请输入抽奖类型', trigger: 'blur' }],
      },
      raffleTypeList: [],
      imagePath: '',
      uploadUrl: process.env.VUE_APP_BASE_API + '/backendApi/file/upload',
      uploadHeaders: {
        'Access-Token': getToken(),
      },
    }
  },
  created() {
    this.syncRouteState()
    this.loadRaffleTypes()
  },
  watch: {
    '$route.query': {
      handler() {
        this.syncRouteState()
      },
      deep: true,
    },
  },
  methods: {
    getImageUrl(path) {
      return resolveImageUrl(this.imagePath, path)
    },
    syncRouteState() {
      const id = this.$route.query.id
      const view = this.$route.query.view
      this.viewMode = !!view
      if (id && id !== '0') {
        this.getDetail(id)
      } else {
        this.resetFormState()
      }
    },
    resetFormState() {
      this.form = {
        id: 0,
        title: '',
        brief: '',
        raffleType: '',
        image: '',
        rafflePoint: 0,
        forwardPoint: 0,
        description: '',
        extraType: 'L',
        extraPrize: '',
        extraImage: '',
        status: 'A',
      }
      this.raffleItems = []
      this.ensureDefaultType()
    },
    loadRaffleTypes() {
      getRaffleTypeList({ page: 1, pageSize: 200, status: 'A' })
        .then((response) => {
          if (response.code === 200 && response.data) {
            const list = response.data.dataList && response.data.dataList.content ? response.data.dataList.content : []
            this.raffleTypeList = Array.isArray(list) ? list : []
          } else {
            this.raffleTypeList = []
          }
          this.ensureDefaultType()
        })
        .catch(() => {
          this.raffleTypeList = []
          this.ensureDefaultType()
        })
    },
    ensureDefaultType() {
      if (this.form && !this.form.raffleType && this.raffleTypeList.length) {
        this.form.raffleType = this.raffleTypeList[0].code
      }
    },
    getDetail(id) {
      this.loading = true
      getRaffleDetail(id).then((response) => {
        if (response.code === 200) {
          const data = response.data.dataList
          this.imagePath = response.data.imagePath || ''
          this.form = {
            id: data.id,
            title: data.title,
            brief: data.brief,
            raffleType: data.raffleType,
            image: data.image,
            rafflePoint: data.rafflePoint || 0,
            forwardPoint: data.forwardPoint || 0,
            description: data.description,
            extraType: data.extraType || 'L',
            extraPrize: data.extraPrize || '',
            extraImage: data.extraImage || '',
            status: data.status,
          }
          this.ensureDefaultType()
          getRaffleRecords({ raffleId: id }).then((res) => {
            if (res.code === 200) {
              this.imagePath = res.data.imagePath || this.imagePath
              const items = res.data.rafList || []
              const grouped = {}
              items.forEach(item => {
                if (!grouped[item.title]) {
                  grouped[item.title] = {
                    title: item.title,
                    prize: item.prize,
                    point: item.point,
                    image: item.image,
                    num: 0
                  }
                }
                if (item.win === 0) {
                  grouped[item.title].num++
                }
              })
              this.raffleItems = Object.values(grouped)
            }
          }).catch(() => {
            this.$message.error('获取抽奖奖品失败')
          })
        } else {
          this.$message.error(response.message || '获取抽奖详情失败')
        }
      }).catch(() => {
        this.$message.error('获取抽奖详情失败')
      }).finally(() => {
        this.loading = false
      })
    },
    addPrizeItem() {
      this.raffleItems.push({
        title: '',
        prize: '',
        point: 0,
        num: 1,
        image: '',
      })
    },
    removePrizeItem(index) {
      this.raffleItems.splice(index, 1)
    },
    handleImageSuccess(res) {
      if (res.code === 200) {
        this.form.image = res.data.path
      }
    },
    handleExtraImageSuccess(res) {
      if (res.code === 200) {
        this.form.extraImage = res.data.path
      }
    },
    handlePrizeImageSuccess(res, index) {
      if (res.code === 200) {
        this.raffleItems[index].image = res.data.path
      }
    },
    beforeImageUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG/GIF 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.raffleItems.length === 0) {
            this.$message.warning('请至少添加一个奖品')
            return
          }
          this.loading = true
          const data = {
            ...this.form,
            rafData: this.raffleItems,
          }
          saveRaffle(data).then((response) => {
            if (response.code === 200) {
              this.$message.success('保存成功')
              this.$router.push('/raffle/index')
            }
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        }
      })
    },
    cancel() {
      this.$router.push('/raffle/index')
    },
  },
}
</script>

<style scoped>
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: inline-block;
}
.avatar-uploader:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}
.table-img {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
}
.ml-2 {
  margin-left: 8px;
}
</style>
