<template>
  <el-dialog :title="(modelType == 'add' ? '添加' : '编辑') + '店铺信息'" width="800px" :visible.sync="dialogVisible">
    <el-form :model="form" :rules="rules" ref="VideoCoverFormForm" label-width="100px">
      <el-form-item prop="shopName" label="店铺名称:">
        <el-input placeholder="请输入店铺名称" v-model="form.shopName"></el-input>
      </el-form-item>
      <el-form-item prop="coverPicture" label="封面图:" required>
        <el-upload
          class="avatar-uploader"
          :action="action"
          accept="image/*"
          :show-file-list="false"
          :headers="{
            'Authorization': 'Bearer ' + token
          }"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <div v-loading="uploading">
            <div v-if="form.coverPicture" class="avatar-black">
              <img :src="form.coverPicture" class="avatar">
              <el-tooltip
                class="item"
                effect="dark"
                content="删除"
                placement="bottom-end">
                  <i class="close el-icon-circle-close"
                  @click.stop="imgUploadDel()"></i>
              </el-tooltip>
            </div>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="封面文字:">
        <el-input placeholder="请输入封面文字" v-model="form.coverText"></el-input>
      </el-form-item>
      <el-form-item label="平台类型:" required>
        <el-radio-group v-model="form.type">
          <el-radio :label="0">品牌（国内）</el-radio>
          <el-radio :label="1">海外</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" :loading="comfirmLoading" @click="handleConfirm">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { addShopConfigInfo, editShopConfigInfo } from "@/api/videoCoverManager";
import { api } from "@/api/api";
import { getToken } from '@/utils/auth'
export default {
  name: "VideoCoverFormModal",
  props: {
  },
  data() {
    var checkCoverPicture = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请上传封面图'));
      } else {
        callback();
      }
    };
    return {
      action: api.fileUrl,
      uploading: false,
      form: {
        shopName: '',
        coverPicture: '',
        coverText: '',
        type: 0
      },
      modelType: 'add',
      dialogVisible: false,
      comfirmLoading: false,
      editId: '',
      shopName: '', // 店铺名称不能重复
      rules: {
        shopName: [
          { required: true, message: "请输入店铺名称", trigger: "blur" }
        ],
        coverPicture: [
          { validator: checkCoverPicture, trigger: "change" }
        ]
      }
    };
  },
  computed: {
    token() {
      return getToken();
    }
  },
  watch: {
    dialogVisible(val) {
      if (!val) {
        this.uploading = false;
        this.form = {
          shopName: '',
          coverPicture: '',
          coverText: '',
          type: 0
        }
        this.modelType =  'add';
        this.comfirmLoading = false;
        this.editId = '';
      }
    }
  },
  methods: {
    show(rows, type) {
      this.dialogVisible = true;
      this.comfirmLoading = false;
      this.modelType = type;
      if (type == 'edit') {
        this.editId = rows.id;
        this.shopName = rows.shopName;
      }
      this.$nextTick(() => {
        this.form = type == 'edit' ? {
          shopName: rows.shopName,
          coverPicture: rows.coverPicture,
          coverText: rows.coverText,
          type: rows.type
        } : {
          shopName: '',
          coverPicture: '',
          coverText: '',
          type: 0
        }
        this.$refs.VideoCoverFormForm.resetFields()
      })
    },
    handleAvatarSuccess(res) {
      this.uploading = false
      this.$refs.VideoCoverFormForm.clearValidate(['coverPicture']);
      if (res.code == 200) {
        this.form.coverPicture = res.data.url;
      } else {
        this.$message.error('上传出错，请重试！');
      }
    },
    beforeAvatarUpload(file) {
      this.uploading = true;
      const imagesTypes = ['image/png','image/gif','image/jpeg']
      const isImages = imagesTypes.includes(file.type)

      if (!isImages) {
        this.uploading = false;
        this.$message.error('图片只能是JPG、PNG、GIF格式!');
      }
      return isImages;
    },
    imgUploadDel() {
      //删除
      this.$confirm("确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.form.coverPicture = '';
        this.$notify({
          title: "成功",
          message: "删除成功",
          type: "success",
          duration: 3000
        });
      });
    },
    handleConfirm() {
      this.$refs.VideoCoverFormForm.validate(valid => {
        if (valid) {
          this.comfirmLoading = true;
          const params = this.form;
          if (this.modelType == 'add') {
            addShopConfigInfo(params).then(res =>{
              this.dialogVisible = false;
              if(res.code == 200){
                this.$message.success(res.msg || "操作成功");
                this.$emit("confirm");
              }
            }).finally(()=>{
              this.comfirmLoading = false;
            })
          } else {
            params.id = this.editId;
            if (this.shopName == this.form.shopName) {
              // 说明没有更新店铺名，店铺名必须唯一
              delete params.shopName;
            }
            editShopConfigInfo(params).then(res =>{
              this.dialogVisible = false;
              if(res.code == 200){
                this.$message.success(res.msg || "操作成功");
                this.$emit("confirm");
              }
            }).finally(()=>{
              this.comfirmLoading = false;
            })
          }
          
        } else {
          return false;
        }
      });
    }
  }
};
</script>
<style lang="scss">
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    display: block;
  }
  .avatar-black {
    width: 180px;
    height: 180px;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    i {
      position: absolute;
      top: -10px;
      right: -10px;
      cursor: pointer;
      z-index: 999999;
      color: red;
      background-color: #fff;
      font-size: 30px;
      border-radius: 50%;
      outline: none;
      width: 28px;
      height: 28px;
      line-height: 28px;
      font-size: 28px;
      color: #8c939d;
      display: block;
      text-align: center;
    }
    img {
      max-height: 100%;
      max-width: 100%;
      vertical-align: middle;
    }
  }
</style>


