<template>
  <div v-loading="loading" class="inline-block">
    <div v-if="showType == 'search'">
      <el-select :disabled="disabled" :style="`width:${width}px`" remote filterable clearable v-loadmore="getMore" :remote-method="remoteMethod" @change="updateActId" class="act-select" v-model="mktActivityId" placeholder="请输入关键字...">
        <el-option v-for="item in tableList" :key="item.mktActivityId" :label="item.name" :value="item.mktActivityId"></el-option>
      </el-select>
      <span v-if="!noAdd" class="ml10 hover-btn" @click="activityDialog = true"><i class="el-icon-plus mr5"></i>新建数据对话</span>
    </div>
    <div v-if="showType == 'textInput'">
      <el-input :style="`width:${width}px`" disabled :value="info.name" />
      <!-- <span v-if="info.deleteFlag === 1" class="fz12 gray03 ml10">当前计划使用的数据对话已删除</span> -->
    </div>
    <div v-if="showType == 'text'">
      <span class="word-break">{{ info.name || '--' }}</span>
      <!-- <span v-if="info.deleteFlag === 1" class="fz12 gray03 ml10">当前计划使用的数据对话已删除</span> -->
    </div>
    <add-activity-dialog ref="addActivityDialog" :dialog-visible.sync="activityDialog" @saveSuccess="saveSuccess" />
  </div>
</template>

<script>
import addActivityDialog from './dialog.vue';
import commonApi from '@/api/common';
const { activityList, getActivityInfo } = commonApi;
export default {
  name: 'ActivityUseSelect',
  components: {
    addActivityDialog
  },
  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();
          }
        });
      }
    }
  },
  props: {
    actId: {
      default: '',
      type: String
    },
    noAdd: {
      default: false,
      type: Boolean
    },
    showType: {
      // 展示类型
      type: String,
      default: 'search', // search:模糊搜索  text:展示name   textInput:展示name(在input中)
    },
    width: {
      // input width
      type: [ Number, String ],
      default: 250
    },
    disabled: {
      type: Boolean,
      default: false
    },
    // 当在列表中做筛选使用时，status需要穿''
    status: {
      type: Number,
      default: 2 // -1未开始  0进行中  1:已结束/已下线   2未下线
    }
  },
  data() {
    return {
      loading: false,
      mktActivityId: '',
      info: {},
      tableList: [],
      total: 0,
      listParams: {
        status: this.status,
        search: '',
        currentPage: 1,
        pageSize: 10
      },
      nomore: false, // 没有更多
      activityDialog: false,
    };
  },
  mounted() {
    !this.showInfo && this.getList();
  },
  methods: {
    // 新增活动成果
    saveSuccess() {
      // 重新获取所有数据
      this.loading = false;
      this.nomore = false;
      this.listParams.search = '';
      this.listParams.currentPage = 1;
      this.tableList = [];
      this.$emit('update:actId', '');
      this.getList();
    },
    // 外部调用
    setListById(actId) {
      this.loading = true;
      getActivityInfo({ mktActivityId: actId })
        .then(res => {
          this.loading = false;
          const info = res.result || {};
          if(info.deleteFlag == 1) {
            info.name += '（已删除）';
          }
          if(JSON.stringify(info) !== '{}') {
            this.tableList = [ info ];
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 获取详情
    getActivityInfo() {
      this.loading = true;
      getActivityInfo({ mktActivityId: this.actId })
        .then(res => {
          this.loading = false;
          this.info = res.result || {};
          if(this.info.deleteFlag == 1) {
            this.info.name += '（已删除）';
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    updateActId(val) {
      this.$emit('update:actId', val);
      this.$emit('actUpdate'); // 触发父组件更新
      if (!val) {
        this.remoteMethod('');
      }
    },
    // 模糊搜索
    remoteMethod(search) {
      this.listParams.search = search;
      this.listParams.currentPage = 1;
      this.tableList = [];
      this.nomore = false;
      // this.mktActivityId = '';
      // this.updateActId('');
      this.getList();
    },
    // 下一页
    getMore() {
      if(this.loading) {
        return;
      }
      if (this.nomore) {
        return;
      }
      this.listParams.currentPage = this.listParams.currentPage * 1 + 1;
      this.getList();
    },
    getList() {
      if (this.nomore) {
        return;
      }
      this.loading = true;
      this.nomore = false;
      const params = { ...this.listParams };
      if(params.status == '') {
        delete params.status;
      }
      activityList(params)
        .then(res => {
          this.loading = false;
          const tableList = this.tableList.concat(res.result.result) || [];
          const total = res.result.totalCount;
          this.tableList = tableList;
          this.total = total;
          this.nomore = total <= tableList.length || total - tableList.length < this.listParams.pagesize; // 没有下一页了
          // console.log('total:', total, 'length:', tableList.length, this.nomore);
        })
        .finally(() => {
          this.loading = false;
        });
    }
  },
  watch: {
    actId: {
      handler(val) {
        // 只读时获取详情
        if (val && this.showType !== 'search') {
          this.getActivityInfo();
        }
        this.mktActivityId = val;
      },
      immediate: true
    }
  }
};
</script>

<style lang="scss" scoped>
.label {
  display: inline-block;
  padding-right: 8px;
}
</style>
