<template>
  <el-dialog title="添加小程序链接" :visible.sync="show" width="770px" class="add-replay-content" :before-close="close">
    <el-form style="max-height: 550px;overflow: auto;" label-position="right" ref="form" :model="form" label-width="100px" v-loading="loading">
      <el-form-item class="text-content" label="文本内容">
        <el-input v-model="form.title" @keyup.native="toInput(form.title, $event)"></el-input>
        <span class="text-num">{{ inputNum }}/{{ inputLength }}</span>
      </el-form-item>
      <div class="content-wrap">
        <div class="xcx-content-wrap">
          <el-form-item label="上传图片">
            <div class="upload-content">
              <el-upload class="avatar-uploader" action="123" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                <img v-if="form.imageUrl" :src="form.imageUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <p>请上传长宽比为5:4的图片</p>
            </div>
          </el-form-item>

          <el-form-item label="链接类型" class="url-link-wrap">
            <div v-loading="linkLoading">
              <el-select @change="changePreValue" v-model="preValue" class="w200" placeholder="请选择" style="margin-right: 6px;">
                <el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value"> </el-option>
              </el-select>
              <el-select v-show="preValue == 5" v-loadmore="getMore" remote filterable clearable :remote-method="remoteMethod" @change="changeNextValue" v-model="nextValue" class="w200" placeholder="请选择(支持模糊查询)">
                <!-- <el-select v-loadmore="getMore" filterable clearable @change="changeNextValue" remote :remote-method="remoteMethod" class="w200" v-model="nextValue" placeholder="请选择"> -->
                <el-option v-for="item in options2" :key="item.linkId" :label="item.name" :value="item.linkId"> </el-option>
              </el-select>
              <el-select v-show="preValue && preValue != 5" filterable clearable @change="changeNextValue" class="w200" v-model="nextValue" placeholder="请选择">
                <el-option v-for="item in options2" :key="item.linkId" :label="item.name" :value="item.linkId"> </el-option>
              </el-select>
              <el-select class="w200" v-model="threeValue" placeholder="请选择" v-if="options3 && options3.length > 0" @change="changeThreeValue">
                <el-option v-for="item in options3" :key="item.tagid" :label="item.tagname" :value="item.tagid"></el-option>
              </el-select>
              <game-list style="margin-top:20px;margin-right: 8px;padding: 20px;border: 1px solid #dcdfe6;border-radius:2px" ref="gameList" v-if="gameLinkVisible" :game-id="gameProps.gameId" :game-type="gameProps.gameType" @select="onSelectGame"></game-list>
            </div>
          </el-form-item>
        </div>
      </div>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="close">关 闭</el-button>
      <el-button type="primary" @click="addItem">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getByteVal, getZhLen } from '../assets/utils.js';
