<template>
  <div class="orderManage app-container">
    <div class="search">
      <div>
        <el-input v-model="query.id" size="small" placeholder="请输入完整激活ID" class="item-width-200"></el-input>
        <el-input v-model="query.serialNumber" size="small" placeholder="请输入激活码" class="item-width-200 ml10"></el-input>
        <el-input v-model="query.phone" size="small" placeholder="请输入激活手机号" class="item-width-200 ml10"></el-input>
        <el-date-picker v-model="date" size="small" value-format="yyyy-MM-dd" class="item-width-350 ml10"
          type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
        <el-select v-model="query.state" size="small" clearable class="item-width-200 ml10" placeholder="请选择状态">
          <el-option label="待使用" value="1"></el-option>
          <el-option label="激活成功" value="2"></el-option>
        </el-select>
        <el-button class="ml10" type="primary" size="small" icon="el-icon-search" @click="handleSearch">
          搜索
        </el-button>
        <el-button class="ml10" type="info" size="small" :loading="downloadLoading" icon="el-icon-printer"
          @click="exportAllExcel">
          导出
        </el-button>
      </div>
      <el-button class="ml10" type="info" size="small" plain icon="el-icon-back" @click="comeBack">
        返回
      </el-button>
    </div>
    <el-descriptions class="margin-top" :column="3" border>
      <el-descriptions-item>
        <template slot="label"> 计费号 </template>
        {{ groupInfos.billId || '--' }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label"> 集团名称 </template>
        {{ groupInfos.groupName || '--' }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label"> 订购数量 </template>
        {{ groupInfos.orderNum || '--' }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label"> 所属平台 </template>
        慧研学惠生活
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label"> 订购产品策划名称 </template>
        {{ groupInfos.groupPlanName || '--' }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label"> 激活码数量 </template>
        {{ groupInfos.totalTicket || '--' }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label"> 已使用数量 </template>
        {{ groupInfos.useTicket || '--' }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label"> 未使用数量 </template>
        {{ groupInfos.totalTicket - groupInfos.useTicket || '--' }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template slot="label"> 激活失败 </template>
        {{ '--' }}
      </el-descriptions-item>
    </el-descriptions>
    <div style="height: 20px;"></div>
    <el-table :data="tableData" tooltip-effect="dark" border v-loading="loading" style="width: 100%">
      <el-table-column align="center" label="激活ID" prop="id" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="serialNumber" align="center" label="激活码" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="planningName" align="center" label="会员套餐" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="goodsAmount" align="center" label="有效期类型" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-if="scope.row.activationType == 1">时间段</span>
          <span v-else>天数</span>
        </template>
      </el-table-column>
      <el-table-column prop="activationDay" align="center" label="时间段/天数" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-if="scope.row.activationType == 1">{{ timeFormat(scope.row.startTime) }}至{{
            timeFormat(scope.row.endTime) }}</span>
          <span v-else>
            {{ scope.row.activationDay+'天' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="startTime" align="center" label="创建时间" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ timeFormat(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="状态" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-if="scope.row.phone == null">待使用</span>
          <span v-else>激活成功</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="推送状态" show-overflow-tooltipphone>
        <template slot-scope="scope">
          <span>{{ scope.row.sync === true ? '推送成功' : '--' }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="激活手机号" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.phone || '--' }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="激活时间" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-if="scope.row.phone == null">--</span>
          <span v-else>{{ timeFormat(scope.row.useTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="address" align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" v-if="scope.row.phone == null"
            @click="activationVip(scope.row)">激活</el-button>
          <el-button type="text" size="small" v-else @click="synchronization(scope.row)">同步</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="page-box">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" background
        :current-page="query.page" :page-sizes="[10, 20, 30, 40]" :page-size="query.size"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <el-dialog title="激活" :visible.sync="vipDialogVisible" width="30%" center>
      <div style="margin-left: 32px;margin-bottom: 30px;font-weight: 600;">激活码:{{ vipCode }}</div>
      <el-form :model="updataPhone" ref="updataPhone" :rules="rules" label-width="130px" size="small">
        <el-form-item label="激活手机号：" prop="num">
          <el-input v-model="updataPhone.num" class="item-width-200" placeholder="请输入激活手机号"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="Cancel">取 消</el-button>
        <el-button type="primary" :loading="updataLoading" @click="confirmActivation('updataPhone')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { checkoutActivationCode, labourActivation, syncNotified } from "@/api/common";
import { timeFormat } from "@/utils/index";
import FileSaver from 'file-saver';
import XLSX from 'xlsx';

export default {
  name: "orderManage",
  data() {
    return {
      downloadLoading: false,
      updataLoading: false,
      date: '',
      vipCode: '',
      groupInfos: {},
      updataPhone: {
        num: '',
      },
      rules: {
        num: [
          { required: true, pattern: /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/, message: "请正确输入手机号", trigger: "blur" },
        ],
      },
      vipDialogVisible: false,

      tableData: [],
      loading: false,
      query: {
        id: '',
        phone: "",
        serialNumber: "",
        groupOrderNo: '',
        startTime: "",
        endTime: "",
        state: '',
        page: 1,
        size: 10,
      },
      title: "",
      total: 0,
    };
  },
  watch: {
    date(val) {
      if (val) {
        this.query.startTime = Date.parse(val[0]);
        this.query.endTime = Date.parse(val[1]);
      } else {
        this.query.startTime = "";
        this.query.endTime = "";
      }
    },
  },
  filters: {

  },
  methods: {
    // 同步和校园数据，待完成
    synchronization(item) {
      syncNotified({ ticketId: item.id }).then((res) => {
        if (res.state == "Success") {
          this.getList()
        }
      })
    },

    Cancel() {
      this.vipDialogVisible = false;
      this.updataPhone.num = ''
    },
    // 确认激活
    confirmActivation(formName) {
      this.$refs[formName].validate((valid) => {
        let updata = {
          phone: this.updataPhone.num,
          serialNumber: this.vipCode
        }
        if (valid) {
          this.updataLoading = true;
          labourActivation({ ...updata }).then((res) => {
            this.updataLoading = false
            if (res.state == "Success") {
              this.vipDialogVisible = false
              this.updataPhone.num = ''
              this.getList()
            } else {
            }
          })
        } else {
          return false;
        }
      });
    },

    // 激活弹窗
    activationVip(item) {
      this.vipDialogVisible = true
      this.vipCode = item.serialNumber
    },

    // 返回上一级
    comeBack() {
      this.$router.back()
    },

    // 导出方法
    exportAllExcel() {
      this.downloadLoading = true
      const allData = [];
      let query = JSON.parse(JSON.stringify(this.query))
      query.size = this.total
      query.page = 0
      checkoutActivationCode(query).then(res => {
        this.downloadLoading = false
        if (res.state == "Success") {
          allData.push(...res.content.content);
          this.exportExcel(allData);
        }
      });
    },

    // 导出数据处理
    exportExcel(r) {
      const data = r.map((item) => {
        let createTime=''
        let codeStatus = ''
        let pushSync=''
        let pushTime=''
        if(item.activationType===1){
          createTime = item.startTime+'至'+item.endTime
        }else{
          createTime = item.activationDay+'天'
        }
        if(item.phone==null){
          codeStatus='待使用'
          pushTime='--'
        }else{
          codeStatus='激活成功'
          pushTime=timeFormat(item.useTime)
        }
        if(item.sync==true){
          pushSync='推送成功'
        }else{
          pushSync='--'
        }
        return {
          "激活ID": item.id,
          "激活码": item.serialNumber,
          "会员套餐": item.planningName,
          "有效期类型": item.goodsAmount,
          "时间段/天数": createTime,
          "创建时间":timeFormat(item.createTime),
          "状态": codeStatus,
          "推送状态": pushSync,
          "激活手机号": item.phone||'--',
          "激活时间": pushTime,
        }
      })
      const worksheet = XLSX.utils.json_to_sheet(data);
      const workbook = { Sheets: { data: worksheet }, SheetNames: ['data'] };
      const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
      const blob = new Blob([excelBuffer], { type: 'application/octet-stream' });
      FileSaver.saveAs(blob, '激活码列表.xlsx');
    },


    handleSearch() {
      this.query.page = 1;
      this.getList();
    },
    timeFormat(val) {
      return timeFormat(val);
    },
    handleSizeChange(val) {
      this.query.page = 1;
      this.query.size = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.query.page = val;
      this.getList();
    },

    search() {
      this.query.page = 1;
      this.getList();
    },
    getList() {
      this.loading = true;
      this.groupInfos = JSON.parse(this.$route.query.groupInfo)
      this.query.groupOrderNo = this.groupInfos.orderNo;
      let obj = JSON.parse(JSON.stringify(this.query));
      obj.page = obj.page - 1;
      if (!obj.orderType) {
        delete obj.orderType;
      }
      checkoutActivationCode(obj).then((res) => {
        this.loading = false;
        if (res.state == "Success") {
          this.tableData = res.content.content;
          this.total = res.content.totalElements;
        }
      });
    },
  },
  created() {
    this.getList();
  },
};
</script>

<style lang="scss"></style>
