<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    width="800px"
    :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="bgImg">
        <ele-image-upload
          v-model="form.bgImg"
          :limit="1"
          :drag="true"
          :multiple="false"
          :upload-handler="bgImgHandler"
          @upload="onUpload"
        />
        <div class="ele-text-secondary">
          建议尺寸1125X2000，主题内容建议做在顶部0~1700像素区域
        </div>
      </el-form-item>
      <el-form-item label="所属机构:" prop="organizationId">
        <el-select
          v-model="form.organizationId"
          placeholder="请选择所属机构"
          class="ele-fluid"
        >
          <el-option
            v-for="item in organizationList"
            :key="item.organizationId"
            :label="item.organizationName"
            :value="item.organizationId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间:" prop="activityStart">
        <el-date-picker
          type="datetime"
          v-model="form.activityStart"
          placeholder="请选择活动开始时间"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          class="ele-fluid"
        />
      </el-form-item>
      <el-form-item label="直播频道:" prop="channelId">
        <el-input
          clearable
          :maxlength="30"
          v-model="form.channelId"
          placeholder="请输入直播频道"
        />
      </el-form-item>
      <el-form-item label="直播时间:" prop="dateRange">
        <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-input
          clearable
          :maxlength="30"
          v-model="form.drawCode"
          placeholder="请输入抽奖码"
        />
      </el-form-item>
      <el-form-item label="收款账户:" prop="mchId">
        <activity-mch-id-select v-model="form.mchId" />
      </el-form-item>
      <el-form-item label="banner:">
        <ele-image-upload
          v-model="form.banner"
          :limit="1"
          :drag="true"
          :multiple="false"
          :upload-handler="bannerHandler"
          @upload="onUpload"
        />
        <div class="ele-text-secondary">建议尺寸750*340</div>
      </el-form-item>
      <el-form-item label="分享图片:" prop="sharePhoto">
        <ele-image-upload
          v-model="form.sharePhoto"
          :limit="1"
          :drag="true"
          :multiple="false"
          :upload-handler="sharePhotoHandler"
          @upload="onUpload"
        />
        <div class="ele-text-secondary">建议尺寸200X200</div>
      </el-form-item>
      <el-form-item label="分享海报:" prop="shareImg">
        <ele-image-upload
          v-model="form.shareImg"
          :limit="10"
          :drag="true"
          :multiple="true"
          :upload-handler="shareImgHandler"
          @upload="onUpload"
        />
        <div class="ele-text-secondary">
          尺寸宽度750，二维码尺寸160X160，二维码位置（距离底部80,距离右边40）
        </div>
      </el-form-item>
      <el-form-item label="分享文案:" prop="shareTitle">
        <div
          style="margin: 8px 0"
          v-for="(item, index) in form.shareTitle"
          :key="index"
        >
          <el-input
            clearable
            :maxlength="60"
            v-model="form.shareTitle[index]"
            placeholder="请输入分享文案"
          />
        </div>
        <el-button
          type="primary"
          plain
          size="small"
          icon="el-icon-plus"
          @click="addShareTitle"
        >
          新增分享文案
        </el-button>
      </el-form-item>
      <el-form-item label="黑名单:">
        <el-radio-group v-model="form.blacklist">
          <el-radio :label="0">否</el-radio>
          <el-radio :label="1">是</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="按扭文案:">
        <el-input
          clearable
          v-model="form.button.title"
          placeholder="请输入按扭文案"
        />
      </el-form-item>
      <el-form-item label="弹幕颜色:">
        <el-radio-group v-model="form.barrage.color">
          <el-radio :label="0">黑</el-radio>
          <el-radio :label="1">白</el-radio>
        </el-radio-group>
        <el-input
          clearable
          v-model="form.barrage.title"
          placeholder="请输入弹幕文案"
        />
      </el-form-item>
      <el-form-item label="报名预约:">
        <el-radio-group v-model="form.signBespeak.status">
          <el-radio :label="0">否</el-radio>
          <el-radio :label="1">是</el-radio>
        </el-radio-group>
        <el-select
          v-if="form.signBespeak.status"
          v-model="form.signBespeak.itemId"
          placeholder="请选择关联商品"
          clearable
          class="ele-fluid"
        >
          <el-option
            v-for="item in goodsList"
            :key="item.itemId"
            :value="item.itemId"
            :label="item.title"
          />
        </el-select>
        <el-input
          v-if="form.signBespeak.status"
          v-model="form.signBespeak.title"
          style="padding-top: 10px"
          clearable
          placeholder="请输入弹窗标题"
        />
        <div
          style="padding-top: 10px"
          v-if="form.signBespeak.status && editVersion"
        >
          <tinymce-editor
            :init="editoption"
            v-model="form.signBespeak.content"
            placeholder="请输入弹窗内容"
          />
        </div>
      </el-form-item>
      <el-form-item label="活动底部:">
        <el-table :data="form.bottoms" :border="true" style="width: 100%">
          <el-table-column label="标题">
            <template v-slot="{ row }">
              <el-input v-model="row.title" placeholder="标题" />
            </template>
          </el-table-column>
          <el-table-column label="类型" align="center">
            <template v-slot="{ row }">
              <el-select v-model="row.urlType" class="ele-fluid">
                <el-option label="链接" value="link" />
                <el-option label="小程序" value="miniProgram" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="链接" width="180px" align="center">
            <template v-slot="{ row }">
              <el-input
                v-model="row.url"
                placeholder="请输入链接"
                :rows="2"
                type="textarea"
              />
              <el-input
                v-if="row.urlType == 'miniProgram'"
                v-model="row.miniProgramId"
                placeholder="小程序原始id"
                style="padding-top: 5px"
                :rows="2"
                type="textarea"
              />
            </template>
          </el-table-column>
          <el-table-column label="图标" width="120px" align="center">
            <template v-slot="{ row, $index }">
              <ele-image-upload
                v-model="row.icon"
                :limit="1"
                :drag="true"
                :multiple="false"
                :upload-handler="$index == 0 ? uploadHandler0 : uploadHandler1"
                @upload="onUpload"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="70px"
            align="center"
            :resizable="false"
          >
            <template v-slot="{ row, $index }">
              <span class="ele-action">
                <el-popconfirm
                  title="确定要删除此底部吗?"
                  @confirm="removeBottoms(row, $index)"
                >
                  <template v-slot:reference>
                    <el-link
                      icon="el-icon-delete"
                      type="danger"
                      :underline="false"
                    >
                      删除
                    </el-link>
                  </template>
                </el-popconfirm>
              </span>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          icon="el-icon-plus"
          style="width: 100%; margin-top: 15px"
          @click="addBottoms"
        >
          新增活动底部菜单
        </el-button>
      </el-form-item>
      <el-form-item label="客服链接:">
        <el-input
          clearable
          :maxlength="60"
          v-model="form.serviceLink"
          placeholder="请输入客服链接"
        />
      </el-form-item>
      <el-form-item label="协议标题:">
        <el-input
          clearable
          :maxlength="60"
          v-model="form.protocolTitle"
          placeholder="请输入活动标题"
        />
      </el-form-item>
      <el-form-item label="协议内容:">
        <!-- 编辑器 -->
        <div v-if="editVersion">
          <tinymce-editor
            :init="editoption"
            v-model="form.protocol"
            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 ActivityMchIdSelect from './activity-mch-id-select.vue';
  import EleImageUpload from 'ele-admin/es/ele-image-upload';
  import request from '@/utils/request';
  import { addActivity, updateActivity } from '@/api/sylive/activity';
  import { listGoods } from '@/api/sylive/goods';
  export default {
    components: {
      TinymceEditor,
      ActivityMchIdSelect,
      EleImageUpload
    },
    props: {
      // 弹窗是否打开
      visible: Boolean,
      // 全部机构
      organizationList: Array,
      // 修改回显的数据
      data: Object
    },
    data() {
      const defaultForm = {
        activityId: null,
        title: '',
        channelId: '',
        dateRange: '',
        shareTitle: [''],
        shareImg: [],
        bgImg: [],
        banner: [],
        sharePhoto: [],
        organizationId: null,
        drawCode: '',
        activityStart: '',
        mchId: '1604032585',
        protocolTitle: '',
        protocol: '',
        serviceLink: '',
        bottoms: [],
        blacklist: 0,
        button: { title: '' },
        signBespeak: { status: 0, title: '', content: '', itemId: 0 },
        barrage: { color: 0, title: '' }
      };
      return {
        goodsList: [],
        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'
            }
          ],
          organizationId: [
            {
              required: true,
              message: '请选择所属机构',
              trigger: 'blur'
            }
          ],
          activityStart: [
            {
              required: true,
              message: '请选择活动开始时间',
              trigger: 'blur'
            }
          ],
          bgImg: [
            {
              required: true,
              message: '请上传背景图',
              trigger: 'blur'
            }
          ],
          channelId: [
            {
              required: true,
              message: '请输入直播频道',
              trigger: 'blur'
            }
          ],
          dateRange: [
            {
              required: true,
              message: '请选择直播时间',
              trigger: 'blur'
            }
          ]
        },
        // 提交状态
        loading: false,
        // 是否是修改
        isUpdate: false
      };
    },
    computed: {
      // 是否开启响应式布局
      styleResponsive() {
        return this.$store.state.theme.styleResponsive;
      }
    },
    methods: {
      /* 查询商品 */
      goodsQuery() {
        if (!this.form.activityId) {
          return false;
        }
        listGoods({ activityId: this.form.activityId, price: 0 })
          .then((list) => {
            this.goodsList = list;
          })
          .catch((e) => {
            this.$message.error(e.message);
          });
      },
      /* 添加海报描述 */
      addShareTitle() {
        this.form.shareTitle.push('');
      },
      /* 保存编辑 */
      save() {
        this.$refs.form.validate((valid) => {
          if (!valid) {
            return false;
          }
          this.form.shareTitle.forEach((item, i) => {
            if (item == '') {
              this.form.shareTitle.splice(i, 1);
            }
          });
          this.loading = true;
          const data = {
            ...this.form
          };
          const saveOrUpdate = this.isUpdate ? updateActivity : addActivity;
          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);
      },
      /* 上传事件 */
      bgImgHandler(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.bgImg.push(item);
        this.onUpload(item);
      },
      payImgHandler(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.pay.img.push(item);
        this.onUpload(item);
      },
      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);
      },
      sharePhotoHandler(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.sharePhoto.push(item);
        this.onUpload(item);
      },
      shareImgHandler(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.shareImg.push(item);
        this.onUpload(item);
      },
      /* 添加 */
      addBottoms() {
        if (this.form.bottoms.length >= 2) {
          this.$message.error('最多添加2个活动底部菜单');
          return;
        }
        this.form.bottoms.push({
          urlType: 'link',
          title: '',
          url: '',
          miniProgramId: '',
          icon: []
        });
      },
      /* 删除 */
      removeBottoms(_row, index) {
        this.form.bottoms.splice(index, 1);
      },
      uploadHandler0(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.bottoms[0]['icon'].push(item);
        this.onUpload(item);
      },
      uploadHandler1(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.bottoms[1]['icon'].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) {
            this.$util.assignObject(this.form, {
              ...this.data
            });
            this.isUpdate = true;
            if (this.form.shareTitle.length == 0) {
              this.form.shareTitle.push('');
            }
            this.goodsQuery();
          } else {
            this.form.bottoms = [];
            this.form.bgImg = [];
            this.form.shareImg = [];
            this.isUpdate = false;
          }
        } else {
          this.$refs.form.clearValidate();
          this.form = { ...this.defaultForm };
        }
      }
    }
  };
</script>
<style>
  .ele-image-upload-list .ele-image-upload-item {
    margin-top: 2px;
    margin-bottom: 2px;
  }
</style>
