<template>
  <el-form size="small" :model="baseForm" :rules="rules" ref="form" 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" :picker-options="pickerOptions" value-format="yyyy-MM-dd" @change="refresh" 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.trim="baseForm.gameRule" show-word-limit :disabled="isDisabled" :autosize="{ minRows: 4 }" type="textarea" /> </el-form-item>
    </div>
    <dm-sub-title type="line">展示信息配置</dm-sub-title>
    <div class="mt20">
      <el-form-item label="游戏模板" prop="templateId">
        <el-radio v-for="item in templateData" v-model="baseForm.templateId" :label="item.templateId" :key="item.templateId">{{ item.templateName }}</el-radio>
      </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">图片建议尺寸{{ baseForm.backImageUrlSize0 }}，格式 jpg/png/gif，大小 {{ baseForm.backImageUrlSize1 }} 以内。</div>
      </el-form-item>
      <el-form-item label="抽奖样式">
        <div class="lottery">
          <div class="tips">图片建议尺寸 400*400px或等比图片，格式 jpg/png/gif，大小 1M 以内。</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')">
                      <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')">
                      <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">图片建议尺寸 {{ baseForm.noticeImageUrlSize0 }}，格式 jpg/png/gif，大小 {{ baseForm.noticeImageUrlSize1 }}以内。</div>
      </el-form-item>
      <el-form-item label="背景音乐">
        <el-switch v-model="baseForm.backMusicFlag" :active-value="1" :inactive-value="0" />
        <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.backMusicUrl" value-key="materialValue" @clear="handleClear" :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" />
        <div class="tips mt10">开启后，如有三名以上用户获奖后，活动首页将轮播展示用户中奖信息。</div>
      </el-form-item>
      <el-form-item label="广告位" prop="adsImageUrl">
        <el-switch v-model="baseForm.adsFlag" :active-value="1" :inactive-value="0" />
        <div class="adsImg" v-show="baseForm.adsFlag">
          <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" style="margin-bottom: 20px;">图片建议尺寸{{ baseForm.adsImageUrlSize0 }}或等比图片，格式 jpg/png/gif，大小{{ baseForm.adsImageUrlSize1 }} 以内。</div>
          <el-form-item label="小程序跳转路径" prop="link" label-width="110px">
            <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 :linkVisible.sync="selectLink.show" :linkData="selectLink.linkData" :can-save="true" :showType="0" @linkSelect="onSaveLink" />
        </div>
      </el-form-item>
    </div>
    <dm-form-bottom class="footer">
      <el-button type="primary">保存并下一步</el-button>
    </dm-form-bottom>
  </el-form>
</template>

<script>
import config from '@/config';
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() {
    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' }
      },
      baseForm: {
        gameName: '',
        gameTime: [],
        gameRule: '1、幸运盲盒大抽奖，惊喜好礼抽不停。</br>2、活动最终解释权归品牌方所有。',
        templateId: '',
        backMusicFlag: 1,
        adsFlag: 1,
        bulletFlag: 1,
        backMusicUrl: ''
      },
      adsImageUrl: { imgUrl: '', code: '' },
      isPlay: false,
      backMusicOptions: [],
      customMusicOptions: [],
      isDisabled: false,
      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: {}
      }
    };
  },
  props: {
    templateArr: {
      type: Array,
      default: () => []
    }
  },
  components: {
    dmUploadAvatar,
    dmUploadImg,
    audioUpload,
    Linktools
  },
  computed: {
    backMusicOptionsComputed() {
      if (this.customMusicOptions.length) {
        return this.customMusicOptions;
      } else {
        return this.backMusicOptions;
      }
    }
  },
  watch: {
    templateArr(val) {
      console.log(val);
      this.templateData = val;
      if (val && val.length) {
        const data = val[0];
        this.baseForm.templateId = data.templateId;
        this.handleTemplateArr(data);
      }
    }
  },
  methods: {
    beforeAvatarUpload(file, key, size1 = 1) {
      console.log(file);
      console.log(size1);
      const arr = ['image/gif', 'image/jpeg', 'image/png'];
      const limit = file.size / 1024 / 1024 < 2;
      if (!arr.includes(file.type)) {
        this.$message.warning('只能上传jpg/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);
            console.log(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) {
      Object.keys(data.materialMap).forEach(key => {
        if (key.indexOf('Image') > -1) {
          let obj = data.materialMap[key][0];
          this.baseForm[key] = obj.materialValue;
          if (obj.materialSize) {
            this.baseForm[key + 'Size0'] = JSON.parse(obj.materialSize).width + '*' + JSON.parse(obj.materialSize).height + 'px';
            this.baseForm[key + 'Size1'] = JSON.parse(obj.materialSize).size + 'M';
          }
        } else {
          this.backMusicOptions = data.materialMap['backMusicUrl'];
          if (data.materialMap['backMusicUrl'] && data.materialMap['backMusicUrl'].length) {
            this.baseForm.backMusicUrl = data.materialMap['backMusicUrl'][0];
          }
          const prizeStyle = data.materialMap['prizeStyleJson'][0];
          this.prizeStyleJson = JSON.parse(prizeStyle.materialValue);
          this.baseForm['prizeStyleJson'] = JSON.parse(prizeStyle.materialValue);
        }
      });
      console.log(this.baseForm);
    },
    handleListen() {
      this.isPlay = !this.isPlay;
      console.log(this.isPlay);
      this.backMusicOptions.forEach(item => {
        if (item.materialValue == this.baseForm.backMusicUrl.materialValue) {
          music.src = this.baseForm.backMusicUrl.materialValue;
          console.log(this.baseForm.backMusicUrl.materialValue);
          this.isPlay ? music.play() : music.pause();
        }
      });
    },
    handleClear() {
      this.customMusicOptions = [];
      this.baseForm.backMusicUrl = this.backMusicOptions[0];
    },
    setAudioList(obj) {
      console.log(obj);
      const { name, url } = obj;
      this.customMusicOptions = [
        {
          materialName: name,
          materialValue: url,
          customFlag: 1,
          materialKey: 'backMusicUrl'
        }
      ];
      this.baseForm.backMusicUrl = this.customMusicOptions[0];
    },
    handleAdsChange(obj) {
      console.log(obj);
      this.baseForm.adsImageUrl = obj.imgUrl;
      this.$emit('change', this.baseForm);
    },
    replace(type, index) {
      this.baseForm.prizeStyleJson[index][type] = this.prizeStyleJson[index][type];
      this.baseForm = Object.assign({}, this.baseForm);
      this.$emit('change', this.baseForm);
    },
    // 保存链接小工具返回的链接数据
    onSaveLink(linkData) {
      console.log(linkData);
      this.selectLink.linkData = linkData;
    },
    handleNameChange(val) {
      console.log(val);
      this.$emit('change', this.baseForm);
    }
  }
};
</script>

<style lang="scss" scoped>
img {
  object-fit: fill;
}
.lottery {
  width: 600px;
  height: 250px;
  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;
}
.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;
}
.wxapp {
  width: 253px;
  height: 32px;
  background: #f2f3f5;
  border-radius: 2px;
  border: 1px solid #dcdfe6;
  padding: 0 11px;
  box-sizing: border-box;
  display: inline-flex;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.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;
}
</style>
