<template>
  <div class="app-container calendar-list-container" v-loading.body="showLoadingBody">
    <div>
      <el-table :key='tableKey' :data="list" border fit highlight-current-row style="width: 100%;">
        <el-table-column type="index" align="center" label="活动ID" width="100">
          <template slot-scope="scope">
            <span>{{scope.row.id}}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="活动名称">
          <template slot-scope="scope">
            <span>{{scope.row.name}}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="活动时间" width="400">
          <template slot-scope="scope">
              <div v-if="scope.row.title">永久</div>
              <div v-else><span>{{scope.row.startTimeStr}}</span> ~ <span>{{scope.row.endTimeStr}}</span></div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="人数限制">
          <template slot-scope="scope">
            <span>{{scope.row.numLimit}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="已参加人数">
          <template slot-scope="scope">
            <span>{{scope.row.hasJoinNum}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="状态" width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.status==1">上架</span>
            <span v-if="scope.row.status==2">下架</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="200"  fixed="right">
            <template slot-scope="scope">
                <el-button size="small" class="el-button el-button--text el-button--small" v-if="activity_btn_update" @click="handleUpdate(scope.row)">编辑</el-button>
                <el-button size="small" class="el-button el-button--text el-button--small" @click="handleActivityData(scope.row)">活动数据</el-button>
            </template>
        </el-table-column>
      </el-table>
      <div v-show="!listLoading" class="pagination-container">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                       :current-page.sync="listQuery.page" :page-sizes="[10,20,30,40,50]" :page-size="listQuery.limit"
                       layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
      </div>
    </div>
    <el-dialog title="编辑" :visible.sync="newPeopelVisible">
		  <el-form :model="formdata" :rules="rules" ref="form" >
        <div style="font-weight: bold;margin-bottom:20px">基础设置</div>
			  <el-row>
          <el-col :span="5">
            <el-form-item label="活动状态" label-width="70px">
              <el-radio-group v-model="formdata.status_name" size="medium">
                <el-radio-button label="上架"></el-radio-button>
                <el-radio-button label="下架"></el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="参与人数" label-width="80px" prop="numLimit">
              <el-input v-model="formdata.numLimit" placeholder="参与人数"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="活动开始/结束时间"  label-width="130px" style="padding-left:8px" required>
              <el-col :span="11">
                <el-form-item prop="starTimeStr">
                  <el-date-picker v-model="formdata.starTimeStr" type = "datetime" placeholder = "开始时间" value-format=" yyyy-MM-dd HH:mm" format="yyyy-MM-dd HH:mm" :picker-options="pickerOptionsStart"></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col class="line" :span="2"><span style="padding-left:18px">-</span></el-col>
              <el-col :span="11">
                <el-form-item prop="endTimeStr">
                  <el-date-picker v-model="formdata.endTimeStr" type = "datetime" placeholder = "结束时间" value-format=" yyyy-MM-dd HH:mm" format="yyyy-MM-dd HH:mm" :picker-options="pickerOptionsEnd"></el-date-picker>
                </el-form-item>
              </el-col>
            </el-form-item>
          </el-col>
        </el-row>
		  </el-form>
      <div slot="footer"  class="dialog-footer">
        <el-button type="primary" @click="update('form')">确定</el-button>
      </div>
	  </el-dialog>

    <!-- 新人活动 -->
    <el-dialog title="活动数据" :visible.sync="newPeopelDataVisible">
		  <el-form :model="newPeopelDataQuery" style="margin-bottom:20px">
			  <el-row>
          <el-date-picker v-model="newPeopelDataQuery.starTimeStr" type = "datetime" placeholder = "开始时间" value-format=" yyyy-MM-dd HH:mm" format="yyyy-MM-dd HH:mm"></el-date-picker>
          <span> - </span>
          <el-date-picker v-model="newPeopelDataQuery.endTimeStr" type = "datetime" placeholder = "结束时间" value-format=" yyyy-MM-dd HH:mm" format="yyyy-MM-dd HH:mm" :picker-options="newPeopelpickerOptionsEnd"></el-date-picker>
          <el-button class="filter-item" type="primary" v-waves icon="search" @click="handleNewPeopelFilter" style="margin-left:20px">搜索</el-button>
        </el-row>
		  </el-form>
      <el-table :key='newPeopeltableKey' :data="newPeopelDataList" border fit highlight-current-row style="width: 100%;">
          <el-table-column type="index" align="center" label="数据描述" width="200">
            <template slot-scope="scope">
              <span>{{scope.row.behavior}}</span>
            </template>
          </el-table-column>

          <el-table-column align="center" label="pv(总)">
            <template slot-scope="scope">
              <span>{{scope.row.p_count}}</span>
            </template>
          </el-table-column>

          <el-table-column align="center" label="pv(日均)">
            <template slot-scope="scope">
                <span>{{scope.row.p_avg_count}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="uv(总)">
            <template slot-scope="scope">
              <span>{{scope.row.u_count}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="uv(日均)">
            <template slot-scope="scope">
              <span>{{scope.row.u_avg_count}}</span>
            </template>
          </el-table-column>
        </el-table>
        <!-- <div class="pagination-container">
          <el-pagination @size-change="newPeopelDataSizeChange" @current-change="newPeopelDataCurrentChange"
                        :current-page.sync="newPeopelDataQuery.page" :page-sizes="[10,20,30,40,50]" :page-size="newPeopelDataQuery.limit"
                        layout="total, sizes, prev, pager, next, jumper" :total="newPeopelDataTotal"></el-pagination>
        </div> -->
	  </el-dialog>


    <!-- 邀请有礼活动 -->
    <el-dialog title="活动数据" :visible.sync="shareDataVisible">
		  <el-form :model="shareDataQuery" style="margin-bottom:20px">
			  <el-row>
          <el-date-picker v-model="shareDataQuery.starTimeStr" type = "datetime" placeholder = "开始时间" value-format=" yyyy-MM-dd HH:mm" format="yyyy-MM-dd HH:mm"></el-date-picker>
          <span> - </span>
          <el-date-picker v-model="shareDataQuery.endTimeStr" type = "datetime" placeholder = "结束时间" value-format=" yyyy-MM-dd HH:mm" format="yyyy-MM-dd HH:mm" :picker-options="shareDatapickerOptionsEnd"></el-date-picker>
          <el-button class="filter-item" type="primary" v-waves icon="search" @click="handleShareDataFilter" style="margin-left:20px">搜索</el-button>
        </el-row>
		  </el-form>
      <el-table :key='shareDatatableKey' :data="shareDataList" border fit highlight-current-row style="width: 100%;">
          <el-table-column type="index" align="center" label="数据描述" width="200">
            <template slot-scope="scope">
              <span>{{scope.row.behavior}}</span>
            </template>
          </el-table-column>

          <el-table-column align="center" label="pv(总)">
            <template slot-scope="scope">
              <span>{{scope.row.p_count}}</span>
            </template>
          </el-table-column>

          <el-table-column align="center" label="pv(日均)">
            <template slot-scope="scope">
                <span>{{scope.row.p_avg_count}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="uv(总)">
            <template slot-scope="scope">
              <span>{{scope.row.u_count}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="uv(日均)">
            <template slot-scope="scope">
              <span>{{scope.row.u_avg_count}}</span>
            </template>
          </el-table-column>
        </el-table>
        <!-- <div class="pagination-container">
          <el-pagination @size-change="shareDataSizeChange" @current-change="shareDataCurrentChange"
                        :current-page.sync="shareDataQuery.page" :page-sizes="[10,20,30,40,50]" :page-size="shareDataQuery.limit"
                        layout="total, sizes, prev, pager, next, jumper" :total="shareDataTotal"></el-pagination>
        </div> -->
	  </el-dialog>
  </div>
</template>

<script>
  import {
    formatDate
  } from 'utils/dateFormattor';

  import {
    toEast8Date,
    deepCopyDate,
    newEast8Date,
    convertDate2Str,
    timestamp2Date,
    getYMD_hm
  } from 'utils/dateUtils';

  import rsCode from '../../utils/rsCode';

  import {mapGetters} from 'vuex';
  import {
    getToken
  } from 'utils/auth';
  import {
    activityList,
    getObj,
    editObj,
    getActivityData
  } from 'api/activityManagement';
  import Element1 from "../admin/menu/components/element";
  import ElRow from "element-ui/packages/row/src/row";
  import ElCol from "element-ui/packages/col/src/col";

  export default {
    name: 'conponList',
    components: {
      ElCol,
      ElRow,
      Element1,
    },
    data() {
      return {
        rules:{
            numLimit: {
                required: true,
                message: '请输入参与人数',
            },
            starTimeStr:{
                required: true,
                message: '请输入起始时间',
            },
            endTimeStr:{
                required: true,
                message: '请输入结束时间',
            }
        },
        newPeopelVisible:false,
        newPeopelDataVisible:false,
        shareDataVisible:false,
        BASE_API: process.env.BASE_API,
        showLoadingBody: false,
        list: null,
        total: null,
        shareDataList : null,
        shareDataTotal : null,
        newPeopelDataList : null,
        newPeopelDataTotal : null,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20,
        },
        newPeopelDataQuery:{
          page: 1,
          limit: 20,
          activityId:'',
          starTimeStr:'',
          endTimeStr:''
        },
        shareDataQuery:{
          page: 1,
          limit: 20,
          activityId:'',
          starTimeStr:'',
          endTimeStr:''
        },
        inline: true,
        tableKey: 0,
        newPeopeltableKey:1,
        shareDatatableKey:2,
        formdata:{},
        //编辑
        pickerOptionsStart: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7;
          }
        },
        pickerOptionsEnd: {
            disabledDate: time => {
                const beginDateVal = new Date(this.formdata.starTimeStr).getTime()
                if (beginDateVal) {
                    return time.getTime() < beginDateVal - 8.64e7
                }
            }
        },
        //邀请有礼活动数据弹窗
        shareDatapickerOptionsStart:{
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7;
          }
        },
        shareDatapickerOptionsEnd: {
            disabledDate: time => {
                const beginDateVal = new Date(this.shareDataQuery.starTimeStr).getTime()
                if (beginDateVal) {
                    return time.getTime() < beginDateVal - 8.64e7
                }
            }
        },
        //新人活动数据弹窗
        newPeopelpickerOptionsStart:{
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7;
          }
        },
        newPeopelpickerOptionsEnd: {
            disabledDate: time => {
                const beginDateVal = new Date(this.newPeopelDataQuery.starTimeStr).getTime()
                if (beginDateVal) {
                    return time.getTime() < beginDateVal - 8.64e7
                }
            }
        },
        activity_btn_update:false,
      }
    },
    created() {
      this.activity_btn_update = this.elements['activity:btn:update'];
      this.getList();
    },
    computed: {
      ...mapGetters([
        'elements'
      ])
    },
    methods: {
      /**
       * 获取活动列表
       * */
      getList() {
        this.listLoading = true;
        activityList(this.listQuery).then(response => {
          let totalCountRs = undefined;
          let listRs = undefined;
          if (!this.$utils.isEmpty(response.data.list) && this.$utils.isInteger(response.data.total)) {
            listRs = response.data.list;
            response.data.list.map(function(item){
              item.startTimeStr = timestamp2Date(item.startTime);
              item.endTimeStr = timestamp2Date(item.endTime);
            });
            totalCountRs = response.data.total;
          }
          this.listLoading = false;
          this.list = listRs;
          this.total = totalCountRs;
        })

      },
      handleSizeChange(val) {
        this.listQuery.limit = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.page = val;
        this.getList();
      },

      //新人活动-活动数据弹窗
      handleNewPeopelFilter() {
        this.newPeopelDataQuery.page = 1;
        this.getNewPeopelDataList();
      },
      newPeopelDataSizeChange(val) {
        this.newPeopelDataQuery.limit = val;
        this.getNewPeopelDataList();
      },
      newPeopelDataCurrentChange(val) {
        this.newPeopelDataQuery.page = val;
        this.getNewPeopelDataList();
      },
      getNewPeopelDataList(){
        var that =this;
        this.listLoading = true;
        if(this.newPeopelDataQuery.starTimeStr||this.newPeopelDataQuery.endTimeStr){
          if(new Date(this.newPeopelDataQuery.endTimeStr).getTime()<new Date(this.newPeopelDataQuery.starTimeStr).getTime()){
            this.$notify({
              title: '警告',
              message: '结束时间不能小于起始时间',
              type: 'warning',
              duration: 2000
            });
            return false;
          }
        }
        this.newPeopelDataQuery.startTime = this.newPeopelDataQuery.starTimeStr?new Date(this.newPeopelDataQuery.starTimeStr).getTime():''
        this.newPeopelDataQuery.endTime = this.newPeopelDataQuery.endTimeStr?new Date(this.newPeopelDataQuery.endTimeStr).getTime():''
        getActivityData(this.newPeopelDataQuery).then(response => {
          let listRs = undefined;
          listRs = response.data;
          this.newPeopelDataList = listRs;
        })
      },

      //邀请有礼-活动数据弹窗
      handleShareDataFilter() {
        this.shareDataQuery.page = 1;
        this.getShareDataList();
      },
      shareDataSizeChange(val) {
        this.shareDataQuery.limit = val;
        this.getShareDataList();
      },
      shareDataCurrentChange(val) {
        this.shareDataQuery.page = val;
        this.getShareDataList();
      },
      getShareDataList(){
        var that =this;
        this.listLoading = true;
        if(this.shareDataQuery.starTimeStr||this.shareDataQuery.endTimeStr){
          if(new Date(this.shareDataQuery.endTimeStr).getTime()<new Date(this.shareDataQuery.starTimeStr).getTime()){
            this.$notify({
              title: '警告',
              message: '结束时间不能小于起始时间',
              type: 'warning',
              duration: 2000
            });
            return false;
          }
        }
        this.shareDataQuery.startTime = this.shareDataQuery.starTimeStr?new Date(this.shareDataQuery.starTimeStr).getTime():''
        this.shareDataQuery.endTime = this.shareDataQuery.endTimeStr?new Date(this.shareDataQuery.endTimeStr).getTime():''
        getActivityData(this.shareDataQuery).then(response => {
          let listRs = undefined;
          listRs = response.data;
          this.shareDataList = listRs;
        })
      },

      handleUpdate(row){
          var that = this;
          getObj(row.id).then(response => {
            var item = response.data;
            item.status_name = item.status==1?"上架":item.status==2?"下架":'';
            if(item.startTime>0){
              item.starTimeStr = getYMD_hm(item.startTime);
            }else{
              item.startTimeStr = '';
            }
            if(item.endTime>0){
              item.endTimeStr = getYMD_hm(item.endTime);
            }else{
              item.endTimeStr = '';
            }
            this.formdata = item;
            console.log(this.formdata)
            that.newPeopelVisible = true;
          })

      },
      handleActivityData(row){
        // 1--新人尊享; 2--推广活动表
        if(row.type==1){
          this.newPeopelDataQuery={
            page: 1,
            limit: 20,
            activityId:row.id,
            starTimeStr:'',
            endTimeStr:''
          }
          this.getNewPeopelDataList();
          this.newPeopelDataVisible = true;
        }
        if(row.type==2){
          this.shareDataQuery={
            page: 1,
            limit: 20,
            activityId:row.id,
            starTimeStr:'',
            endTimeStr:''
          }
          this.getShareDataList();
          this.shareDataVisible = true;
        }
      },
      /**
       * 编辑-更新
       * */
      update(formName) {
        let that = this;
        const set = this.$refs;
        set[formName].validate(valid => {
          if (valid) {
            that.formdata.status = that.formdata.status_name=='上架'?1:that.formdata.status_name=='下架'?2:'';
            that.formdata.startTime = new Date(this.formdata.starTimeStr).getTime();
            that.formdata.endTime = new Date(this.formdata.endTimeStr).getTime();
            if(new Date(this.formdata.endTimeStr).getTime()<new Date(this.formdata.starTimeStr).getTime()){
              this.$notify({
                title: '警告',
                message: '结束时间不能小于起始时间',
                type: 'warning',
                duration: 2000
              });
              return false;
            }
            editObj(this.formdata).then(response => {
              if (response.status === 200) {
                this.newPeopelVisible = false;
                this.getList();
                this.$notify({
                  title: '成功',
                  message: '编辑成功',
                  type: 'success',
                  duration: 2000
                });
              } else {
                this.$notify({
                  title: '失败',
                  message: rsCode.msg[response.code] ? rsCode.msg[response.code] : '操作失败！',
                  type: 'error',
                  duration: 2000
                });
              }
            });
          } else {
            return false;
          }
        });
      },
    }
  }
</script>
