<template>
  <div class="app-container" style="width: 800px;margin: 0 auto;">
    <el-form ref="bannerForm" :model="form" label-width="100px">
      <el-form-item label="主题:" prop="topic" :rules="rules.topic">
        <el-input v-model="form.topic" placeholder="请输入菜单名，5字以内" maxlength="5" style="width: 250px;" />
      </el-form-item>
      <el-form-item label="图标:" prop="image" :rules="rules.image" style="margin-bottom: 40px;">
        <div class="form-el-upload" style="width: 148px;height: 148px;">
          <el-upload
            class="avatar-uploader"
            :action="actionUrl"
            :headers="getToken"
            :show-file-list="false"
            :on-success="handleSuccess"
            :before-upload="beforeUpload"
          >
            <div v-loading="loadImgLoading" class="avatar" style="width: 148px;height: 148px;display: block;">
              <img v-if="form.image" :src="form.image" style="width: 148px;height: 148px;display: block;" @error="reloadImage" @load="loadSucess">
              <i v-else class="el-icon-plus avatar-uploader-icon" style="width: 148px;height: 148px;line-height: 148px;" />
            </div>
          </el-upload>
          <p class="uploader-tips">注：请尽量上传100*100(px)尺寸的图片。</p>
        </div>
      </el-form-item>
      <el-form-item label="排序:" prop="sort" :rules="rules.sort">
        <el-input v-model="form.sort" style="width: 200px" />
      </el-form-item>
      <el-form-item label="状态:" prop="enabledStatus" :rules="rules.enabledStatus">
        <el-select v-model="form.enabledStatus" placeholder="请选择">
          <el-option label="上线" :value="1" />
          <el-option label="下线" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="跳转:" prop="jumpType" :rules="rules.jumpType">
        <el-radio-group v-model="form.jumpType">
          <el-radio :label="1">单个商品详情</el-radio>
          <el-radio :label="2">活动列表</el-radio>
        </el-radio-group>
      </el-form-item>
      <template v-if="form.jumpType === 1">
        <el-form-item label="商品信息" prop="products" :rules="rules.products">
          <template v-if="form.products && form.products.length === 0">
            <el-button type="primary" autofocussize="mini" size="mini" icon="el-icon-plus" @click="handleDialogVisible">选择商品</el-button>
            <el-checkbox-group v-show="false" v-model="form.products" />
          </template>
          <template v-else>
            <el-table :data="form.products" border width="1000">
              <el-table-column property="mainImage" label="商品图片" align="center" width="80">
                <template slot-scope="{ row }">
                  <el-popover
                    placement="top-start"
                    title=""
                    width="180"
                    trigger="hover"
                  >
                    <img :src="row.mainImage" alt="" style="width:150px;height:150px;">
                    <img slot="reference" :src="row.mainImage" alt="" style="width:30px;height:30px;">
                  </el-popover>
                </template>
              </el-table-column>
              <el-table-column prop="productName" label="商品名称" align="center" width="300" />
              <el-table-column prop="validFlag" label="商品状态" align="center" width="150">
                <template slot-scope="{row}">
                  <el-tag :type="row.validFlag | statusFilter">{{ row.validFlag*1 === 2 ? '已上架' : '已下架' }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center">
                <el-button type="text" @click="deleteShop">删除</el-button>
              </el-table-column>
            </el-table>
          </template>
        </el-form-item>
      </template>
      <template v-if="form.jumpType === 2">
        <el-form-item label="选择活动:" prop="jumpActiveId" :rules="rules.jumpActiveId">
          <el-select v-model="form.jumpActiveId" clearable>
            <el-option
              v-for="item in activityList"
              :key="item.id"
              :label="item.topic"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </template>
    </el-form>
    <div class="el-dialog__footer" style="text-align: center;">
      <el-button type="primary" @click="onSubmit('bannerForm')">保存</el-button>
      <el-button plain @click="backToList">返回</el-button>
    </div>
    <!-- 商品弹框 -->
    <good-dialog v-if="dialogVisible" ref="goodDialog" @cancel="handleGoodCancel" @confirm="handleGoodConfirm" />
  </div>
</template>

<script>
import { saveMenu, formMenu, getActiveList } from '@/api/campaign'
import goodDialog from './components/good-dialog'
export default {
  name: 'BannerEdit',
  components: { goodDialog },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        0: 'warning'
      }
      return statusMap[status]
    }
  },
  data() {
    const defaultForm = () => {
      return {
        organizeId: this.$store.getters.organizeId,
        topic: '', // 菜单主题
        image: '',
        sort: 1, // 菜单排序值
        enabledStatus: 1, // 菜单上线状态
        jumpType: null, // 跳转类型
        jumpActiveId: null, // 跳转活动Id
        jumpProductId: null, // 单个跳转商品详情Id
        products: []
      }
    }
    return {
      form: defaultForm(),
      activityList: [],
      editType: 'add',
      // 商品列表
      dialogVisible: false,
      loadImgLoading: false,
      rules: {
        topic: [{ required: true, message: '请填写菜单名称', trigger: 'blur' }],
        image: [{ required: true, message: '请上传菜单图标', trigger: 'blur' }],
        products: [{ required: true, type: 'array', message: '请添加一个商品', trigger: ['change'] }],
        sort: [{ required: true, message: '排序值不能为空', trigger: 'blur' }],
        enabledStatus: [{ required: true, message: '请选择状态', trigger: 'blur' }],
        jumpType: [{ required: true, message: '请选择跳转类型', trigger: 'blur' }],
        jumpActiveId: [{ required: true, message: '请选择活动列表', trigger: 'blur' }]
      },
      listQuery: {
        index: 1,
        pageSize: 100,
        enabledStatus: 1,
        organizeId: this.$store.getters.organizeId
      }
    }
  },
  computed: {
    getToken() {
      return {
        'token': this.$store.getters.token
      }
    },
    actionUrl() {
      return process.env.VUE_APP_BASE_API + '/formData/MultiPictareaddData'
    }
  },
  created() {
    this.editType = this.$route.query.type || 'edit'
    if (this.editType === 'edit') {
      console.log('edit')
      this.formMenu(this.$route.query.id)
    }
    this.getActiveList()
  },
  methods: {
    async getActiveList() {
      // 获取活动列表
      const res = await getActiveList(this.listQuery)
      this.activityList = [...this.activityList, ...res.data.results]
    },
    async formMenu(id) {
      // 获取菜单详情
      try {
        const res = await formMenu(id)
        this.form = { ...this.form, ...res.data }
        if (res.data.jumpType === 2) {
          this.form.products = []
        }
      } catch (error) {
        console.log('error', error)
      }
    },
    // 显示选择商品弹窗
    handleDialogVisible() {
      this.dialogVisible = true
    },
    handleGoodDialogVisible(index) {
      // 显示选择商品弹窗
      this.addIndex = index
      this.dialogGoodVisible = true
    },
    deleteShop() {
      // 清除商品
      this.form.jumpProductId = ''
      this.form.products = []
    },
    handleGoodConfirm(data) {
      // 确认选择商品
      this.form.jumpProductId = data.productId
      this.form.products.push(data)
      console.log('products', this.form.products)
      console.log('jumpProductId', this.form.jumpProductId)
      this.handleGoodCancel()
    },
    onSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.$confirm('是否提交数据', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            console.log('form', this.form)
            this.saveMenu(this.form)
          })
        } else {
          return false
        }
      })
    },
    async saveMenu(params) {
      // 保存
      await saveMenu(params)
      this.$message.success('保存成功')
      setTimeout(() => {
        this.$router.push({ path: '/campaign/list', query: { type: 2 }})
      }, 1000)
    },
    // 取消选择商品
    handleGoodCancel() {
      this.dialogVisible = false
      this.$refs.goodDialog.visible = false
    },
    // 上传图标事件
    handleSuccess(response, file) {
      this.loadImgLoading = true
      this.$nextTick(() => {
        setTimeout(() => {
          this.form.image = response.data
        }, 1000 * 2)
      })
    },
    // 对上传图片的大小、格式进行限制
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isJPG2 = file.type === 'image/jpg'
      const isPNG = file.type === 'image/png'
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isJPG && !isJPG2 && !isPNG) {
        this.$message.error('只支持jpg或png格式图片')
      }
      if (!isLt5M) {
        this.$message.error('请上传5MB以内的图片!')
      }
      return (isJPG || isJPG2 || isPNG) && isLt5M
    },
    reloadImage() {
      this.loadImgLoading = true
      setTimeout(() => {
        this.temp.classifyImage = this.temp.classifyImage.split('?')[0] + '?r=' + Math.floor(Math.random() * 1000)
      }, 1000 * 2)
    },
    loadSucess() {
      this.loadImgLoading = false
    },
    backToList() {
      this.$store.dispatch('tagsView/delView', this.$route).then(() => {
        this.$nextTick(() => {
          this.$router.replace({ path: '/campaign/list', query: { type: 2 }})
        })
      })
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    float: left;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon{
    font-size: 30px;
    color: #999999;
  }
  .el-form-item__label{
      text-align: right !important;
  }
  .el-upload__tip{
    line-height: 20px;
    color: red;
    text-align: left;
    position: absolute;
    right: -50%;
    bottom: 0;
  }
  .span_tip{
    font-size: 12px;
    color: red;
    margin-left: 5px;
  }
  .filter-item-temp{
    width: 100px;
  }
</style>