import qs from 'qs';
import GameList from './game-list.vue';
export default {
  name: 'lib-wxa',
  components: { GameList },
  props: {
    show: {
      type: Boolean,
      default: false
    },
    item: {
      type: Object,
      default() {
        return {};
      }
    },
    resourceStatus: Number
  },
  data() {
    return {
      loading: false,
      form: {
        title: '',
        linkStyle: '0',
        url: '',
        imageUrl: '',
        mediaId: ''
      },
      inputNum: 0, // 输入文字个数(两个字母/汉字算一个字)
      inputLength: 20, // 限制最大字数
      preValue: '',
      nextValue: '',
      threeValue: '',
      options1: [
        {
          value: 3,
          label: '导航tabbar页'
        },
        {
          value: 4,
          label: '二级功能页'
        },
        {
          value: 5,
          label: '自定义页面'
        }
      ],
      options2: [],
      gameProps: {
        gameType: '',
        gameId: ''
      },
      wechatContent: {},
      listParams: {
        pageSize: 10,
        currentPage: 1,
        search: '',
        requestProject: 'gic-web'
      },
      nomore: false,
      linkLoading: false
    };
  },
  directives: {
    loadmore: {
      inserted(el, binding) {
        // 获取element-ui定义好的scroll盒子
        const SELECTDOWN_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap');
        SELECTDOWN_DOM.addEventListener('scroll', function() {
          const CONDITION = this.scrollHeight - this.scrollTop <= this.clientHeight;
          if (CONDITION) {
            binding.value();
          }
        });
      }
    }
  },
  computed: {
    options3() {
      let obj = this.options2.find(el => {
        return el.linkId === this.nextValue;
      });
      if (obj && obj.childList && obj.childList.length > 0) {
        return obj.childList;
      } else {
        return [];
      }
    },
    gameLinkVisible() {
      return this.nextValue == 'GAME_LINK' && this.threeValue;
    }
  },
  watch: {
    options3() {
      this.threeValue = '';
    },
    show(val) {
      this.form = {
        title: '',
        linkStyle: '0',
        url: '',
        imageUrl: '',
        mediaId: ''
      };
      this.preValue = '';
      this.nextValue = '';
      this.threeValue = '';
      this.selectedGame = null;
      this.wechatContent = {};
      if (val && this.item.ecmMarketingTypeRelationId) {
        this.form = JSON.parse(JSON.stringify(this.item));
        // console.log('编辑', this.item);
        if (this.resourceStatus !== 0) return;
        const pagePath = this.form.pagePath ? JSON.parse(this.form.pagePath) : {};
        this.wechatContent.type = pagePath.type;
        this.wechatContent.objId = '';
        this.wechatContent.title = pagePath.title;
        this.wechatContent.pageType = pagePath.pageType;
        this.preValue = pagePath.pageType;

        if (pagePath.pageType === 5) {
          // 自定义链接
          // 获取pageName
          this.getPageName(pagePath.pageId);
        } else {
          this.getNextList(this.preValue).then(res => {
            if (pagePath.type.startsWith('GAME_LINK')) {
              this.nextValue = 'GAME_LINK';
            } else {
              this.nextValue = pagePath.type;
            }
            if (this.nextValue == 'GAME_LINK') {
              this.$nextTick(() => {
                this.threeValue = pagePath.gameType;
                this.gameProps.gameType = pagePath.gameType;
                this.gameProps.gameId = pagePath.tagid;
                this.wechatContent.tagid = pagePath.tagid;
                this.wechatContent.tagname = pagePath.tagname;
                this.wechatContent.gameType = pagePath.gameType;
                this.wechatContent.gameName = pagePath.gameName;
                this.selectedGame = { gameId: pagePath.tagid };
              });
            } else {
              this.$nextTick(() => {
                this.threeValue = pagePath.tagid;
              });
            }
          });
        }
      }
    }
  },
  methods: {
    toInput(value, e) {
      // 控制字符数量
      var that = this;
      that.form.title = getByteVal(e.target.value, that.inputLength);
      that.inputNum = getZhLen(that.form.title);
    },
    handleAvatarSuccess(res, file) {
      //
    },
    beforeAvatarUpload(file) {
      // console.log(file)
      let fd = new FormData();
      fd.append('file', file);
      fd.append('requestProject', 'gic-web');
      this.axios.post('/api-admin/marketing-wechat-image-save', fd).then(res => {
        //成功后回调
        var data = res.data;
        // console.log(data);
        if (data.errorCode == 0) {
          this.form.imageUrl = data.result.qcloudImageUrl;
          this.form.mediaId = data.result.imageMediaId;

          this.$message({
            type: 'success',
            message: '上传成功'
          });
        } else {
          this.$message({
            type: 'error',
            message: data.message
          });
        }
      });
      return true;
    },
    // 链接类型
    changePreValue(val) {
      // val==3  导航tabbar页 val==4 二级功能页 val==5 自定义链接
      this.nextValue = '';
      this.options2 = [];
      if (val === 5) {
        this.remoteMethod('');
      } else {
        this.getNextList(val);
      }
    },
    // 获取页面名称
    getPageName(pageId) {
      this.axios
        .post(
          '/api-admin/get-custom-page-entity',
          qs.stringify({
            pageId,
            requestProject: 'gic-web'
          })
        )
        .then(res => {
          var data = res.data;
          if (data.errorCode == 0) {
            this.listParams.search = data.result.title;
            this.getCustonList().then(res => {
              this.nextValue = pageId;
            });
          } else {
            this.loading = false;
            this.$message({
              type: 'error',
              message: data.message
            });
          }
        });
    },
    // 模糊搜索
    remoteMethod(search) {
      this.listParams.search = search;
      this.listParams.currentPage = 1;
      this.options2 = [];
      this.nomore = false;
      this.getCustonList();
    },
    // 下一页
    getMore() {
      console.log(this.nomore);
      if (this.nomore) {
        return;
      }
      this.listParams.currentPage = this.listParams.currentPage * 1 + 1;
      this.getCustonList();
    },
    changeNextValue(val) {
      if (val) {
        let obj = {};
        obj = this.options2.find(style => {
          return style.linkId === val;
        });
        this.wechatContent.type = obj.linkId;
        this.wechatContent.objId = '';
        this.wechatContent.title = obj.name;
        this.wechatContent.pageType = this.preValue;
      }
    },
    changeThreeValue(val) {
      console.log(val);
      if (val.startsWith('GAME_LINK')) {
        this.selectedGame = null;
        this.wechatContent.type = val;
        this.$nextTick(() => {
          this.gameProps.gameType = val;
          this.gameProps.gameId = '';
        });
      } else {
        let option = this.options3.find(el => el.tagid === val);
        this.wechatContent.tagid = option.tagid;
        this.wechatContent.tagname = option.tagname;
      }
    },
    onSelectGame(val) {
      if (val) {
        this.gameProps.gameId = val.gameId || val.gameActivityId;
        this.wechatContent.tagid = val.gameId || val.gameActivityId;
        this.wechatContent.tagname = val.gameName;
        this.wechatContent.gameType = this.threeValue;
        this.wechatContent.gameName = val.gameName;
        this.selectedGame = val;
      }
    },
    // 获取自定义链接list
    getCustonList() {
      return new Promise((resolve, reject) => {
        this.linkLoading = true;
        this.axios.post('/api-admin/list-custom-page-for-link', qs.stringify(this.listParams)).then(res => {
          this.linkLoading = false;
          //成功后回调
          var data = res.data;
          if (data.errorCode == 0) {
            const options2 =
              data.result.result.map(v => {
                return {
                  linkId: v.pageId,
                  name: v.name,
                  url: v.url
                };
              }) || [];
            const tableList = options2 ? this.options2.concat(options2) : [];
            const total = data.result.totalCount;
            this.options2 = tableList;
            this.total = total;
            this.nomore = total <= tableList.length || total - tableList.length < this.listParams.pagesize; // 没有下一页了
            resolve();
          } else {
            this.linkLoading = false;
            this.$message({
              type: 'error',
              message: data.message
            });
          }
        });
      });
    },
    // 获得链接类型的二级
    getNextList(type) {
      return new Promise((resolve, reject) => {
        this.axios
          .post(
            '/api-plug/list-link-data',
            qs.stringify({
              requestProject: 'gic-web',
              linkScene: parseInt(type)
            })
          )
          .then(res => {
            //成功后回调
            var data = res.data;
            if (data.errorCode == 0) {
              this.options2 = data.result;
              this.total = data.result.length;
              this.nomore = false; // 没有下一页了
              resolve();
            } else {
              this.$message({
                type: 'error',
                message: data.message
              });
            }
          });
      });
    },
    addItem() {
      let sendData = {
        ecmMarketingTypeRelationId: this.item.ecmMarketingTypeRelationId,
        comName: 'wxa',
        title: this.form.title,
        mediaId: this.form.mediaId
      };

      if (!sendData.title) {
        this.$message({ type: 'warning', message: '简介未填写' });
        return;
      }
      if (!sendData.mediaId) {
        this.$message({ type: 'warning', message: '图片未上传' });
        return;
      }
      if (!this.preValue || !this.nextValue) {
        this.$message({ type: 'warning', message: '链接选择' });
        return;
      }
      if (this.options3 && this.options3.length > 0 && !this.threeValue) {
        this.$message({ type: 'warning', message: '链接选择' });
        return;
      }
      if (this.nextValue == 'GAME_LINK' && !this.selectedGame) {
        this.$message({ type: 'warning', message: '请选择游戏' });
        return;
      }

      // 自定义链接
      if (this.preValue === 5) {
        sendData.pagePath = JSON.stringify({
          customUrl: this.options2.find(v => {
            return v.linkId === this.nextValue;
          }).url,
          pageId: this.nextValue,
          pageType: 5
        });
      } else {
        sendData.pagePath = JSON.stringify(this.wechatContent);
      }
      this.$emit('sendItem', sendData);
      this.close();
    },
    close() {
      this.listParams.currentPage = 1;
      this.listParams.search = '';
      this.listParams.nomore = false;
      this.options2 = [];
      this.options3 = [];
      this.$emit('update:show', false);
    }
  }
};
</script>

<style lang="scss" scoped>
.add-replay-content {
  .text-content {
    position: relative;
    width: 400px;
    .text-num {
      position: absolute;
      right: 10px;
      bottom: 2px;
      color: #c0c4cc;
      font-size: 12px;
      background: #fff;
      height: 28px;
      line-height: 28px;
      padding-left: 10px;
    }
  }
  .link-url-warning {
    color: #909399;
    font-size: 12px;
    line-height: 1;
    padding-top: 4px;
    margin-top: 3px;
    position: absolute;
    top: 100%;
    left: 0;
  }
}
.xcx-content-wrap {
  width: 100%;
  .upload-content {
    > p {
      height: 36px;
      line-height: 36px;
      font-size: 12px;
      color: #b8b8b8;
    }
  }
}
.avatar-uploader {
  width: 152px;
  height: 152px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  &:hover {
    border-color: #2f54eb;
  }
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}
.avatar {
  width: 150px;
  height: 150px;
  display: block;
}
.upload-content /deep/ .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.upload-content /deep/ .avatar-uploader .el-upload:hover {
  border-color: #2f54eb;
}
</style>
