<template>
    <el-card shadow="never" class="aui-card--fill">
        <div class="mod-home">
          <div class="title">活动列表</div>
          <el-row :gutter="20" style="margin-top: 20px;">
            <el-col :span="6" class="adfac">
              <div class="query_text">活动类型</div>
              <el-select v-model="queryParams.typeId" placeholder="请选择活动类型" class="select-box" style="width: 100%;" clearable>
                <el-option v-for="item in typeOptions" :key="item.id" :label="item.typeName" :value="item.id"></el-option>
              </el-select>
            </el-col>
            <el-col :span="6" class="adfac">
              <div class="query_text">活动分类</div>
              <el-select v-model="queryParams.categoryId" placeholder="请选择活动分类" class="select-box" style="width: 100%;" clearable>
                <el-option v-for="item in categoryOptions" :key="item.id" :label="item.categoryName" :value="item.id"></el-option>
              </el-select>
            </el-col>
          </el-row>
          <el-row :gutter="20" style="margin-top: 20px;">
            <el-col :span="6" class="adfac">
              <div class="query_text">活动名称</div>
              <el-input v-model="queryParams.activityName" placeholder="请输入活动名称" class="input-box" clearable></el-input>
            </el-col>
            <el-col :span="6" class="adfac">
              <div class="query_text">活动时间</div>
              <el-date-picker v-model="queryParams.startEndDate" @change="handleDateChange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%;"></el-date-picker>
            </el-col>
            <el-col :span="12" class="adfac">
                <el-button type="default" @click="handleReset">重置</el-button>
                <el-button type="primary" @click="getList">查询</el-button>
                <el-button type="primary" @click="handleAdd" v-if="$hasPermission('core:activity:save')">新增活动</el-button>
            </el-col>
          </el-row>
          <el-table :data="dataList" border cell-class-name="vertical-top-cell" v-loading="loading" empty-text="暂无活动" style="margin-top: 24px;">
              <el-table-column prop="id" label="活动ID" width="200"></el-table-column>
              <el-table-column prop="activityName" label="活动名称" width="350"></el-table-column>
              <el-table-column prop="typeName" label="活动类型" width="120"></el-table-column>
              <el-table-column prop="categoryName" label="活动分类" width="120"></el-table-column>
              <el-table-column prop="" label="报名时间" width="320">
                <template #default="scope">{{ scope.row.signupStartTime }} - {{ scope.row.signupEndTime }}</template>
              </el-table-column>
              <el-table-column prop="" label="报名人数" width="120">
                <template #default="scope">
                  <div class="adfac"><span style="color: #00AE57;">{{ scope.row.recruitmentNow||0 }}</span>/{{ scope.row.recruitmentMax||'无限制' }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="totalLoveValue" label="总爱心值" width="120">
                <template #default="scope">
                  {{ scope.row.totalLoveValue||0 }}
                </template>
              </el-table-column>
              <el-table-column prop="" label="上下架" width="120">
                <template #default="scope">
                  <span v-if="scope.row.state==1" style="color: #00AE57;">已上架</span>
                  <span v-if="scope.row.state==0">已下架</span>
                </template>
              </el-table-column>
              <el-table-column prop="activeState" label="活动状态" width="150">
                <template #default="scope">
                  <div class="as" :class="activeStateColorDict[scope.row.activeState]||'grey'">{{ activeStateCfg[scope.row.activeState] || '未知' }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="" label="活动时间" width="320">
                <template #default="scope">{{ scope.row.activityStartTime }} - {{ scope.row.activityEndTime }}</template>
              </el-table-column>
              <el-table-column prop="channelName" label="渠道方" width="120"></el-table-column>
              <el-table-column prop="organizerName" label="举办方" width="120" show-overflow-tooltip></el-table-column>
              <el-table-column prop="createDate" label="创建时间" width="180"></el-table-column>
              <el-table-column label="操作" width="300" fixed="right">
                  <template #default="scope">
                      <!-- <el-button link type="text" @click="handleEdit(scope.row)" v-if="scope.row.activeState!=3&&$hasPermission('core:activity:update')">编辑</el-button> -->
                      <el-button link type="text" @click="handleEdit(scope.row)" v-if="scope.row.activeState<2&&$hasPermission('core:activity:update')">编辑</el-button>
                      <el-button link type="text" @click="handleDetail(scope.row)" v-if="$hasPermission('core:activity:detail')&&scope.row.activeState>-2">详情</el-button>
                      <el-button link type="text" @click="handleInfo(scope.row)" v-if="$hasPermission('core:activity:info')&&scope.row.activeState>-2">报名信息</el-button>
                      <el-button link type="text" @click="handleCode(scope.row)" v-if="!scope.row.signCode&&scope.row.activeState==2&&$hasPermission('core:activity:code')">生成签到码</el-button>
                      <el-button link type="text" @click="handleReviewCode(scope.row)" v-if="scope.row.signCode&&scope.row.activeState==2&&$hasPermission('core:activity:code')">查看签到码</el-button>
                      <!-- <el-button link type="text" @click="handleUpDown(scope.row,0)" v-if="scope.row.state==1&&(scope.row.activeState==0||scope.row.activeState==3)&&$hasPermission('core:activity:updown')">下架</el-button> -->
                      <el-button link type="text" @click="handleUpDown(scope.row,0)" v-if="scope.row.state==1&&$hasPermission('core:activity:updown')&&scope.row.activeState>-2">下架</el-button>
                      <el-button link type="text" @click="handleUpDown(scope.row,1)" v-if="scope.row.state==0&&$hasPermission('core:activity:updown')&&scope.row.activeState>-2">上架</el-button>
                      <el-button link type="text" @click="handleCancel(scope.row)" v-if="$hasPermission('core:activity:cancel')&&scope.row.activeState!=-1&&(Date.parse(new Date())>Date.parse(scope.row.signupEndTime)&&Date.parse(new Date())<Date.parse(scope.row.activityStartTime))">取消</el-button>
                      <el-button link type="text" @click="handleDelete(scope.row)" v-if="($hasPermission('core:activity:delete')&&scope.row.state==0&&scope.row.activeState==0)||($hasPermission('core:activity:delete')&&scope.row.activeState==-2)">删除</el-button>
                  </template>
              </el-table-column>
            </el-table>
            <el-pagination
              :current-page="queryParams.page"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="queryParams.limit"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="pageSizeChangeHandle"
              @current-change="pageCurrentChangeHandle">
            </el-pagination>
        </div>
        <el-dialog width="600px" :visible.sync="show" title="签到码" @close="cancel">
          <div class="code-img adffcacjc">
            <img :src="signCodeUrl">
          </div>
          <div class="demo-drawer__footer" style="display: flex;justify-content: end;margin-top: 50px;">
            <el-button type="primary" @click="downloadImg">下 载</el-button>
            <el-button @click="cancel" style="margin-right: 5%;">取 消</el-button>
          </div>
        </el-dialog>
    </el-card>
</template>

<script>
import moment from 'moment'
export default {
  data () {
    return {
      activeStateCfg: {
        '-2': '草稿',
        '-1': '已取消',
        0: '未开始',
        1: '报名中',
        2: '进行中',
        3: '已结束'
      },
      activeStateColorDict: {
        '-2': 'grey',
        '-1': 'grey',
        0: 'red',
        1: 'yellow',
        2: 'blue',
        3: 'grey'
      },
      typeOptions: [],
      categoryOptions: [],
      queryParams: {
        page: 1,
        limit: 10,
        typeId: '',
        categoryId: '',
        activityName: '',
        startEndDate: '',
        startDate: '',
        endDate: ''
      },
      total: 0,
      dataList: [],
      loading: false,
      show: false,
      signCodeUrl: ''
    }
  },
  created () {
    this.getTypeOptions()
    this.getCategoryOptions()
  },
  mounted () {
    this.getList()
  },
  methods: {
    getList () {
      this.loading = true
      let { startEndDate, ...newParams } = JSON.parse(JSON.stringify(this.queryParams))
      this.$http.get('/core/activity/page', { params: newParams }).then(res => {
        if (res.data.code !== 0) return this.$message.error(res.data.msg)
        this.dataList = res.data.data.list || []
        this.total = res.data.data.total || 0
        this.loading = false
      })
    },
    handleReset () {
      this.queryParams = {
        page: 1,
        limit: 10,
        typeId: '',
        categoryId: '',
        activityName: '',
        startEndDate: '',
        startDate: '',
        endDate: ''
      }
      this.getList()
    },
    pageSizeChangeHandle (val) {
      this.queryParams.limit = val
      this.getList()
    },
    pageCurrentChangeHandle (val) {
      this.queryParams.page = val
      this.getList()
    },
    handleDateChange (val) {
      this.queryParams.startDate = moment(val[0]).format('YYYY-MM-DD')
      this.queryParams.endDate = moment(val[1]).format('YYYY-MM-DD')
    },
    getTypeOptions () {
      this.$http.get('/core/activity/type/page', { params: { page: 1, limit: -1 } }).then(res => {
        this.typeOptions = res.data.data.list || []
      })
    },
    getCategoryOptions () {
      this.$http.get('/core/activity/category/page', { params: { page: 1, limit: -1 } }).then(res => {
        this.categoryOptions = res.data.data.list || []
      })
    },
    handleAdd () {
      this.$router.push({ name: 'activityAdd' })
    },
    handleEdit (row) {
      this.$router.push({ name: 'activityAdd', query: { id: row.id } })
    },
    handleDetail (row) {
      this.$router.push({ name: 'activityDetail', query: { id: row.id } })
    },
    handleInfo (row) {
      this.$router.push({ name: 'activityApplyInfo', query: { id: row.id } })
    },
    handleCode (row) {
      this.$http.get('/core/activity/genSignCode/' + row.id).then(res => {
        if (res.data.code !== 0) return this.$message.error(res.data.msg)
        this.$message.success('生成成功')
        this.getList()
      })
    },
    handleReviewCode (row) {
      this.show = true
      this.signCodeUrl = row.signCode
    },
    cancel () {
      this.show = false
    },
    downloadImg () {
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = this.signCodeUrl
      link.setAttribute('download', '签到码')
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      this.show = false
    },
    handleUpDown (row, state) {
      if ([0, 1, 2].includes(row.activeState) && row.recruitmentNow > 0) return this.$message.error(`当前活动已存在报名人数，无法${state ? '上架' : '下架'}`)
      this.$confirm(`是否确认${state ? '上架' : '下架'}活动【${row.activityName}】?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.post('/core/activity/updState', { id: row.id, state }).then(res => {
          if (res.data.code !== 0) return this.$message.error(res.data.msg)
          this.$message.success((state ? '上架' : '下架') + '成功')
          this.getList()
        })
      })
    },
    handleCancel (row) {
      this.$confirm(`是否确认取消活动【${row.activityName}】?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.get(`core/activity/cancelEvent/${row.id}`).then(res => {
          if (res.data.code !== 0) return this.$message.error(res.data.msg)
          this.$message.success('取消成功')
          this.getList()
        })
      }).catch(() => {})
    },
    handleDelete (row) {
      this.$confirm(`是否确认删除活动【${row.activityName}】?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete('/core/activity', { 'data': [row.id] }).then(res => {
          if (res.data.code !== 0) return this.$message.error(res.data.msg)
          this.$message.success('删除成功')
          this.getList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style scoped lang="scss">
  .title{
    font-family: PingFang-SC, PingFang-SC;
    font-weight: bold;
    font-size: 16px;
    color: #252525;
    line-height: 22px;
  }

  .query_text{
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: #393939;
    line-height: 20px;
    width: 80px;
    margin-right: 16px;
  }

  .as{
    width: 58px;
    height: 24px;
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: #646464;
    line-height: 24px;
    text-align: center;
    background: #F7F7F7;
    border-radius: 6px;
    display: inline-block;
    &.blue{
      background: rgba(46,105,235,0.08);
      color: #2E69EB;
    }
    &.red{
      background: rgba(253,79,102,0.11);
      color: #FD4F66;
    }
    &.yellow{
      background: rgba(255,152,10,0.08);
      color: #FF980A;
    }
  }

  .code-img{
    width: 100%;
    height: 500px;
    img{
      width: 100%;
      height: auto;
    }
  }
</style>
