<template>
  <div class="app-container">
    <div class="table">
      <!-- 搜索栏 -->
      <div class="filter-container">
        <!-- 系统 -->
        <el-select
          v-model="listQuery.sysOrigin"
          :placeholder="$t('pages.activityTemplateManage.filter.system')"
          style="width: 120px"
          class="filter-item"
          @change="handleSearch"
        >
          <el-option
            v-for="item in permissionsSysOriginPlatforms"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
            <span style="float: left;">
              <sys-origin-icon :icon="item.value" :desc="item.value"
            /></span>
            <span style="float: left;margin-left:10px">{{ item.label }}</span>
          </el-option>
        </el-select>

        <!-- 状态 -->
        <el-select
          v-model="listQuery.showcase"
          :placeholder="$t('pages.activityTemplateManage.filter.status')"
          style="width: 120px"
          class="filter-item"
          clearable
          @change="handleSearch"
        >
          <el-option-group :label="$t('pages.activityTemplateManage.group.runtimeStatus')">
            <el-option :label="$t('pages.activityTemplateManage.word.started')" :value="1" />
            <el-option :label="$t('pages.activityTemplateManage.word.ended')" :value="2" />
          </el-option-group>
          <el-option-group :label="$t('pages.activityTemplateManage.group.managementStatus')">
            <el-option :label="$t('pages.activityTemplateManage.word.onShelf')" :value="3" />
            <el-option :label="$t('pages.activityTemplateManage.word.offShelf')" :value="4" />
          </el-option-group>
        </el-select>

        <!-- 活动ID -->
        <el-input
          v-model.trim="listQuery.id"
          v-number
          :placeholder="$t('pages.activityTemplateManage.filter.activityId')"
          style="width: 200px;"
          class="filter-item"
        />

        <!-- 模版ID -->
        <el-input
          v-model.trim="listQuery.templateId"
          v-number
          :placeholder="$t('pages.activityTemplateManage.filter.templateId')"
          style="width: 200px;"
          class="filter-item"
        />

        <!-- 搜索按钮 -->
        <el-button
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          @click="handleSearch"
        >
          {{ $t('pages.activityTemplateManage.action.search') }}
        </el-button>

        <!-- 新增按钮 -->
        <el-button
          class="filter-item"
          type="primary"
          icon="el-icon-edit"
          @click="clickCreate"
        >
          {{ $t('pages.activityTemplateManage.action.create') }}
        </el-button>

        <!-- 帮助按钮 -->
        <el-popover :title="$t('pages.activityTemplateManage.help.title')" trigger="hover">
          <div class="content">
            <div class="help">
              <strong>{{ $t('pages.activityTemplateManage.help.createTitle') }}</strong>
              <p>{{ $t('pages.activityTemplateManage.help.createStep1') }}</p>
              <p>{{ $t('pages.activityTemplateManage.help.createStep2') }}</p>
              <p>{{ $t('pages.activityTemplateManage.help.createStep3') }}</p>
              <p>{{ $t('pages.activityTemplateManage.help.createStep4') }}</p>
              <strong>{{ $t('pages.activityTemplateManage.help.rankTitle') }}</strong>
              <p>{{ $t('pages.activityTemplateManage.help.rankStep1') }}</p>
              <p>
                {{ $t('pages.activityTemplateManage.help.rankStep2') }}
              </p>
              <p>{{ $t('pages.activityTemplateManage.help.rankStep3') }}</p>
              <p>{{ $t('pages.activityTemplateManage.help.rankStep4') }}</p>
              <strong>{{ $t('pages.activityTemplateManage.help.noticeTitle') }}</strong>
              <p>
                {{ $t('pages.activityTemplateManage.help.noticeStep1') }}
              </p>
              <p>
                {{ $t('pages.activityTemplateManage.help.noticeStep2') }}
              </p>
              <p>
                {{ $t('pages.activityTemplateManage.help.noticeStep3') }}
              </p>
            </div>
          </div>
          <span slot="reference"><i class="el-icon-info" />{{ $t('pages.activityTemplateManage.action.help') }}</span>
        </el-popover>
      </div>

      <!-- 列表 -->
      <el-table
        v-loading="listLoading"
        :data="list"
        element-loading-text="Loading"
        fit
        highlight-current-row
      >
        <!-- 关联模版 -->
        <el-table-column
          :label="$t('pages.activityTemplateManage.table.relatedTemplate')"
          prop="templateName"
          align="center"
          min-width="200"
        />

        <!-- 备注 -->
        <el-table-column
          :label="$t('pages.activityTemplateManage.table.remark')"
          prop="config.remark"
          align="center"
          min-width="200"
        />

        <!-- 状态 -->
        <el-table-column
          :label="$t('pages.activityTemplateManage.table.status')"
          prop="config.startTime"
          align="center"
          min-width="200"
        >
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.config.showcase === true ? 'primary' : 'danger'"
            >
              {{ scope.row.config.showcase === true ? $t("pages.activityTemplateManage.word.onShelf") : $t("pages.activityTemplateManage.word.offShelf") }}
            </el-tag>
            <el-tag v-if="scope.row.status === 0" type="info">{{ $t('pages.activityTemplateManage.word.notStarted') }}</el-tag>
            <el-tag v-if="scope.row.status === 1" type="success">{{ $t('pages.activityTemplateManage.word.started') }}</el-tag>
            <el-tag v-if="scope.row.status === 2" type="warning">{{ $t('pages.activityTemplateManage.word.ended') }}</el-tag>
          </template>
        </el-table-column>

        <!-- 活动时间 -->
        <el-table-column
          :label="$t('pages.activityTemplateManage.table.activityTime')"
          prop="config.startTime"
          align="center"
          min-width="200"
        >
          <template slot-scope="scope">
            <div>{{ $t('pages.activityTemplateManage.label.start') }}: {{ scope.row.config.startTime | dateFormat }}</div>
            <div>{{ $t('pages.activityTemplateManage.label.end') }}: {{ scope.row.config.endTime | dateFormat }}</div>
          </template>
        </el-table-column>

        <!-- 修改/创建人 -->
        <el-table-column
          :label="$t('pages.activityTemplateManage.table.updatedCreatedBy')"
          prop="config.createTime"
          align="center"
          min-width="200"
        >
          <template slot-scope="scope">
            <div>{{ $t('pages.activityTemplateManage.label.update') }}: {{ scope.row.updateUserName }}</div>
            <div>{{ $t('pages.activityTemplateManage.label.create') }}: {{ scope.row.createUserName }}</div>
          </template>
        </el-table-column>

        <!-- 修改/创建时间 -->
        <el-table-column
          :label="$t('pages.activityTemplateManage.table.updatedCreatedTime')"
          prop="config.createTime"
          align="center"
          min-width="200"
        >
          <template slot-scope="scope">
            <div>{{ $t('pages.activityTemplateManage.label.update') }}: {{ scope.row.config.updateTime | dateFormat }}</div>
            <div>{{ $t('pages.activityTemplateManage.label.create') }}: {{ scope.row.config.createTime | dateFormat }}</div>
          </template>
        </el-table-column>

        <!-- 操作栏 -->
        <el-table-column fixed="right" :label="$t('pages.activityTemplateManage.table.actions')" align="center" width="80">
          <template slot-scope="scope">
            <el-dropdown>
              <span class="el-dropdown-link">
                <i class="el-icon-more" />
              </span>
              <el-dropdown-menu slot="dropdown">
                <!-- 未开始/已开始:编辑,已结束:查看 -->
                <el-dropdown-item @click.native="clickEdit(scope.row)">
                  {{
                    scope.row.status !== 2 ? $t("pages.activityTemplateManage.action.edit") : $t("pages.activityTemplateManage.action.view")
                  }}</el-dropdown-item
                >

                <!-- 已开始/已结束:排行榜 -->
                <el-dropdown-item
                  v-if="scope.row.status !== 0"
                  @click.native="clickRank(scope.row)"
                >
                  {{ $t('pages.activityTemplateManage.action.ranking') }}
                </el-dropdown-item>

                <!-- 未开始/已开始:编辑模版 -->
                <el-dropdown-item
                  v-if="scope.row.status !== 2"
                  @click.native="clickEditTemplate(scope.row)"
                >
                  {{ $t('pages.activityTemplateManage.action.editTemplate') }}
                </el-dropdown-item>

                <!-- 复制活动 -->
                <el-dropdown-item @click.native="clickCopyActivity(scope.row)">
                  {{ $t('pages.activityTemplateManage.action.copyActivity') }}
                </el-dropdown-item>

                <!-- 已结束:发送奖品 -->
                <el-dropdown-item
                  v-if="scope.row.status === 2"
                  @click.native="clickSendReward(scope.row)"
                >
                  {{
                    scope.row.config.awardStatus === true
                      ? $t("pages.activityTemplateManage.action.rewardRecord")
                      : $t("pages.activityTemplateManage.action.sendReward")
                  }}
                </el-dropdown-item>

                <!-- 复制活动ID -->
                <el-dropdown-item
                  @click.native="copyContent(scope.row.config.id)"
                >
                  {{ $t('pages.activityTemplateManage.action.copyActivityId') }}
                </el-dropdown-item>

                <!-- 复制模版ID -->
                <el-dropdown-item
                  @click.native="copyContent(scope.row.config.templateId)"
                >
                  {{ $t('pages.activityTemplateManage.action.copyTemplateId') }}
                </el-dropdown-item>

                <!-- 复制活动链接 -->
                <el-dropdown-item @click.native="clickActivityLink(scope.row)">
                  {{ $t('pages.activityTemplateManage.action.copyActivityLink') }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 加载模块 -->
      <div v-if="listQuery.lastId" class="load-more">
        <span v-if="notData">{{ $t('pages.activityTemplateManage.word.loadedAll') }}</span>
        <el-button
          v-else
          size="mini"
          :disabled="loadMoreLoading"
          :loading="loadMoreLoading"
          @click="clickLoadMore"
          >{{ $t('pages.activityTemplateManage.action.loadMore') }}</el-button
        >
      </div>

      <form-edit
        v-if="formEditVisible"
        :row="thatRow"
        :sys-origin="listQuery.sysOrigin"
        @close="formEditVisible = false"
        @success="formEditSuccess"
      />

      <activity-rank-reward
        v-if="activityRankRewardVisible"
        :row="thatRow"
        @close="activityRankRewardVisible = false"
      />

      <activity-rank
        v-if="activityRankVisible"
        :row="thatRow"
        @close="activityRankVisible = false"
      />
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { copyText, deepClone } from "@/utils";

import { listActivityConf } from "@/api/sys";

import FormEdit from "./form-edit";
import ActivityRankReward from "./activity-rank-reward";
import ActivityRank from "./activity-rank";

export default {
  components: { FormEdit, ActivityRankReward, ActivityRank },
  data() {
    return {
      activityRankVisible: false,
      activityRankRewardVisible: false,
      list: [],
      listLoading: true,
      templatId: "",
      formEditVisible: false,
      thatRow: {},
      notData: false,
      loadMoreLoading: false,
      txtVal: 0,
      activeGiftId: "",
      pushTextHistoryLoading: false,
      pushTextHistoryVisible: false,
      pushTextHistory: [],
      delarr: [],
      listQuery: {
        limit: 20,
        lastId: "",
        id: "",
        sysOrigin: "",
        showcase: 1,
        templateId: ""
      },
      textOptTitle: ""
    };
  },

  computed: {
    ...mapGetters(["permissionsSysOriginPlatforms"])
  },

  created() {
    const that = this;
    const querySystem = this.permissionsSysOriginPlatforms[0];
    if (!querySystem) {
      return;
    }
    that.listQuery.sysOrigin = querySystem.value;
    that.renderData(true);
  },

  methods: {
    renderData(isClean) {
      const that = this;
      if (isClean === true) {
        this.listQuery.lastId = "";
        this.list = [];
      }
      that.listLoading = true;
      listActivityConf(that.listQuery)
        .then(res => {
          that.listLoading = false;
          that.loadMoreLoading = false;
          // 网络差的情况, 可能会绕过第一个clean,出现多次concat
          if (isClean === true) {
            this.listQuery.lastId = "";
            this.list = [];
          }
          const { body } = res;
          const list = body || [];
          that.notData = list.length < that.listQuery.limit;
          if (list && list.length > 0) {
            that.list = that.list.concat(list);
            that.listQuery.lastId = that.list[that.list.length - 1].config.id;
          }
        })
        .catch(er => {
          console.error(er);
          that.listLoading = false;
          that.loadMoreLoading = false;
        });
    },

    handleSearch() {
      this.renderData(true);
    },

    clickCreate() {
      this.thatRow = null;
      this.formEditVisible = true;
    },

    copyContent(text) {
      copyText(text)
        .then(() => {
          this.$opsMessage.success();
        })
        .catch(er => {
          this.$opsMessage.fail();
        });
    },

    clickActivityLink(row) {
      this.copyContent(
        `${process.env.VUE_APP_H5_BASE_URL}/#/activity/${row.config.id}`
      );
    },

    clickCopyActivity(row) {
      this.thatRow = deepClone(row);
      this.thatRow.config.id = null;
      this.thatRow.status = 0;
      this.thatRow.config.awardStatus = false;
      if (this.thatRow.config.butOneRewards) {
        this.thatRow.config.butOneRewards.forEach(element => {
          element.rankUsers = [];
          element.status = false;
        });
      }
      if (this.thatRow.config.butTwoRewards) {
        this.thatRow.config.butTwoRewards.forEach(element => {
          element.rankUsers = [];
          element.status = false;
        });
      }
      this.formEditVisible = true;
    },

    clickSendReward(row) {
      this.thatRow = row;
      this.activityRankRewardVisible = true;
    },

    clickRank(row) {
      this.thatRow = row;
      this.activityRankVisible = true;
    },

    clickEditTemplate(row) {
      const that = this;
      that
        .$confirm(
          that.$t("pages.activityTemplateManage.confirm.editTemplateMessage"),
          that.$t("pages.activityTemplateManage.confirm.title"),
          {
            confirmButtonText: that.$t("pages.activityTemplateManage.action.confirm"),
            cancelButtonText: that.$t("pages.activityTemplateManage.action.cancel"),
            type: "warning"
          }
        )
        .then(() => {
          that.$router.push("/activity/template?id=" + row.config.templateId);
        })
        .catch(() => {});
    },

    clickEdit(row) {
      this.thatRow = row;
      this.formEditVisible = true;
    },

    formEditSuccess() {
      this.formEditVisible = false;
      this.renderData(true);
    },

    clickLoadMore() {
      const that = this;
      that.loadMoreLoading = true;
      that.renderData();
    }
  }
};
</script>

<style scoped lang="scss">
.popover-content {
  max-width: 300px;
  line-height: 20px;
}

.load-more {
  padding: 20px;
  text-align: center;
}
</style>
