<template>
  <div class="app-container" style="width: 800px; margin: 0 auto">
    <el-form ref="bannerForm" :model="form" label-width="130px">
      <el-form-item label="PC端图片:" prop="pcImage" :rules="rules.pcImage" 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="handleSuccessPcImage"
            :before-upload="beforeUpload"
          >
            <div v-loading="loadPcImageLoading" class="avatar" style="width: 142px; height: 177px; display: block">
              <img
                v-if="form.pcImage"
                :src="form.pcImage"
                style="width: 142px; height: 177px; display: block"
                @error="reloadImage"
                @load="loadPcImageSucess"
              />
              <i
                v-else
                class="el-icon-plus avatar-uploader-icon"
                style="width: 142px; height: 177x; line-height: 177px"
              ></i>
            </div>
          </el-upload>
          <p class="uploader-tips">注：请尽量上传284*343(px)尺寸的图片。</p>
        </div>
      </el-form-item>
      <el-form-item label="小程序端图片:" prop="appImage" :rules="rules.appImage" style="margin-bottom: 40px">
        <div class="form-el-upload" style="width: 142px; height: 177px">
          <el-upload
            class="avatar-uploader"
            :action="actionUrl"
            :headers="getToken"
            :show-file-list="false"
            :on-success="handleSuccessAppImage"
            :before-upload="beforeUpload"
          >
            <div v-loading="loadImgLoading" class="avatar" style="width: 142px; height: 177px; display: block">
              <img
                v-if="form.appImage"
                :src="form.appImage"
                style="width: 153px; height: 230px; display: block"
                @error="reloadImage"
                @load="loadSucess"
              />
              <i
                v-else
                class="el-icon-plus avatar-uploader-icon"
                style="width: 153px; height: 230px; line-height: 177px"
              ></i>
            </div>
          </el-upload>
          <p class="uploader-tips">注：请尽量上传307*460(px)尺寸的图片。</p>
        </div>
      </el-form-item>
      <el-form-item label="供应商" prop="shops" :rules="rules.shops">
        <template v-if="form.shops && form.shops.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.shops" />
        </template>
        <template v-else>
          <el-table :data="form.shops" border width="1000">
            <el-table-column prop="shopName" label="供应商名称" align="center" />
            <el-table-column prop="linkMan" label="联系人" align="center" />
            <el-table-column prop="mobile" label="手机号" align="center" />
            <el-table-column label="操作" align="center">
              <el-button type="text" @click="deleteShop"> 删除 </el-button>
            </el-table-column>
          </el-table>
        </template>
      </el-form-item>
      <el-form-item label="跳转链接:" prop="jumpLink" :rules="rules.jumpLink">
        <el-input v-model="form.jumpLink" placeholder="请输入跳转链接" maxlength="200" style="width: 600px" />
      </el-form-item>
      <el-form-item label="状态:" prop="status" :rules="rules.status">
        <el-select v-model="form.status" placeholder="请选择">
          <el-option label="上架" :value="0" />
          <el-option label="下架" :value="1" />
        </el-select>
      </el-form-item>
    </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>
    <!-- 供应商弹框 -->
    <shop-dialog v-if="shopDialogVisible" ref="shopDialog" @confirm="handleAddShopConfirm" @cancel="handleCancel" />
  </div>
</template>

<script>
import { getShopAdvertisingImageById, saveShopAdvertisingImage } from '@/api/user/customer/customer'
import ShopDialog from './components/shop-advertis-dialog'

export default {
  name: 'AdvertisEdit',
  components: { ShopDialog },
  data() {
    const defaultForm = () => {
      return {
        id: '',
        shopId: this.$route.query.shopId,
        pcImage: '', // PC广告图
        appImage: '', // 小程序广告图
        jumpLink: '', // 跳转链接
        status: 0, // 上下架状态 0 上架 1 下架
        addTime: '', // 添加时间
        shops: []
      }
    }
    return {
      form: defaultForm(),
      editType: 'add',
      // 商品列表
      shopDialogVisible: false,
      loadImgLoading: false,
      loadPcImageLoading: false,
      rules: {
        pcImage: [{ required: true, message: '请上传PC广告图', trigger: 'blur' }],
        appImage: [{ required: true, message: '请上传小程序广告图', trigger: 'blur' }],
        shops: [{ required: true, type: 'array', message: '请添加供应商', trigger: ['change'] }],
        jumpLink: [{ required: true, message: '请填写跳转链接', trigger: 'blur' }],
        sort: [{ required: true, message: '排序值不能为空', trigger: 'blur' }],
        status: [{ required: true, message: '请选择状态', trigger: 'blur' }]
      }
    }
  },
  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.getShopAdvertisingImageById(this.$route.query.id)
    }
  },
  methods: {
    async getShopAdvertisingImageById(id) {
      // 获取菜单详情
      try {
        const res = await getShopAdvertisingImageById(id)
        this.form = { ...this.form, ...res.data }
      } catch (error) {
        console.log('error', error)
      }
    },
    // 显示选择商品弹窗
    handleDialogVisible() {
      this.shopDialogVisible = true
    },
    handleGoodDialogVisible(index) {
      // 显示选择商品弹窗
      this.addIndex = index
      this.dialogGoodVisible = true
    },
    deleteShop() {
      // 清除供应商
      this.form.shopId = ''
      this.form.shops = []
    },
    handleAddShopConfirm(data) {
      // 确认选择商品
      this.form.shopId = data.shopId
      this.form.shops.push(data)
      this.handleCancel()
    },
    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm('是否提交数据', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            console.log('form', this.form)
            this.saveShopAdvertisingImage(this.form)
          })
        } else {
          return false
        }
      })
    },
    async saveShopAdvertisingImage(params) {
      // 保存
      await saveShopAdvertisingImage(params)
      this.$message.success('保存成功')
      setTimeout(() => {
        this.$router.push({ path: '/user/customer/advertis-list' })
      }, 1000)
    },
    // 取消选择商品
    handleCancel() {
      this.shopDialogVisible = false
      this.$refs.shopDialog.visible = false
    },
    // 上传PC广告图事件
    handleSuccessPcImage(response, file) {
      this.loadPcImageLoading = true
      this.$nextTick(() => {
        setTimeout(() => {
          this.form.pcImage = response.data
        }, 1000 * 2)
      })
    },
    // 上传小程序广告图事件
    handleSuccessAppImage(response, file) {
      this.loadImgLoading = true
      this.$nextTick(() => {
        setTimeout(() => {
          this.form.appImage = 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)
    },
    loadPcImageSucess() {
      this.loadPcImageLoading = false
    },
    loadSucess() {
      this.loadImgLoading = false
    },
    backToList() {
      this.$store.dispatch('tagsView/delView', this.$route).then(() => {
        this.$nextTick(() => {
          this.$router.replace({ path: '/user/customer/advertis-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: 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;
}
.uploader-tips {
  position: absolute;
  bottom: 0;
  left: 160px;
  line-height: 28px;
  color: red;
  margin: 0;
}
</style>
