<template>
  <div v-loading="readOnly && loading" :class="{ 'inline-block': onlySelect }">
    <template v-if="!onlySelect">
      <div v-if="!readOnly">
        <span class="dm-input_label">营销活动<span v-if="colon">：</span></span>
        <el-select remote filterable clearable v-loadmore="getMore" :remote-method="remoteMethod" @change="updateActId" class="w250 act-select" size="small" v-model="marketingActivityId" :disabled="readOnly || disabled" placeholder="选择营销活动">
          <el-option v-for="item in tableList" :key="item.marketingActivityId" :label="item.name" :value="item.marketingActivityId"></el-option>
        </el-select>
        <el-button type="text" class="ml10" @click="toAdd">去新建</el-button>
      </div>
      <div v-else>
        <span class="dm-input_label">营销活动<span v-if="colon">：</span></span>
        <p class="inline-block">{{ info.name || '--' }} <span v-if="info.status === 0" class="fz12 gray ml10">当前计划使用的营销活动已删除</span></p>
      </div>
    </template>
    <el-select v-else remote filterable clearable v-loadmore="getMore" :remote-method="remoteMethod" @change="updateActId" size="small" v-model="marketingActivityId" :disabled="readOnly" placeholder="选择营销活动">
      <el-option v-for="item in tableList" :key="item.marketingActivityId" :label="item.name" :value="item.marketingActivityId"></el-option>
    </el-select>
  </div>
</template>

<script>
import { activityList, getActivityInfo } from '@/service/api/activityApi.js';
export default {
  name: 'activity-use-select',
  props: {
    actId: {
      default: '',
      type: String
    },
    readOnly: {
      default: false,
      type: Boolean
    },
    // onlySelect: 只有下拉 用于列表处
    onlySelect: {
      default: false,
      type: Boolean
    },
    // 是否需要冒号
    colon: {
      default: false,
      type: Boolean
    }
  },
  data() {
    return {
      loading: false,
      marketingActivityId: '',
      info: {},
      tableList: [],
      total: 0,
      listParams: {
        expireType: -1, // -1: 进行中/未开始 1: 已过期 0: 使用中
        search: '',
        currentPage: 1,
        pageSize: 10
      },
      nomore: false, // 没有更多
      disabled: false // 给外部使用，或条件
    };
  },
  watch: {
    actId: {
      handler(val) {
        // 只读时获取详情
        if (val && this.readOnly) {
          this.marketingActivityId = val;
          this.getActivityInfo();
        }
      },
      immediate: true
    }
  },
  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();
          }
        });
      }
    }
  },
  methods: {
    toAdd() {
      if(process.env['NODE_ENV'] !== 'development') { // eslint-disable-line
        // 强制切换 避免顶部菜单没切换
        console.log(window.location.origin + window.location.pathname + 'activity/add');
        window.location.href = window.location.origin + window.location.pathname + '#/activity/add';
        window.location.reload();
      } else {
        this.$router.push('/activity/add');
      }
    },
    // 外部设置反显
    setInfo(actId) {
      this.loading = true;
      getActivityInfo({ marketingActivityId: actId })
        .then(res => {
          this.loading = false;
          this.tableList = res.result ? [res.result] : [];
          this.marketingActivityId = actId;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 获取详情
    getActivityInfo() {
      this.loading = true;
      getActivityInfo({ marketingActivityId: this.actId })
        .then(res => {
          this.loading = false;
          this.info = res.result || {};
        })
        .catch(() => {
          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.marketingActivityId = '';
      // this.updateActId('');
      this.getList();
    },
    // 下一页
    getMore() {
      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;
      activityList(this.listParams)
        .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);
        })
        .catch(() => {
          this.loading = false;
        });
    }
  },
  mounted() {
    !this.readOnly && this.getList();
  }
};
</script>

<style lang="scss" scoped>
.dm-input_label {
  padding-right: 8px;
}
</style>
