<template>
  <el-form size="small" :model="baseForm" :rules="rules" ref="baseForm" label-width="80px">
    <dm-sub-title type="line">基本信息</dm-sub-title>
    <div class="mt20">
      <el-form-item label="游戏名称" prop="gameName"> <el-input maxlength="10" class="w382" @change="handleNameChange" v-model.trim="baseForm.gameName" show-word-limit :disabled="isDisabled" placeholder="请输入游戏名称" /> </el-form-item>
      <el-form-item label="游戏时间" prop="gameTime"><el-date-picker class="w382" v-model="baseForm.gameTime" :disabled="isDisabled" :picker-options="pickerOptions" value-format="timestamp" @change="handleDateChange(val, 'gameTime')" type="daterange" range-separator="~" start-placeholder="开始日期" end-placeholder="结束日期"> </el-date-picker></el-form-item>
      <el-form-item label="游戏说明" prop="gameRule"> <el-input maxlength="500" class="w382" v-model="baseForm.gameRule" show-word-limit :autosize="{ minRows: 4 }" type="textarea" /> </el-form-item>
    </div>
    <dm-sub-title type="line">展示信息配置</dm-sub-title>
    <div class="mt20" style="margin-bottom: 32px">
      <el-form-item label="游戏模板" prop="templateId">
        <el-radio-group @change="handleTemplateChange" v-model="baseForm.templateId" :disabled="isDisabled" class="radioGroup">
          <el-radio v-for="item in templateData" :label="item.templateId" :key="item.templateId">{{ item.templateName }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="游戏背景" prop="backImageUrl">
        <div class="flex">
          <img :src="baseForm.backImageUrl" alt="游戏背景" style="width: 100px;height: 193px;" />
          <el-upload class="avatar-uploader" action="123" :show-file-list="false" :before-upload="file => beforeAvatarUpload(file, 'backImageUrl', baseForm.backImageUrlSize1)">
            <el-button type="text" class="ml16">替换图片</el-button>
          </el-upload>
        </div>

        <div class="tips mt6">图片建议尺寸{{ baseForm.backImageUrlSize0 }}，格式 jpg/jpeg/png/gif，大小 {{ baseForm.backImageUrlSize1 }} M以内。</div>
      </el-form-item>
      <el-form-item label="抽奖样式">
        <div class="lottery">
          <div class="tips">图片建议尺寸{{ baseForm.prizeStyleJsonSize0 }}或等比图片，格式 jpg/jpeg/png/gif，大小 {{ baseForm.prizeStyleJsonSize1 }}M 以内。</div>
          <div v-for="item in baseForm.prizeStyleJson" :key="item.index">
            <div class="imgContent">
              <div class="imageOrigin">
                <p>未选中效果</p>
                <div style="display: flex;">
                  <img :src="item.imageNoSelectUrl" alt="未选中效果" style="width: 120px;height: 120px;" />
                  <div class="imgBtn">
                    <el-upload class="avatar-uploader" action="123" :show-file-list="false" :before-upload="file => beforeAvatarUpload(file, 'imageNoSelectUrl', baseForm.prizeStyleJsonSize1)">
                      <el-button type="text">替换</el-button>
                    </el-upload>
                    <el-button type="text" @click="replace('imageNoSelectUrl', item.index)">重置</el-button>
                  </div>
                </div>
              </div>
              <div class="imageSelect">
                <p>选中效果</p>
                <div style="display: flex;">
                  <img :src="item.imageSelectUrl" alt="选中效果" style="width: 120px;height: 120px;" />
                  <div class="imgBtn">
                    <el-upload class="avatar-uploader" action="123" :show-file-list="false" :before-upload="file => beforeAvatarUpload(file, 'imageSelectUrl', baseForm.prizeStyleJsonSize1)">
                      <el-button type="text">替换</el-button>
                    </el-upload>
                    <el-button type="text" @click="replace('imageSelectUrl', item.index)">重置</el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="提示样式" prop="noticeImageUrl">
        <div class="flex">
          <img :src="baseForm.noticeImageUrl" alt="提示样式" class="imgBox" />
          <el-upload class="avatar-uploader" action="123" :show-file-list="false" :before-upload="file => beforeAvatarUpload(file, 'noticeImageUrl', baseForm.noticeImageUrlSize1)">
            <el-button type="text" class="ml16">替换图片</el-button>
          </el-upload>
        </div>
        <div class="tips mt6">图片建议尺寸 {{ baseForm.noticeImageUrlSize0 }}，格式 jpg/jpeg/png/gif，大小 {{ baseForm.noticeImageUrlSize1 }}M以内。</div>
      </el-form-item>
      <el-form-item label="背景音乐">
        <el-switch v-model="baseForm.backMusicFlag" :active-value="1" :inactive-value="0" @change="handleDateChange" />
        <div class="flex mt16" v-show="baseForm.backMusicFlag">
          <div class="flex">
            <el-button size="small" class="playBtn" @click="handleListen"><i :class="['iconfont fz14', isPlay ? 'icon-zanting' : 'icon-kaiqi']"></i> 点击试听</el-button>
            <el-select class="musicSelect" v-model="baseForm.backMusicUrlObj" value-key="materialValue" @clear="handleClear" @change="handleChange" :clearable="customMusicOptions.length">
              <el-option v-for="item in backMusicOptionsComputed" :key="item.materialValue" :value="item" :label="item.materialName"> </el-option>
            </el-select>
          </div>
          <audio-upload tips="" @sendAduioList="setAudioList" :textType="true" label="替换音乐" class="ml16"></audio-upload>
        </div>
      </el-form-item>
      <el-form-item label="氛围弹幕">
        <el-switch v-model="baseForm.bulletFlag" :active-value="1" :inactive-value="0" @change="handleDateChange" />
        <div class="tips mt10">开启后，如有三名及以上用户获奖后，活动首页将轮播展示用户中奖信息。</div>
      </el-form-item>
      <el-form-item label="广告位">
        <el-switch v-model="baseForm.adsFlag" :active-value="1" :inactive-value="0" @change="handleDateChange(val, 'adsFlag')" />
        <div class="adsImg" v-show="baseForm.adsFlag">
          <el-form-item prop="adsImageUrl" :rules="rules.adsImageUrl" label-width="0">
            <dm-upload-avatar class="upload-avatar" width="375" height="75" :limit="{ type: false, maxSize: 1 }" fileType="img" :model.sync="adsImageUrl" label="上传图片" tips="" @backImg="handleAdsChange" :unused="isInfo"></dm-upload-avatar>
            <div class="tips">图片建议尺寸750*150px或等比图片，格式 jpg/jpeg/png/gif，大小1 M以内。</div>
          </el-form-item>
          <el-form-item label="小程序跳转路径" prop="link" label-width="110px" :rules="rules.link">
            <div class="wxapp mr16" v-if="selectLink.linkData.name">
              {{ selectLink.linkData.name }}
            </div>
            <el-button type="text" @click="selectLink.show = true"> 选择链接 </el-button>
          </el-form-item>
          <linktools :remove="[5, 35]" :linkVisible.sync="selectLink.show" :linkData="selectLink.linkData" :can-save="true" @linkSelect="onSaveLink" />
        </div>
      </el-form-item>
    </div>
    <dm-form-bottom class="footer">
      <el-button type="primary" @click="nextStep()">保存并下一步</el-button>
    </dm-form-bottom>
  </el-form>
</template>

<script>
import config from '@/config';
import { getPageLink } from '@/service/api/gameApi.js';
import dmUploadAvatar from '@/components/upload/avatar';
import dmUploadImg from '@/components/upload/img';
import Linktools from '@/components/linktools-fulls/index.vue';
import audioUpload from '../common/audio-upload.vue';
const maxTimeRange = 180 * 24 * 60 * 60 * 1000; // 6个月
const music = new Audio();

export default {
  data() {
    const adsImageUrlVal = (rule, value, callback) => {
      if (this.baseForm.adsFlag == 1 && !this.baseForm.adsImageUrl) {
        callback(new Error('请上传广告位图片'));
      } else {
        callback();
      }
    };
    const linkVal = (rule, value, callback) => {
      if (this.baseForm.adsFlag == 1 && !this.baseForm.adsLinkUrl) {
        callback(new Error('请选择链接'));
      } else {
        callback();
      }
    };
    return {
      rules: {
        gameName: { type: 'string', required: true, message: '游戏名称未填写', trigger: 'blur' },
        gameTime: { type: 'array', required: true, message: '未配置游戏时间', trigger: 'blur' },
        gameRule: { type: 'string', required: true, message: '未配置游戏说明', trigger: 'blur' },
        adsImageUrl: { validator: adsImageUrlVal },
        link: { validator: linkVal }
      },
      baseForm: {
        gameName: '',
        gameTime: [],
        gameRule: '1、幸运盲盒大抽奖，惊喜好礼抽不停。\n2、活动最终解释权归品牌方所有。',
        templateId: '',
        backMusicFlag: 0,
        adsFlag: 0,
        bulletFlag: 0,
        backMusicUrlObj: ''
        // addMomentsCard: false
      },
      gameExt: {},
      adsImageUrl: { imgUrl: '', code: '' },
      isPlay: false,
      backMusicOptions: [],
      customMusicOptions: [],

      templateData: [],
      api: config.api,
      prizeStyleJson: [], // 抽奖样式
      pickerOptions: {
        onPick(time) {
          //  查询最大时间跨度为6个月 && 结束时间只能选到当天
        },
        disabledDate: time => {
          return time.getTime() < new Date(new Date().toLocaleDateString()).getTime() || time.getTime() > new Date().getTime() + maxTimeRange;
        }
      },
      // 链接小工具选择链接
      selectLink: {
        show: false,
        linkData: {}
      },
      isAdd: this.$route.meta.type === 'add',
      isCopy: this.$route.meta.type === 'copy',
      isEdit: this.$route.meta.type === 'edit'
    };
  },
  props: {
    gameStatus: 0,
    templateArr: {
      type: Array,
      default: () => []
    },
    echoData: {
      type: Object,
      default: () => {}
    }
  },
  mounted() {
    music.addEventListener('ended', () => {
      music.currentTime = 0;
      this.isPlay = false;
    });
  },
  components: {
    dmUploadAvatar,
    dmUploadImg,
    audioUpload,
    Linktools
  },
  computed: {
    backMusicOptionsComputed() {
      if (this.customMusicOptions.length) {
        return this.customMusicOptions;
      } else {
        return this.backMusicOptions;
      }
    },
    isDisabled() {
      return this.gameStatus == 1;
    }
  },
  watch: {
    templateArr(val) {
      if (this.isAdd || this.isCopy) {
        this.templateData = val.filter(item => item.statusFlag == 1);
        const data = this.templateData[0];
        this.baseForm.templateId = data.templateId;
        this.handleTemplateArr(data.gameTemplateMaterialList);
        this.$emit('change', this.baseForm);
      }
    },
    echoData(val) {
      let { gameExt } = val;
      let initTemp = false;
      this.baseForm = Object.assign(this.baseForm, val);
      if (this.baseForm.adsFlag) {
        this.adsImageUrl = { imgUrl: gameExt.adsImageUrl && gameExt.adsImageUrl.materialValue, code: gameExt.adsImageUrl && gameExt.adsImageUrl.materialValue };
      }
      let currentTemp = this.templateArr.filter(item => item.templateId == this.baseForm.templateId)[0];
      if (this.isEdit) {
        this.templateData = this.templateArr.filter(item => item.statusFlag == 1 || item.templateId == this.baseForm.templateId);
      }
      if (this.isCopy && currentTemp.statusFlag == 0) {
        currentTemp = this.templateArr.filter(item => item.statusFlag == 1)[0];
        this.baseForm.templateId = currentTemp.templateId;
        initTemp = true;
        this.$message.info('原游戏模板已失效,已重置默认模板');
      }
      let obj = {};
      let arr = ['noticeImageUrl', 'shareCard', 'shareReport', 'momentsCard', 'prizeStyleJson', 'backImageUrl'];
      let keys = Object.keys(gameExt);

      currentTemp.gameTemplateMaterialList.forEach(item => {
        if (item.materialKey == 'backMusicUrl') {
          this.backMusicOptions.push(item);
        } else if (!keys.includes(item.materialKey)) {
          obj[item.materialKey] = item;
          // if (item.materialKey == 'momentsCard') {
          //   this.baseForm.addMomentsCard = true;
          // }
        }
      });
      if (initTemp) {
        let currentTempObj = {};
        currentTemp.gameTemplateMaterialList.forEach(item => {
          currentTempObj[item.materialKey] = item;
        });
        keys.forEach(key => {
          if (arr.includes(key)) {
            gameExt[key] = currentTempObj[key];
          }
        });
      }
      obj = Object.assign(obj, gameExt); // 详情的素材库与模板接口的默认有值的素材库取交集
      this.handleTemplateArr(Object.values(obj), 'echo');
      this.selectLink.linkData = this.baseForm.mpUrlView ? JSON.parse(this.baseForm.mpUrlView) : {};
      if (this.isCopy) {
        this.baseForm.gameTime = [];
      }
      this.$emit('change', this.baseForm);
    }
  },
  methods: {
    handleDateChange(val, type) {
      this.$emit('change', this.baseForm);
      if (type == 'adsFlag') {
        this.$nextTick(_ => {
          const formContent = document.getElementById('formContent');

          formContent.scrollTop = formContent.scrollHeight + 500;
          // adsImg[0].scrollIntoView({
          //   // 滚动到指定节点
          //   // 值有start,center,end，nearest，当前显示在视图区域中间
          //   block: 'center',
          //   // 值有auto、instant,smooth，缓动动画（当前是慢速的）
          //   behavior: 'smooth'
          // });
        });
      } else if (type == 'gameTime' && this.baseForm.gameTime && this.baseForm.gameTime.length) {
        this.baseForm.gameTime[1] = this.baseForm.gameTime[1] + 86399000;
      }
    },
    handleTemplateChange(val) {
      this.baseForm.templateId = val;
      const data = this.templateArr.filter(item => item.templateId == val)[0].gameTemplateMaterialList;
      this.customMusicOptions = [];
      this.backMusicOptions = [];
      this.handleTemplateArr(data, 'tempChange');
      this.$emit('change', this.baseForm);
    },
    beforeAvatarUpload(file, key, size1 = 1) {
      const arr = ['image/gif', 'image/jpeg', 'image/png'];
      const limit = file.size / 1024 / 1024 < size1;
      if (!arr.includes(file.type)) {
        this.$message.warning('只能上传jpg/jpeg/png/gif格式文件!');
        return false;
      }
      if (!limit) {
        this.$message.warning(`上传图片大小不能超过 ${size1}MB!`);
        return;
      }
      let fd = new FormData();
      fd.append('file', file);
      fd.append('requestProject', 'gic-web');
      this.axios
        .post('/api-marketing/upload-game-image', fd)
        .then(res => {
          //成功后回调
          let data = res.data;
          if (data.errorCode == 0) {
            if (key == 'imageNoSelectUrl' || key == 'imageSelectUrl') {
              this.baseForm['prizeStyleJson'][0][key] = data.result.qcloudImageUrl;
            } else {
              this.baseForm[key] = data.result.qcloudImageUrl;
            }
            this.baseForm = Object.assign({}, this.baseForm);
            this.$message({
              type: 'success',
              message: '上传成功'
            });
            this.$emit('change', this.baseForm);
          }
        })
        .catch(error => {
          this.$message({
            type: 'error',
            message: error.message
          });
        });
      return true;
    },
    handleTemplateArr(data, type) {
      this.gameExt = data;
      const materialKeys = ['mpUrlView', 'adsLinkUrl', 'adsImageUrl']; // 模板切换时 保留广告位
      data.forEach(item => {
        if (item.materialKey == 'prizeStyleJson') {
          this.prizeStyleJson = JSON.parse(item.materialValue);
          this.baseForm['prizeStyleJson'] = JSON.parse(item.materialValue);
        } else {
          if (type == 'tempChange') {
            if (!materialKeys.includes(item.materialKey)) {
              this.baseForm[item.materialKey] = item.materialValue;
            }
          } else {
            this.baseForm[item.materialKey] = item.materialValue;
          }
        }
        if (item.materialSize) {
          const { width, height, size } = JSON.parse(item.materialSize);
          this.baseForm[item.materialKey + 'Size0'] = width + '*' + height + 'px';
          this.baseForm[item.materialKey + 'Size1'] = size;
        }
        if (item.materialKey == 'backMusicUrl') {
          if (type == 'echo') {
            if (item.customFlag == 1) {
              this.customMusicOptions.push(item);
              this.baseForm.backMusicUrlObj = item;
            } else {
              this.baseForm.backMusicUrlObj = item;
            }
          } else {
            this.backMusicOptions.push(item);
            this.baseForm.backMusicUrlObj = this.backMusicOptions[0];
          }
        }
      });
      console.log(this.baseForm);
    },
    handleListen() {
      this.isPlay = !this.isPlay;
      this.backMusicOptionsComputed.forEach(item => {
        if (item.materialValue == this.baseForm.backMusicUrlObj.materialValue) {
          music.src = this.baseForm.backMusicUrlObj.materialValue;
          this.isPlay ? music.play() : music.pause();
        }
      });
    },
    handleClear() {
      if (this.isPlay) {
        this.isPlay = !this.isPlay;
        music.pause();
      }
      this.customMusicOptions = [];
      this.baseForm.backMusicUrlObj = this.backMusicOptions[0];
    },
    handleChange() {
      if (this.isPlay) {
        this.isPlay = !this.isPlay;
        music.pause();
      }
    },
    setAudioList(obj) {
      const { name, url } = obj;
      this.customMusicOptions = [
        {
          materialName: name,
          materialValue: url,
          customFlag: 1,
          materialKey: 'backMusicUrl'
        }
      ];
      if (this.isPlay) {
        this.isPlay = !this.isPlay;
        music.pause();
      }
      this.baseForm.backMusicUrlObj = this.customMusicOptions[0];
    },
    handleAdsChange(obj) {
      this.baseForm.adsImageUrl = obj.imgUrl;
      this.$refs.baseForm.validateField('adsImageUrl');
      this.$emit('change', this.baseForm);
    },
    replace(type, index) {
      const currentTemp = this.templateData.filter(item => item.templateId == this.baseForm.templateId)[0];
      let prizeStyleJson = currentTemp.gameTemplateMaterialList.filter(item => item.materialKey == 'prizeStyleJson')[0];
      prizeStyleJson = prizeStyleJson ? JSON.parse(prizeStyleJson.materialValue) : [];
      this.baseForm.prizeStyleJson[index][type] = prizeStyleJson[index][type];
      this.baseForm = Object.assign({}, this.baseForm);
      this.$emit('change', this.baseForm);
    },
    // 保存链接小工具返回的链接数据
    onSaveLink(linkData) {
      getPageLink({ requestProject: 'gic-web', pageLink: linkData }).then(res => {
        const { link } = res.result;
        this.selectLink.linkData = linkData;
        this.baseForm.mpUrlView = JSON.stringify(linkData);
        this.baseForm.adsLinkUrl = link;
        this.$refs.baseForm.validateField('link');
      });
    },
    handleNameChange(val) {
      this.$emit('change', this.baseForm);
    },
    nextStep(noNext) {
      return new Promise(resolve => {
        this.$refs.baseForm.validate(val => {
          if (val) {
            const data = { ...this.baseForm };
            let gameExt = {};
            this.gameExt.forEach(item => {
              gameExt[item.materialKey] = item;
            });
            Object.keys(data).forEach(key => {
              if (gameExt[key]) {
                gameExt[key].materialValue = data[key];
              }
            });

            gameExt.backMusicUrl = data.backMusicUrlObj;
            gameExt.prizeStyleJson.materialValue = JSON.stringify(gameExt.prizeStyleJson.materialValue);
            if (!data.adsFlag) {
              delete gameExt.adsImageUrl;
              delete gameExt.adsLinkUrl;
              delete gameExt.mpUrlView;
            }
            data.gameExt = gameExt;
            resolve(true);
            this.$emit('nextStep', data, noNext);
          } else {
            resolve(false);
            this.scrollToError(this);
          }
        });
      });
    }
  },
  destroyed() {
    if (this.isPlay) {
      this.isPlay = false;
      music.pause();
    }
  }
};
</script>

<style lang="scss" scoped>
img {
  object-fit: fill;
}
.lottery {
  width: 600px;
  background: #ffffff;
  border: 1px solid #dcdfe6;
  padding: 14px 20px;
  .imgContent {
    display: flex;
    margin-top: 15px;
    .imageOrigin,
    .imageSelect {
      width: 204px;
      height: 184px;
      background: #f7f8fa;
      padding: 10px 20px 20px 20px;
      box-sizing: border-box;
      p {
        line-height: 20px;
      }
      img {
        margin-top: 14px;
      }
    }
    .imageSelect {
      margin-left: 20px;
    }
  }
}
.playBtn {
  width: 100px;
  border-radius: 2px 0px 0px 2px;
  box-sizing: border-box;
  border-right: none;
  color: #2f54eb;
}
.musicSelect {
  width: 380px;
  /deep/ input {
    border-radius: 0px 2px 2px 0px;
  }
}

.imgBox {
  width: 250px;
  height: 50px;
  background: #ffffff;
  border-radius: 2px;
  border: 1px solid #dcdfe6;
  object-fit: contain;
}
.imgBtn {
  display: flex;
  flex-direction: column;
  margin: 14px 0 0 16px;
  button:last-child {
    margin: 8px 0 0 0;
    color: #606266;
  }
}
.adsImg {
  width: 600px;
  height: 187px;
  background: #f7f8fa;
  padding: 16px 20px;
  box-sizing: border-box;
  margin-top: 16px;
}

.upload-avatar {
  width: 375px;
  height: 75px;
  background: #fff;
  margin-bottom: 10px;
  /deep/.dm-avatar__upload {
    background: #fff;
  }
  .dm-avatar__upload {
    background: #fff;
  }
}
/deep/.dm-avatar__upload {
  background: #fff;
}
.dm-avatar__upload {
  background: #fff;
}
.footer {
  width: calc(100% - 520px) !important;
}
.radioGroup {
  .el-radio + .el-radio {
    margin-left: 0;
  }
}
</style>
