<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="activeType" :rules="rules.activeType">
        <el-select v-model="form.activeType" placeholder="请选择" @change="handeleSelChange($event)">
          <el-option label="商品列表" :value="1" />
          <el-option label="宣传图（一张）" :value="2" />
          <el-option label="宣传图（多张）" :value="3" />
        </el-select>
        <el-button v-if="form.activeType === 3" type="primary" icon="el-icon-plus" :disabled="disabled" style="margin-left: 10px;" @click="handleAddList">新增宣传图</el-button>
      </el-form-item>
      <el-form-item label="主题:" prop="topic" :rules="rules.topic">
        <el-input v-model="form.topic" placeholder="请输入活动主题,30个字以内" maxlength="30" 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>
      <template v-if="form.activeType === 1">
        <!-- 商品列表 -->
        <el-form-item label="商品信息" prop="products" :rules="rules.products">
          <el-button type="primary" icon="el-icon-sort" size="mini" :disabled="disabled3(form.products)" @click="handleOnInputBlur">一键排序</el-button>
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleDialogVisible">添加商品</el-button>
          <el-checkbox-group v-show="false" v-model="form.products" />
          <el-table v-show="form.products && form.products.length>0" :data="form.products" border>
            <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 property="productName" label="商品名称" align="center" />
            <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 prop="sort" label="排序" align="center" width="100">
              <template slot-scope="{row}">
                <el-input v-model="row.sort" type="text" :maxlength="4" size="mini" />
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button type="text" @click="handleDeletePros(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </template>
      <!-- 一张宣传图 -->
      <template v-if="form.activeType === 2">
        <div v-for="(activ,index) in form.images" :key="index" class="form-cell">
          <el-form-item label="宣传图:" prop="image" :rules="rules.image" style="margin-bottom: 40px;">
            <div class="form-el-upload" style="width: 375px;height: 680px;">
              <upload-image
                :limit="1"
                :dom-width="'375px'"
                :dom-height="'680px'"
                :dom-index="index"
                :dialog-image-url="activ.image"
                :before-upload="beforeUpload"
                @success="uploadSuccess"
                @remove="handleRemove"
              />
              <p class="uploader-tips">注：请尽量上传700*1000(px)尺寸的图片。</p>
            </div>
          </el-form-item>
          <!-- 商品列表 -->
          <el-form-item label="商品信息" :prop="`images.${index}.products`" :rules="rules.products">
            <el-button type="primary" icon="el-icon-sort" size="mini" :disabled="disabled3(activ.products)" @click="handleOnInputSort(index)">一键排序</el-button>
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleDialogVisible(index)">添加商品</el-button>
            <el-checkbox-group v-show="false" v-model="activ.products" />
            <el-table v-show="activ.products && activ.products.length>0" :data="activ.products" border>
              <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 property="productName" label="商品名称" align="center" />
              <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" width="100">
                <template slot-scope="{row}">
                  <el-input v-model="row.sort" type="text" maxlength="4" />
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                  <el-button type="text" @click="handleDeletePros(scope.$index,index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </div>
      </template>
      <!-- 多张宣传图 -->
      <template v-if="form.activeType === 3">
        <div v-for="(activ,index) in form.images" :key="index" class="form-cell">
          <el-form-item label="标题:" :prop="`images.${index}.topic`" :rules="rules.topic1">
            <el-input v-model="activ.topic" placeholder="请输入宣传图标题" maxlength="30" style="width: 200px;" />
          </el-form-item>
          <el-form-item label="宣传图:" prop="image" :rules="rules.image" style="margin-bottom: 40px;">
            <div class="form-el-upload" style="width: 350px;height: 170px;">
              <upload-image
                :limit="1"
                :dom-width="'350px'"
                :dom-height="'170px'"
                :dom-index="index"
                :dialog-image-url="activ.image"
                :before-upload="beforeUpload"
                @success="uploadSuccess1"
                @remove="handleRemove1"
              />
              <p class="uploader-tips">注：请尽量上传700*360(px)尺寸的图片。</p>
            </div>
          </el-form-item>
          <!-- 商品列表 -->
          <el-form-item label="商品信息" :prop="`images.${index}.products`" :rules="rules.products">
            <el-button type="primary" icon="el-icon-sort" size="mini" :disabled="disabled3(activ.products)" @click="handleOnInputSort(index)">一键排序</el-button>
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleDialogVisible(index)">添加商品</el-button>
            <el-checkbox-group v-show="false" v-model="activ.products" />
            <el-table v-show="activ.products && activ.products.length>0" :data="activ.products" border>
              <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 property="productName" label="商品名称" align="center" />
              <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" width="100">
                <template slot-scope="{row}">
                  <el-input v-model="row.sort" maxlength="4" minlength="1" />
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                  <el-button type="text" @click="handleDeletePros(scope.$index,index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-button class="delete_label" :disabled="disabled1" icon="el-icon-delete" size="mini" type="danger" @click="handleDelete(index)">删除</el-button>
        </div>
      </template>
    </el-form>
    <div class="el-dialog__footer" style="text-align: left;">
      <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 { saveActive, formActive } from '@/api/campaign'
