<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    width="750px"
    :visible="visible"
    :append-to-body="true"
    :close-on-click-modal="true"
    custom-class="ele-dialog-form"
    :title="isUpdate ? '修改商品' : '添加商品'"
    @update:visible="updateVisible"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="82px">
      <el-form-item label="商品标题:" prop="title">
        <el-input
          clearable
          :maxlength="60"
          v-model="form.title"
          placeholder="请输入商品标题"
        />
      </el-form-item>
      <el-form-item label="商品价格:" prop="price">
        <el-input-number
          v-model="form.price"
          controls-position="right"
          :min="0"
          style="width: 150px; margin-right: 10px"
        />
      </el-form-item>
      <el-form-item label="库存数:" prop="stock">
        <el-input-number
          v-model="form.stock"
          controls-position="right"
          :min="0"
          style="width: 150px; margin-right: 10px"
        />
      </el-form-item>
      <el-form-item label="商品图片:" prop="banner">
        <ele-image-upload
          v-model="form.banner"
          :limit="10"
          :drag="true"
          :multiple="true"
          :upload-handler="bannerHandler"
          @upload="onUpload"
        />
        <div class="ele-text-secondary">建议尺寸750X680</div>
      </el-form-item>
      <el-form-item label="商品类型:">
        <el-select
          clearable
          v-model="form.type"
          placeholder="请选择"
          class="ele-fluid"
        >
          <el-option label="权益" :value="0" />
          <el-option label="商品" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="抢购时间:">
        <el-date-picker
          v-model="form.dateRange"
          type="datetimerange"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          class="ele-fluid"
        />
      </el-form-item>
      <el-form-item label="使用时间:">
        <el-date-picker
          v-model="form.useRange"
          type="datetimerange"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          class="ele-fluid"
        />
      </el-form-item>
      <el-form-item label="是否核销:">
        <el-radio-group v-model="form.ifCode">
          <el-radio :label="0">否</el-radio>
          <el-radio :label="1">是</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="收货地址:">
        <el-radio-group v-model="form.ifAddress">
          <el-radio :label="0">不需要</el-radio>
          <el-radio :label="1">需要</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="排序:">
        <el-input-number
          v-model="form.sort"
          controls-position="right"
          :min="0"
          style="width: 150px; margin-right: 10px"
        />
      </el-form-item>
      <el-form-item label="商品详情:" prop="descrip">
        <!-- 编辑器 -->
        <div v-if="editversion">
          <tinymce-editor
            :init="editoption"
            v-model="form.descrip"
            placeholder="请输入商品详情"
          />
        </div>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="updateVisible(false)">取消</el-button>
      <el-button type="primary" :loading="loading" @click="save">
        保存
      </el-button>
    </template>
  </ele-modal>
</template>

<script>
  import TinymceEditor from '@/components/TinymceEditor/index.vue';
  import EleImageUpload from 'ele-admin/es/ele-image-upload';
  import request from '@/utils/request';
  import { addGoods, updateGoods } from '@/api/sylive/goods';
  export default {
    components: { EleImageUpload, TinymceEditor },
    props: {
      // 弹窗是否打开
      visible: Boolean,
      // 修改回显的数据
      data: Object
    },
    data() {
      const defaultForm = {
        itemId: null,
        activityId: null,
        type: 0,
        title: '',
        price: 0,
        stock: 0,
        banner: [],
        dateRange: [],
        useRange: [],
        sort: 0,
        ifAddress: 0,
        ifCode: 0,
        descrip: ''
      };
      return {
        editversion: false,
        editoption: {
          height: 300,
          toolbar: [
            'code | forecolor backcolor bold italic underline strikethrough link anchor | alignleft aligncenter alignright alignjustify outdent indent | fontsizeselect | bullist numlist | \
    table emoticons hr preview | fullscreen | bdmap indent2em lineheight formatpainter axupimgs| image emoticons hr '
          ]
        },
        defaultForm,
        // 表单数据
        form: { ...defaultForm },
        // 表单验证规则
        rules: {
          title: [
            {
              required: true,
              message: '请输入商品标题',
              trigger: 'blur'
            }
          ],
          price: [
            {
              required: true,
              message: '请输入商品价格',
              trigger: 'blur'
            }
          ],
          stock: [
            {
              required: true,
              message: '请输入库存数',
              trigger: 'blur'
            }
          ]
        },
        // 提交状态
        loading: false,
        // 是否是修改
        isUpdate: false
      };
    },
    computed: {
      // 是否开启响应式布局
      styleResponsive() {
        return this.$store.state.theme.styleResponsive;
      }
    },
    methods: {
      /* 保存编辑 */
      save() {
        this.$refs.form.validate((valid) => {
          if (!valid) {
            return false;
          }
          this.loading = true;
          const data = {
            ...this.form
          };
          const saveOrUpdate = this.isUpdate ? updateGoods : addGoods;
          saveOrUpdate(data)
            .then((msg) => {
              this.loading = false;
              this.$message.success(msg);
              this.updateVisible(false);
              this.$emit('done');
            })
            .catch((e) => {
              this.loading = false;
              this.$message.error(e.message);
            });
        });
      },
      /* 更新visible */
      updateVisible(value) {
        this.$emit('update:visible', value);
      },
      /* 上传事件 */
      bannerHandler(file) {
        const item = {
          file,
          uid: file.uid,
          name: file.name,
          progress: 0,
          status: null
        };
        if (!file.type.startsWith('image')) {
          this.$message.error('只能选择图片');
          return;
        }
        if (file.size / 1024 / 1024 > 2) {
          this.$message.error('大小不能超过 2MB');
          return;
        }
        item.url = window.URL.createObjectURL(file);
        // 关键就是这里要自己 push 添加数据而不是靠 v-modal 自动更新
        this.form.banner.push(item);
        this.onUpload(item);
      },
      /* 上传 item */
      onUpload(item) {
        item.status = 'uploading';
        const formData = new FormData();
        formData.append('file', item.file);
        request({
          url: '/upload',
          method: 'post',
          data: formData,
          onUploadProgress: (e) => {
            if (e.lengthComputable) {
              item.progress = (e.loaded / e.total) * 100;
            }
          }
        })
          .then((res) => {
            if (res.data.code === 0) {
              item.status = 'done';
              item.url = res.data.data.full_url;
              item.fileUrl = res.data.data.url;
            }
          })
          .catch(() => {
            item.status = 'exception';
          });
      }
    },
    watch: {
      visible(visible) {
        this.editversion = false;
        if (visible) {
          this.editversion = true;
          if (this.data.itemId) {
            this.$util.assignObject(this.form, {
              ...this.data
            });
            this.isUpdate = true;
          } else {
            this.form.banner = [];
            this.form.activityId = this.data.activityId;
            this.isUpdate = false;
          }
        } else {
          this.$refs.form.clearValidate();
          this.form = { ...this.defaultForm };
        }
      }
    }
  };
</script>
<style>
  .ele-image-upload-list .ele-image-upload-item {
    margin-top: 5px;
    margin-bottom: 5px;
  }
  .tox-menubar {
    display: none !important;
  }
  /* .tox-toolbar__group:last-child {
    display: none !important;
  } */
</style>
