<template>
  <div class="app-container" style="width: 800px;margin: 0 auto;">
    <el-form ref="floorForm" :model="form" label-width="100px">
      <el-form-item label="楼层标题:" prop="topic" :rules="rules.topic">
        <el-input v-model="form.topic" placeholder="10个字以内" maxlength="30" style="width: 200px;" />
      </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="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" :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>
    </el-form>
    <div class="el-dialog__footer" style="text-align: right;">
      <el-button type="primary" @click="onSubmit('floorForm')">保存</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 { savePageFloor, formPageFloor } from '@/api/floor'
import goodDialog from './components/good-multi-dialog'
export default {
  name: 'FloorEdit',
  components: { goodDialog },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        0: 'warning'
      }
      return statusMap[status]
    }
  },
  data() {
    const defaultForm = () => {
      return {
        organizeId: this.$store.getters.organizeId,
        sort: 0,
        topic: '', // 楼层标题
        enabledStatus: 1, // 楼层启用状态
        products: [] // 楼层商品列表
      }
    }
    return {
      form: defaultForm(),
      ActivIndex: 0,
      editType: 'add',
      // 商品列表
      dialogVisible: false,
      loadImgLoading: false,
      rules: {
        topic: [{ 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: []

    }
  },
  computed: {
    disabled() {
      return this.form.images.length === 10
    },
    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.formPageFloor(this.$route.query.id)
    }
  },
  methods: {
    async formPageFloor(id) {
      // 获取轮播图详情
      const res = await formPageFloor(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) {
      // 确认选择商品
      this.form.products = [...this.form.products, ...data]
      console.log('products', this.form.products)
      this.handleGoodCancel()
    },
    handeSetSort() {
      return { sort: 0 }
    },
    handleDeletePros(index) {
      // 删除商品
      console.log('1111', index)
      this.$confirm('确定删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.form.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.savePageFloor(this.form)
          })
        } else {
          return false
        }
      })
    },
    // 保存活动
    async savePageFloor(params) {
      // 保存
      await savePageFloor(params)
      this.$message.success('保存成功')
      setTimeout(() => {
        this.$store.dispatch('tagsView/delView', this.$route).then(() => {
          this.$nextTick(() => {
            this.$router.push({ path: '/floor/list' })
          }, 1000)
        })
      })
    },
    // 修改活动类型时清空商品
    handeleSelChange() {
      this.handelProduts = []
    },
    // 取消选择商品
    handleGoodCancel() {
      this.dialogVisible = false
      this.$refs.goodDialog.visible = false
    },
    handleOnInputBlur() {
      // 商品排序
      this.form.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
      }
    },
    // 上传图标事件
    handleSuccess(response, file) {
      this.loadImgLoading = true
      this.$nextTick(() => {
        setTimeout(() => {
          this.temp.classifyImage = 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: '/floor/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;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
  }
  .avatar {
    width: 148px;
    height: 148px;
    display: block;
  }
  .avatar img {
    width: 148px;
    height: 148px;
    display: block;
  }
  .el-form-item__label{
      text-align: right !important;
  }
  .form-el-upload{
    width: 150px;
  }
  .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>