import goodDialog from './components/good-multi-dialog'
const defaultImages = () => {
  return {
    image: '',
    products: []
  }
}
export default {
  name: 'ActivityEdit',
  components: { goodDialog },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        0: 'warning'
      }
      return statusMap[status]
    }
  },
  data() {
    const defaultForm = () => {
      return {
        organizeId: this.$store.getters.organizeId,
        topic: '', // 活动主题
        activeType: 1, // 活动类型 1商品列表 2宣传图（一张） 3宣传图（多张）)
        enabledStatus: 1, // 活动上线状态
        products: [],
        images: [// 活动 2,3
          {
            image: '',
            products: []
          }
        ]
      }
    }
    return {
      form: defaultForm(),
      ActivIndex: 0,
      editType: 'add',
      // 商品列表
      dialogVisible: false,
      loadImgLoading: false,
      rules: {
        activeType: [{ required: true, message: '请选择活动类型', trigger: 'blur' }],
        topic: [{ required: true, message: '请填写轮播主题', trigger: 'blur' }],
        topic1: [{ required: true, message: '请填写宣传图标题', trigger: 'blur' }],
        banner: [{ 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' }]
      },
      handelProduts: [],
      oneImageList: [],
      moreImageList: []
    }
  },
  computed: {
    disabled() {
      return this.form.images.length === 10
    },
    disabled1() {
      return this.form.images.length === 1
    }
  },
  created() {
    this.editType = this.$route.query.type || 'edit'
    if (this.editType === 'edit') {
      console.log('edit')
      this.formActive(this.$route.query.id)
    }
  },
  methods: {
    async formActive(id) {
      // 获取轮播图详情
      const res = await formActive(id)
      this.form = { ...this.form, ...res.data }
    },
    // 显示选择商品弹窗
    handleDialogVisible(index) {
      if (index) { this.ActivIndex = index }
      this.dialogVisible = true
    },
    deleteShop() {
      // 清除供应商
      this.form.productId = ''
      this.productData = []
    },
    handleGoodConfirm(data) {
      // 确认选择商品
      if (this.form.activeType === 1) {
        this.form.products = [...this.form.products, ...data]
      } else {
        this.form.images[this.ActivIndex].products = [...this.form.images[this.ActivIndex].products, ...data]
      }
      console.log('products', this.form.products)
      this.handleGoodCancel()
    },
    handeSetSort() {
      return { sort: 0 }
    },
    handleDeletePros(index, acIndex) {
      // 删除商品
      this.$confirm('确定删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log('1111', this.form)
        if (this.form.activeType === 1) {
          this.form.products.splice(index, 1)
        } else {
          this.form.images[acIndex].products.splice(index, 1)
        }
      })
    },
    onSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.$confirm('是否提交数据', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            console.log('form', this.form)
            this.saveActive(this.form)
          })
        } else {
          return false
        }
      })
    },
    // 保存活动
    async saveActive(params) {
      // 保存
      await saveActive(params)
      this.$message.success('保存成功')
      setTimeout(() => {
        this.$router.push({ path: '/campaign/activity-list' })
      }, 1000)
    },
    // 修改活动类型时清空商品
    handeleSelChange(value) {
      if (value === 1) {
        this.form.products = []
      } else {
        this.form.images = []
        this.form.images.push(defaultImages())
      }
    },
    // 取消选择商品
    handleGoodCancel() {
      this.dialogVisible = false
      this.$refs.goodDialog.visible = false
    },
    handleAddList() {
      // 新增宣传图
      this.form.images.push(defaultImages())
    },
    handleDelete(index) {
      // 删除单挑优惠券
      this.$confirm('确定删除此条吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.form.images.splice(index, 1)
      })
    },
    handleOnInputBlur() {
      // 商品排序
      this.form.products.sort(this.sortByEnent('sort'))
    },
    handleOnInputSort(index) {
      // 商品排序
      this.form.images[index].products.sort(this.sortByEnent('sort'))
    },
    sortByEnent(i) {
      // 排序
      return function(a, b) {
        return a[i] - b[i] //  a[i] - b[i]为正序，倒叙为  b[i] - a[i]
      }
    },
    disabled3(array) {
      if (array && array.length >= 2) {
        return false
      } else {
        return true
      }
    },
    // 单张上传宣传图
    uploadSuccess(data, file, fileList) {
      this.form.images[data.data.index].image = data.data.data
      console.log('images', this.form.images)
    },
    // 单张上传宣传图删除
    handleRemove({ data, file, fileList }) {
      this.form.images[data.index].image = fileList.length || ''
      console.log('images', this.form.images)
    },
    // 多张上传宣传图
    uploadSuccess1(data, file, fileList) {
      this.form.images[data.data.index].image = data.data.data
      console.log('images', this.form.images)
    },
    // 宣传图删除
    handleRemove1({ data, file, fileList }) {
      this.form.images[data.index].image = fileList.length || ''
      console.log('images', this.form.images)
    },
    beforeUpload(file) {
      const flag = file.size / 1024 / 1024 < 5
      if (!flag) {
        this.$message.error('上传图片大小不能超过 5MB!')
      }
      return flag
    },
    backToList() {
      this.$store.dispatch('tagsView/delView', this.$route).then(() => {
        this.$nextTick(() => {
          this.$router.replace({ path: '/campaign/activity-list' })
        })
      })
    }
  }
}
</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;
  }
  .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;
  }
  .form-cell{
    border: 1px solid #e1e1e1;
    border-radius: 8px;
    box-sizing: border-box;
    box-shadow: 0px 3px 6px 0px rgba(0, 0, 0, 0.07);
    padding: 20px;
    position: relative;
    margin-bottom: 20px;
  }
  .delete_label{
    position: absolute;
    right: 2%;
    top: 20px;
  }
</style>
