<template>
  <el-form size="small" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="134px">
    <dm-sub-title type="line" class="mb20">玩法配置</dm-sub-title>
    <el-form-item label="参与人群" prop="filterJson">
      <el-radio-group v-model="ruleForm.memberType" :disabled="isDisabled" @change="clearValidate('filterJson')">
        <el-radio :label="0">客户筛选</el-radio>
        <el-radio :label="1">客户分组</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item>
      <div v-show="ruleForm.memberType == 0" style="min-width:1000px">
        <vue-gic-people v-bind="storeParams" projectName="marketing" :triggerReset="true" :isAdd="isAdd" :hasSearchData="ruleForm.hasSearchData" :useId="ruleForm.memberWeightView.searchId" sceneValue="member" ref="peopleFilter" @findFilter="findFilter" @getBackData="getBackData" @editShow="toggleTag = true" @editHide="toggleTag = false" @hideBtn="toggleTag = false" />
        <div class="gic-people--button" v-show="toggleTag">
          <el-button size="small" type="primary" @click="getData" :disabled="isDisabled">确 定</el-button>
          <el-button size="small" @click="cancelFilter">取 消</el-button>
        </div>
      </div>

      <div v-show="ruleForm.memberType == 1">
        <el-button v-if="!selectedGroupIds" size="small" @click="groupVisible = true">添加分组</el-button>
        <gic-new-member-group :visiable.sync="groupVisible" :onlyRead="isDisabled" :selectedIds="selectedGroupIds" @change="confirmGroupDialog" />
      </div>
    </el-form-item>

    <el-form-item label="适用人群说明" prop="memberDesc">
      <el-input maxlength="100" type="textarea" class="w382" placeholder="请输入适用人群说明" v-model="ruleForm.memberDesc" show-word-limit :autosize="{ minRows: 5 }" />
    </el-form-item>
    <el-form-item label="参与门槛" prop="playConditionFlag" style="margin-bottom: 12px;">
      <el-radio-group v-model="ruleForm.playConditionFlag" :disabled="isDisabled">
        <el-radio :label="1">有门槛</el-radio>
        <el-radio :label="0">无门槛</el-radio>
      </el-radio-group>
      <div class="tips mt6">支持单选或多选参与门槛</div>
    </el-form-item>
    <el-form-item>
      <div class="shareBox" v-show="ruleForm.playConditionFlag == 1">
        <div v-for="(item, index) in ruleForm.gameRuleConditionList" :key="item.conditionType">
          <div v-if="index == 0">
            <div class="flex mb10"><el-checkbox v-model="item.conditionType" :true-label="2" :false-label="-1" :disabled="isDisabled" /> <span class="ml10">赠与免费游戏次数</span></div>
            <div class="flex" v-show="item.conditionType == 2">
              <el-select class="w140" v-model="item.conditionJson.type" :disabled="isDisabled">
                <el-option :value="22" label="总赠送"></el-option>
                <el-option :value="21" label="每日赠送"></el-option>
              </el-select>
              <el-form-item :prop="'gameRuleConditionList.' + index + '.conditionJson.' + 'value'" :rules="{ required: true, message: '请输入次数' }">
                <el-input-number class="w140" :disabled="isDisabled" placeholder="请输入次数" v-model="item.conditionJson.value" :min="1" :max="1000000" controls-position="right" />
              </el-form-item>
              <span class="ml10">次游戏次数</span>
            </div>
          </div>
          <div v-if="index == 1">
            <div class="flex mb10"><el-checkbox v-model="item.conditionType" :true-label="0" :false-label="-1" :disabled="isDisabled" @change="$emit('change', { val: item.conditionJson.value, type: item.conditionType, id: 0 })" /> <span class="ml10">消耗积分获得游戏次数</span></div>
            <div v-show="item.conditionType == 0">
              <el-form-item label="参与游戏每次消耗积分" label-width="170px" :prop="'gameRuleConditionList.' + index + '.conditionJson.' + 'value'" :rules="{ required: true, message: '请输入积分' }">
                <el-input-number class="w140" :disabled="isDisabled" placeholder="请输入积分" v-model="item.conditionJson.value" :min="1" :max="1000000" controls-position="right" @change="$emit('change', { val: item.conditionJson.value, type: item.conditionType, id: 0 })" />
                <span class="ml10">积分 </span>
              </el-form-item>
              <el-form-item label="提示客户积分获取路径" label-width="170px" :prop="'gameRuleConditionList.' + index + '.conditionJson.' + 'mpUrlView'" :rules="rules.mpUrlView">
                <div class="wxapp mr16" v-if="item.conditionJson.mpUrlView && item.conditionJson.mpUrlView.name">
                  {{ item.conditionJson.mpUrlView.name }}
                </div>
                <el-button type="text" :disabled="isDisabled" @click="show = true"> 选择链接 </el-button>
              </el-form-item>
            </div>
          </div>
          <div v-if="index == 2">
            <div class="flex mb10"><el-checkbox @change="$emit('change', { val: item.conditionJson.value, type: item.conditionType, id: 1 })" v-model="item.conditionType" :true-label="1" :false-label="-1" :disabled="isDisabled" /><span class="ml10"> 邀请好友助力获得游戏次数</span></div>
            <div v-show="item.conditionType == 1">
              <el-form-item label="邀请机制" label-width="80px" style="margin-bottom:0;">
                <div class="flex">
                  每成功邀请
                  <el-form-item label-width="0" :prop="'gameRuleConditionList.' + index + '.conditionJson.' + 'inviteNum'" :rules="{ required: true, message: '请输入' }"> <el-input-number v-model="item.conditionJson.inviteNum" :min="1" :max="1000000" class="w110 ml10 mr10" controls-position="right" :disabled="isDisabled" />人可获得 </el-form-item>
                  <el-form-item label-width="0" :prop="'gameRuleConditionList.' + index + '.conditionJson.' + 'value'" :rules="{ required: true, message: '请输入' }"> <el-input-number v-model="item.conditionJson.value" :min="1" :max="1000000" class="w110 ml10 mr10" controls-position="right" :disabled="isDisabled" />次游戏 </el-form-item>
                </div>
              </el-form-item>

              <el-form-item label="成功邀请条件" label-width="108px">
                <el-radio-group v-model="item.conditionJson.type" :disabled="isDisabled">
                  <el-radio :label="11">注册新会员</el-radio>
                  <el-radio :label="12">首次关注服务号</el-radio>
                </el-radio-group>
              </el-form-item>
              <div v-show="item.conditionJson.type == 12">
                <el-form-item label="关注回复" :prop="'gameRuleConditionList.' + index + '.conditionJson.' + 'subscribeMsg'" label-width="80px" :rules="rules.subscribeMsg"> <el-input maxlength="20" :disabled="isDisabled" show-word-limit v-model="item.conditionJson.subscribeMsg" /> </el-form-item>
              </div>
              <div>
                <div class="mini-sub-title">
                  <div class="line"></div>
                  <div class="text">
                    <div class="space-between">
                      邀请分享样式
                    </div>
                  </div>
                </div>
                <el-form-item label="小程序卡片标题" label-width="122px" :prop="'gameRuleConditionList.' + index + '.conditionJson.' + 'shareTitle'" :rules="rules.shareTitle"> <el-input class="w340" maxlength="24" show-word-limit v-model="item.conditionJson.shareTitle" :disabled="isDisabled" /> </el-form-item>
                <el-form-item label="小程序卡片图片" label-width="122px">
                  <div class="flex">
                    <img :src="item.conditionJson.shareCard" alt="游戏背景" style="width: 100px;height: 75px;" />
                    <el-upload class="avatar-uploader" action="123" :show-file-list="false" :disabled="isDisabled" :before-upload="file => beforeAvatarUpload(file, 'shareCard', shareCardSize1)">
                      <el-button type="text" class="ml16" :disabled="isDisabled">替换图片</el-button>
                    </el-upload>
                  </div>

                  <div class="tips mt6">图片建议尺寸{{ shareCardSize0 }}，格式 jpg/jpeg/png，大小 {{ shareCardSize1 }} M以内。</div>
                </el-form-item>
                <el-form-item label="分享朋友圈" label-width="122px">
                  <div class="flex">
                    <img :src="item.conditionJson.momentsCard" alt="游戏背景" style="width: 100px;height: 178px;" />
                    <el-upload class="avatar-uploader" action="123" :show-file-list="false" :disabled="isDisabled" :before-upload="file => beforeAvatarUpload(file, 'momentsCard', momentsCardSize1)">
                      <el-button type="text" class="ml16" :disabled="isDisabled">替换图片</el-button>
                    </el-upload>
                  </div>

                  <div class="tips mt6">图片建议尺寸{{ momentsCardSize0 }}，格式 jpg/jpeg/png，大小 {{ momentsCardSize1 }} M以内。</div>
                </el-form-item>
                <el-form-item label="分享海报" label-width="122px">
                  <div class="flex">
                    <img :src="item.conditionJson.shareReport" alt="游戏背景" style="width: 100px;height: 178px;" />
                    <el-upload class="avatar-uploader" action="123" :show-file-list="false" :disabled="isDisabled" :before-upload="file => beforeAvatarUpload(file, 'shareReport', shareReportSize1)">
                      <el-button type="text" class="ml16" :disabled="isDisabled">替换图片</el-button>
                    </el-upload>
                    <el-button type="text" class="ml16 downloadBtn" @click="downloadTmp">下载模板</el-button>
                  </div>
                  <div class="tips mt6">图片建议尺寸{{ shareReportSize0 }}，格式 jpg/jpeg/png，大小 {{ shareReportSize1 }} M以内。</div>
                </el-form-item>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-form-item>
    <el-form-item label="每人最多可玩次数" prop="playTimes" :rules="rules.playTimes"> <el-input v-model.number="ruleForm.playTimes" class="w140" placeholder="上限1000" :disabled="isDisabled" />次游戏次数 </el-form-item>
    <!-- <el-form-item label="分享" prop="shareFlag">
      <el-switch v-model="ruleForm.shareFlag" :active-value="1" :inactive-value="0" />
      <div class="tips mt6">关闭后用户无法分享小程序</div>
    </el-form-item> -->
    <linktools :linkVisible.sync="show" :remove="[5, 35]" :linkData="ruleForm.gameRuleConditionList[1].conditionJson.mpUrlView" :can-save="true" @linkSelect="onSaveLink" />
    <dm-form-bottom class="footer">
      <el-button @click="prevStep">上一步</el-button>
      <el-button type="primary" @click="submit" :loading="btnLoading">发布并预览</el-button>
    </dm-form-bottom>
  </el-form>
