<template>
  <div class="ele-body">
    <el-card shadow="never">
      <!-- 搜索表单 -->
      <gro-exchange-search @search="reload" />
      <!-- 数据表格 -->
      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="datasource"
        cache-key="syliveExchangeTable"
      >
        <!-- 表头工具栏 -->
        <template v-slot:toolbar>
          <el-button
            size="small"
            type="primary"
            class="ele-btn-icon"
            icon="el-icon-dexchangeload"
            @click="exportData"
          >
            导出核销
          </el-button>
          <el-button
            size="small"
            icon="el-icon-upload2"
            class="ele-btn-icon"
            @click="openImport"
          >
            导入审核
          </el-button>
        </template>
        <template v-slot:useStatus="{ row }">
          <span
            :class="row.useStatus == 2 ? 'ele-text-success' : 'ele-text-danger'"
          >
            {{ row.useStatusName }}
          </span>
        </template>
        <template v-slot:action="{ row }">
          <el-link
            v-if="row.useStatus != 1"
            type="primary"
            :underline="false"
            icon="el-icon-view"
            @click="openDetail(row)"
          >
            详情
          </el-link>
          <el-popconfirm
            v-if="row.useStatus == 1 && !row.ifAddress"
            class="ele-action"
            title="确定要通过吗？"
            @confirm="remove(row, 2)"
          >
            <template v-slot:reference>
              <el-link
                type="primary"
                :underline="false"
                icon="el-icon-finished"
              >
                通过
              </el-link>
            </template>
          </el-popconfirm>
          <el-link
            v-if="row.useStatus == 1 && row.ifAddress"
            type="primary"
            :underline="false"
            icon="el-icon-finished"
            @click="setStatus(row, 2)"
          >
            通过
          </el-link>
          <el-link
            v-if="row.useStatus == 1"
            type="danger"
            :underline="false"
            icon="el-icon-circle-close"
            @click="setStatus(row, 3)"
          >
            驳回
          </el-link>
        </template>
      </ele-pro-table>
    </el-card>
    <!-- 详情弹窗 -->
    <gro-exchange-detail :visible.sync="showDetail" :data="current" />
    <!-- 导入弹窗 -->
    <gro-exchange-import :visible.sync="showImport" @done="reload" />
    <!-- 审核弹窗 -->
    <gro-exchange-status
      :visible.sync="showStatus"
      :data="currentStatus"
      @done="reload"
    />
  </div>
</template>

<script>
  import { setPageTabTitle } from '@/utils/page-tab-util';
  import GroExchangeSearch from './components/gro-exchange-search.vue';
  import { getActivity } from '@/api/sylive/activity';
  import {
    getGroupsExchangeDetail,
    listGroupsExchange,
    updateGroupsExchangeUseStatus,
    exportGroupsExchange
  } from '@/api/sylive/groups-exchange';
  import { utils, writeFile } from 'xlsx';
  import GroExchangeDetail from './components/gro-exchange-detail.vue';
  import GroExchangeStatus from './components/gro-exchange-status';
  import GroExchangeImport from './components/gro-exchange-import';
  const ROUTE_PATH = '/sylive/groups-exchange';

  export default {
    name: 'syliveGroupsExchange',
    components: {
      GroExchangeImport,
      GroExchangeStatus,
      GroExchangeDetail,
      GroExchangeSearch
    },
    data() {
      return {
        activityId: null,
        // 加载状态
        title: '核销记录',
        loading: true,
        showDetail: false,
        showStatus: false,
        showImport: false,
        current: [],
        currentStatus: {},
        useType: 0,
        // 表格列配置
        columns: []
      };
    },
    methods: {
      /* 删除 */
      remove(row, status) {
        const loading = this.$loading({ lock: true });
        updateGroupsExchangeUseStatus({
          cfId: row.id,
          type: this.useType,
          useStatus: status,
          descrip: ''
        })
          .then((msg) => {
            loading.close();
            this.$message.success(msg);
            this.reload();
          })
          .catch((e) => {
            loading.close();
            this.$message.error(e.message);
          });
      },
      /* 打开导入弹窗 */
      openImport() {
        this.showImport = true;
      },
      /* 详情 */
      openDetail(row) {
        getGroupsExchangeDetail({ cfId: row.id, type: this.useType })
          .then((list) => {
            this.current = list;
          })
          .catch((e) => {
            this.$message.error(e.message);
          });
        this.showDetail = true;
      },
      setStatus(row, status) {
        this.showStatus = true;
        this.currentStatus = {
          cfId: row.id,
          type: this.useType,
          useStatus: status,
          descrip: ''
        };
      },
      /* 表格数据源 */
      async datasource({ page, limit, where, order }) {
        this.useType = where ? where.useType : 0;
        const result = await listGroupsExchange({
          ...where,
          ...order,
          page,
          limit,
          activityId: this.activityId
        });
        if (!order.sort && result.columns) {
          this.columns = result.columns;
        }
        return { count: result.count, list: result.list };
      },
      query() {
        this.loading = true;
        getActivity(Number(this.activityId))
          .then((data) => {
            this.loading = false;
            // 修改页签标题
            if (this.$route.path === ROUTE_PATH) {
              this.title = data.title + '的核销记录';
              setPageTabTitle(this.title);
            }
          })
          .catch((e) => {
            this.loading = false;
            this.$message.error(e.message);
          });
      },
      /* 刷新表格 */
      reload(where) {
        this.useType = where ? where.useType : 0;
        this.$refs.table.reload({ page: 1, where: where });
      },
      /* 导出数据 */
      exportData() {
        const loading = this.$loading({ lock: true });
        this.$refs.table.doRequest(({ where, order }) => {
          const activityId = this.activityId;
          exportGroupsExchange({ ...where, ...order, activityId })
            .then((data) => {
              loading.close();
              const array = [data.columns];
              data.list.forEach((d) => {
                let arrayItem = [];
                for (let key in d) {
                  arrayItem.push(d[key]);
                }
                array.push(arrayItem);
              });
              writeFile(
                {
                  SheetNames: ['Sheet1'],
                  Sheets: {
                    Sheet1: utils.aoa_to_sheet(array)
                  }
                },
                this.title + '.xlsx'
              );
            })
            .catch((e) => {
              loading.close();
              this.$message.error(e.message);
            });
        });
      }
    },
    watch: {
      $route: {
        handler(route) {
          const { path } = route;
          if (path !== ROUTE_PATH) {
            return;
          }
          const activityId = this.$route.query.id;
          if (!activityId || activityId == this.activityId) {
            return;
          }
          this.activityId = activityId;
          this.query();
          if (this.$refs.table) {
            this.$refs.table.reload({ page: 1 });
          }
        },
        immediate: true
      }
    }
  };
</script>