</template>

<script>
import { getPageLink } from '@/service/api/gameApi.js';
import Linktools from '@/components/linktools-fulls/index.vue';
export default {
  data() {
    const filterJsonVal = (rule, value, callback) => {
      if (this.ruleForm.memberType == 1 && !this.selectedGroupIds) {
        callback(new Error('客户分组不能为空'));
        return;
      }
      callback();
    };
    const mpUrlViewVal = (rule, value, callback) => {
      if (this.ruleForm.playConditionFlag == 1 && this.ruleForm.gameRuleConditionList[1].conditionType != -1 && !this.ruleForm.gameRuleConditionList[1].conditionJson.dumpPath) {
        callback(new Error('请选择'));
        return;
      }
      callback();
    };
    const shareTitleVal = (rule, value, callback) => {
      if (this.ruleForm.playConditionFlag == 1 && this.ruleForm.gameRuleConditionList[2].conditionType != -1 && this.ruleForm.gameRuleConditionList[2].conditionJson.type == 11 && !this.ruleForm.gameRuleConditionList[2].conditionJson.shareTitle) {
        callback(new Error('请输入'));
        return;
      }
      callback();
    };
    const subscribeMsgVal = (rule, value, callback) => {
      if (this.ruleForm.playConditionFlag == 1 && this.ruleForm.gameRuleConditionList[2].conditionType != -1 && this.ruleForm.gameRuleConditionList[2].conditionJson.type == 12 && !this.ruleForm.gameRuleConditionList[2].conditionJson.subscribeMsg) {
        callback(new Error('请输入'));
        return;
      }
      callback();
    };

    return {
      // 链接小工具选择链接
      show: false,
      selectLink: {
        show: false,
        linkData: {}
      },
      selectedGroupIds: '', // 被选中的客户分组id
      groupVisible: false,
      ruleForm: {
        hasSearchData: '',
        memberType: 0,
        memberDesc: '',
        playConditionFlag: 1,
        shareFlag: 1,
        playTimes: '',
        filterJsonView: '',
        shareImageUrl: '',
        memberWeightView: { searchId: '' },
        creatorId: '',
        gameRuleConditionList: [
          {
            type: 2,
            conditionType: -1, // 赠与免费游戏次数
            conditionJson: {
              type: 22,
              value: ''
            }
          },
          {
            type: 0,
            conditionType: -1, // 消耗积分获得游戏次数
            conditionJson: {
              type: 1,
              value: '',
              dumpPath: '',
              mpUrlView: {}
            }
          },
          {
            type: 1,
            conditionType: -1, //邀请好友助力获得游戏次数
            conditionJson: {
              type: 11, // 11 注册新会员 12 首次关注服务号
              inviteNum: '',
              value: '',
              subscribeMsg: '恭喜你已完成助力',
              shareTitle: '我正在参加幸运大盲盒，邀请你一起参加！',
              shareCard: '',
              momentsCard: '',
              shareReport: ''
            }
          }
        ]
      },
      toggleTag: false, // 控制按钮显示的参数,仅供参考,可自行修改
      rules: {
        memberType: { required: true, message: '请选择' },
        memberDesc: { type: 'string', required: true, message: '请输入适用人群说明', trigger: 'blur' },
        playTimes: { type: 'number', required: true, message: '请输入不超过1000的数字', max: 1000, min: 1 },
        playConditionFlag: { required: true },
        mpUrlView: { validator: mpUrlViewVal },
        shareTitle: { validator: shareTitleVal },
        filterJson: { validator: filterJsonVal },
        subscribeMsg: { validator: subscribeMsgVal }
      },
      isAdd: this.$route.meta.type === 'add',
      isEdit: this.$route.meta.type === 'edit',
      gameDays: 0,
      boolVal: true,
      shareCardSize0: '',
      shareCardSize1: 1,
      momentsCardSize0: '',
      momentsCardSize1: 1,
      shareReportSize1: 1,
      shareReportSize0: '',
      addMomentsCard: false,
      momentsCard: ''
    };
  },
  props: {
    shareImgData: {
      type: Object,
      default: () => {}
    },
    gameStatus: 0,
    btnLoading: Boolean,
    echoData: {
      type: Object,
      default: () => {}
    },
    gameTime: {
      type: Object,
      default: () => []
    },
    templateId: String
  },
  watch: {
    shareImgData(val) {
      const { shareCard, shareReport, shareCardSize0, shareCardSize1, shareReportSize1, shareReportSize0, momentsCard, momentsCardSize0, momentsCardSize1 } = val;
      this.ruleForm.gameRuleConditionList[2].conditionJson.shareCard = shareCard;
      this.ruleForm.gameRuleConditionList[2].conditionJson.momentsCard = momentsCard;
      this.ruleForm.gameRuleConditionList[2].conditionJson.shareReport = shareReport;
      this.ruleForm.shareImageUrl = shareCard;
      this.shareCardSize0 = shareCardSize0;
      this.shareCardSize1 = shareCardSize1;
      this.momentsCardSize0 = momentsCardSize0;
      this.momentsCardSize1 = momentsCardSize1;
      this.shareReportSize1 = shareReportSize1;
      this.shareReportSize0 = shareReportSize0;
      // this.addMomentsCard = addMomentsCard;
      // this.momentsCard = momentsCard;
      this.ruleForm.gameRuleConditionList = this.ruleForm.gameRuleConditionList.splice(0);
    },
    echoData(val) {
      const { ruleId, filterJson, filterJsonView, gameRuleConditionList, memberDesc, memberType, playConditionFlag, playTimes, shareFlag, shareImageUrl, shareRuleDesc, memberWeightView, creatorId } = val;
      if (playConditionFlag == 1) {
        let obj = {};
        gameRuleConditionList.forEach(item => {
          obj[item.conditionType] = item;
        });
        this.ruleForm.gameRuleConditionList.forEach(item => {
          if (obj[item.type]) {
            item.conditionType = obj[item.type].conditionType;
            item.conditionJson = obj[item.type].conditionJson;
            item.conditionId = obj[item.type].conditionId;
          }
        });
        // if (this.addMomentsCard) {
        //   this.ruleForm.gameRuleConditionList[2].conditionJson.momentsCard = this.momentsCard;
        // }
      }
      if (this.isEdit) {
        if (memberType == 1) {
          this.selectedGroupIds = filterJson;
        } else {
          this.ruleForm.hasSearchData = filterJson;
        }
        this.ruleForm.memberType = memberType;
      }
      this.ruleForm = Object.assign(this.ruleForm, { ruleId, memberDesc, playConditionFlag, playTimes, shareFlag, shareImageUrl, shareRuleDesc, memberWeightView, creatorId, filterJsonView });
      console.log(this.ruleForm);
    },
    gameTime(val) {
      if (val && val.length) {
        this.gameDays = (val[1] - val[0]) / (24 * 60 * 60 * 1000);
        console.log(this.gameDays);
        this.gameDays = this.gameDays.toFixed();
      }
    }
  },
  components: {
    Linktools
  },
  computed: {
    storeParams() {
      return !this.isAdd ? { creatorId: this.ruleForm.creatorId } : {};
    },
    isDisabled() {
      return this.gameStatus == 1;
    }
  },
  methods: {
    /**客户分组 */
    confirmGroupDialog(arr, idStr) {
      this.selectedGroupIds = idStr;
      this.clearValidate('filterJson');
    },
    /*-------人群筛选器的方法-------*/
    getData() {
      this.$refs.peopleFilter.confirmSet();
      this.clearValidate('filterJson');
    },
    // 取消
    cancelFilter() {
      this.$refs.peopleFilter.cancelSet();
    },
    getBackData(val) {
      console.log(val);
      this.ruleForm.filterJsonView = val;
    },
    // 子组件触发父组件事件,返回过滤条件数据
    findFilter(val) {
      console.log(val);
      this.ruleForm.hasSearchData = val;
    },
    downloadTmp() {
      let id = this.templateId == 3 ? 1 : this.templateId;
      window.open(`https://pic01-10001430.cos.ap-shanghai.myqcloud.com/game/template${id}/海报.ai`);
    },
    // 保存链接小工具返回的链接数据
    onSaveLink(linkData) {
      getPageLink({ requestProject: 'gic-web', pageLink: linkData }).then(res => {
        const { link } = res.result;
        this.selectLink.linkData = linkData;
        this.ruleForm.gameRuleConditionList[1].conditionJson.dumpPath = link;
        this.ruleForm.gameRuleConditionList[1].conditionJson.mpUrlView = linkData;
        this.ruleForm.gameRuleConditionList = this.ruleForm.gameRuleConditionList.splice(0);
        this.$refs.ruleForm.validateField('gameRuleConditionList.' + 1 + '.conditionJson.' + 'mpUrlView');
      });
    },
    beforeAvatarUpload(file, key, size1 = 1) {
      const arr = ['image/jpeg', 'image/png'];
      const limit = file.size / 1024 / 1024 < size1;
      if (!arr.includes(file.type)) {
        this.$message.warning('只能上传jpg/jpeg/png格式文件!');
        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 == 'shareCard') {
              this.ruleForm.gameRuleConditionList[2].conditionJson.shareCard = data.result.qcloudImageUrl;
              this.ruleForm.shareImageUrl = data.result.qcloudImageUrl;
            } else if (key == 'momentsCard') {
              this.ruleForm.gameRuleConditionList[2].conditionJson.momentsCard = data.result.qcloudImageUrl;
            } else {
              this.ruleForm.gameRuleConditionList[2].conditionJson.shareReport = data.result.qcloudImageUrl;
            }
            this.ruleForm.gameRuleConditionList = this.ruleForm.gameRuleConditionList.splice(0);
            this.$message({
              type: 'success',
              message: '上传成功'
            });
          }
        })
        .catch(error => {
          this.$message({
            type: 'error',
            message: error.message
          });
        });
      return true;
    },
    prevStep() {
      this.$emit('prevStep');
    },
    clearValidate(name) {
      this.$refs.ruleForm.clearValidate(name);
    },
    validateData() {
      this.$refs.ruleForm.validate(val => {
        this.boolVal = val;
        if (!val) {
          this.scrollToError(this);
        }
      });
      if (!this.boolVal) {
        this.$message.error('请确认规则设置的必填字段都已填写且通过校验');
        return false;
      }
      if (this.ruleForm.memberType == 0 && this.toggleTag && !this.ruleForm.filterJsonView) {
        this.$message.error('人群筛选未保存条件');
        return false;
      }
      if (this.ruleForm.playConditionFlag == 1 && !this.ruleForm.gameRuleConditionList.filter(item => item.conditionType != -1).length) {
        this.$message.error('请至少勾选一项');
        return false;
      }
      const conditionType2 = this.ruleForm.gameRuleConditionList.filter(item => item.conditionType == 2);
      if (this.ruleForm.playConditionFlag == 1 && conditionType2.length) {
        const maxTimes = conditionType2[0].conditionJson.type == 22 ? conditionType2[0].conditionJson.value : conditionType2[0].conditionJson.value * this.gameDays;
        if (maxTimes > this.ruleForm.playTimes) {
          this.$message.error(`每人最多可玩次数需大于免费游戏次数${maxTimes}`);
          return false;
        }
      }

      return true;
    },
    nextStep(noNext) {
      return new Promise(resolve => {
        const val = this.validateData();
        if (val) {
          const data = { ...this.ruleForm };
          const arr = [];
          if (data.memberType == 1) {
            data.filterJson = this.selectedGroupIds;
          } else {
            data.filterJson = data.hasSearchData;
          }
          data.gameRuleConditionList.forEach(item => {
            if (item.conditionType != -1) {
              arr.push(item);
            }
          });
          data.gameRuleConditionList = arr;
          console.log(data);
          this.$emit('nextStep', data, noNext);
        }
        resolve(val);
      });
    },
    submit() {
      this.$emit('submit');
    }
  }
};
</script>

<style lang="scss" scoped>
.footer {
  width: calc(100% - 520px) !important;
}
.shareBox {
  width: 600px;
  background: #f7f8fa;
  padding: 16px 20px;
  box-sizing: border-box;
}

.downloadBtn {
  display: flex;
  margin-top: 8px;
}
</style>
