<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" :size="ELsize" label-width="auto">
      <el-form-item label="优惠券名称" prop="name" label-width="100px">
        <el-input v-model="queryParams.name" placeholder="请输入优惠券名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="用户类型" prop="trait">
        <el-select v-model="queryParams.trait" placeholder="请选择用户类型" clearable size="small" style="width: 240px">
          <el-option label="普通券" :value="0"></el-option>
          <el-option label="新人券" :value="1"></el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="领取时间">
        <el-date-picker v-model="daterangeCreateTime" value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange"
          range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请输入状态" clearable size="small" style="width: 240px">
          <el-option label="上架" :value="true" />
          <el-option label="下架" :value="false" />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" :size="ELsize" @click="handleAdd">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange" :border="TableBorder"
      :size="ELTableSize">
      <el-table-column align="center" prop="code" label="编号">
      </el-table-column>
      <el-table-column prop="name" header-align="center" align="center" label="优惠券名称">
      </el-table-column>
      <el-table-column prop="trait" header-align="center" align="center" label="用户类型">
        <template slot-scope="{ row }">
          <el-tag v-if="row.trait === 0">普通券</el-tag>
          <el-tag v-if="row.trait === 1" type="success">新人券</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="faceValue" header-align="center" align="center" label="优惠金额">
        <template slot-scope="{ row }">
          {{ row.faceValue }}
        </template>
      </el-table-column>
      <el-table-column prop="threshold" header-align="center" align="center" label="使用门槛">
        <template slot-scope="{ row }">
          {{ !row.hasThreshold ? '无' : row.threshold }}
        </template>
      </el-table-column>
      <el-table-column prop="receiveLimit" header-align="center" align="center" label="每人限领张数">
        <template slot-scope="{ row }">
          {{ row.receiveLimit == '-1' ? '不限' : row.receiveLimit }}
        </template>
      </el-table-column>
      <el-table-column prop="issueNumber" header-align="center" align="center" label="剩余张数">
        <template slot-scope="{ row }">
          {{
            row.issueNumber == -1 ? '不限' : row.issueNumber - row.receiveNum
          }}
        </template>
      </el-table-column>
      <el-table-column prop="receiveNum" header-align="center" align="center" label="已领取张数">
        <template slot-scope="{ row }">
          <span class="clickCls"></span>
          <el-button type="text" size="small" @click="seeReceiveList(row)">{{
            row.receiveNum
          }}</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="applyTime" width="170px" header-align="center" align="center" label="可领取时间">
        <template slot-scope="{ row }">
          {{ row.startTime }} 至 {{ row.endTime }}
        </template>
      </el-table-column>
      <el-table-column prop="activeState" header-align="center" align="center" label="领取状态">
        <template slot-scope="{ row }">
          <el-tag v-if="row.activeState === 3">正常</el-tag>
          <el-tag v-if="row.activeState === 4" type="success">已完成</el-tag>
          <el-tag v-if="row.activeState === 2" type="info">已发布</el-tag>
          <el-tag v-if="row.activeState === 1" type="warning">待发布</el-tag>
          <el-tag v-if="row.activeState === 0" type="danger">已终止</el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed="right" header-align="center" align="center" width="150" label="操作">
        <template slot-scope="{ row }">
          <el-button type="text" :size="ELTableSize" v-if="
            row.activeState === 3 ||
            row.activeState === 4 ||
            row.activeState === 0 ||
            row.activeState === 2
          " @click="openDetails('查看', row)">查看详情</el-button>
          <el-button type="text" v-if="row.activeState === 1" :size="ELTableSize"
            @click="openDetails('编辑', row)">编辑</el-button>
          <el-button type="text" :size="ELTableSize" v-if="row.activeState === 2"
            @click="cancelReleased(row)">撤回</el-button>
          <el-button type="text" :size="ELTableSize" v-if="row.activeState === 3" @click="stop(row)">终止</el-button>
          <el-button type="text" :size="ELTableSize" v-if="row.activeState === 0" @click="released(row)">恢复</el-button>
          <el-button type="text" :size="ELTableSize" v-if="row.activeState === 1" @click="reply(row)">发布</el-button>
          <el-button type="text" v-if="row.activeState === 1" :size="ELTableSize"
            @click="handleDelete(row)">删除</el-button>
          <el-button type="text" :size="ELTableSize" v-if="row.activeState === 3 && row.trait != 2"
            @click="addGiveNumber(row)">增加发放量</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <couponDetails ref="couponDetailsRef" @change="getList()" />
    <couponCollectRecords ref="couponCollectRecordsRef" />
    <el-dialog title="添加发放量" :visible.sync="giveNumDialogVisible" width="650px" :before-close="handlegiveNumClose"
      :close-on-click-modal="false" :close-on-press-escape="false">
      <div>
        <el-input-number v-model="addIssueNumber" :min="-1" :step="1" step-strictly></el-input-number>
        <div style="color: red">
          <p>注意：</p>
          <p>
            1、如果优惠券的发行量原来是-1（代表无上限），设置之后就不是无上限，而是现在的发行量
          </p>
          <p>2、如果原发行量不是-1，则是增加发行量</p>
          <p>3、如果设置为 -1 则代表现在为无上限 不能设置为 0</p>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handlegiveNumClose">取 消</el-button>
        <el-button type="primary" @click="handlegiveNumSure">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import couponDetails from "@/views/marketing/couponDetails.vue";
import couponCollectRecords from "@/views/marketing/couponCollectRecords.vue"
import { couponPage, couponReleased, couponCancelReleased, couponStop, couponCancelStop, couponDel, addIssueNumber } from "@/api/marketing.js";
import { getToken } from "@/utils/auth";
export default {
  components: { couponDetails, couponCollectRecords },
  data() {
    return {
      //按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 测试单表表格数据
      list: [],
      // 是否显示弹出层
      open: false,
      // 创建时间时间范围
      daterangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        trait: 0
      },
      giveNumDialogVisible: false,
      currentCouponId: undefined,
      addIssueNumber: undefined
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询测试单表列表 */
    getList() {
      this.loading = true;
      this.queryParams["canReceiveStartTime"] = undefined;
      this.queryParams["canReceiveEndTime"] = undefined;
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams["canReceiveStartTime"] = this.daterangeCreateTime[0];
        this.queryParams["canReceiveEndTime"] = this.daterangeCreateTime[1];
      }
      couponPage(this.queryParams).then(response => {
        this.list = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    addGiveNumber(row) {
      this.currentCouponId = row.id
      this.giveNumDialogVisible = true
    },
    handlegiveNumClose() {
      this.giveNumDialogVisible = false
      this.currentCouponId = null
      this.addIssueNumber = 1
    },
    handlegiveNumSure() {
      if (this.add_issue_number == 0) {
        return this.$message.warning('发行数量不能为0')
      }
      addIssueNumber({
        id: this.currentCouponId,
        addIssueNumber: this.addIssueNumber
      })
        .then((res) => {
          if (res && res.code == 200) {
            this.$message.success('添加发行量成功')
            this.handlegiveNumClose()
            this.getList()
          }
        })
    },
    handleResourceTip(type) {
      for (let item of this.resourceModelList) {
        if (type == item.value) {
          return item.label || "";
        }
      }
    },
    // 恢复
    released(item) {
      couponCancelStop(item.id).then((res) => {
        if (res && res.data.code == 200) {
          this.$message.success('恢复成功！')
          this.getDataList()
        }
      })
    },
    // 发布
    reply(item) {
      couponReleased(item.id).then((res) => {
        if (res && res.code == 200) {
          this.$message.success('发布成功！')
          this.getList()
        }
      })
    },
    // 撤回
    cancelReleased(item) {
      couponCancelReleased(item.id).then((res) => {
        if (res && res.code == 200) {
          this.$message.success('撤回成功！')
          this.getList()
        }
      })
    },
    // 终止
    stop(item) {
      couponStop(item.id).then((res) => {
        if (res && res.code == 200) {
          this.$message.success('终止成功！')
          this.getList()
        }
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$refs.couponDetailsRef.open('新增');
    },
    openDetails(title, row) {
      this.$refs.couponDetailsRef.open(title, row);
    },
    seeReceiveList(row) {
      this.$refs.couponCollectRecordsRef.open(row);
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除优惠券名称为"' + row.name + '"的数据项？').then(() => {
        this.loading = true;
        return couponDel(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('demo/demo/export', {
        ...this.queryParams
      }, `demo_${new Date().getTime()}.xlsx`)
    },
  }
};
</script>
<style lang="scss">
.el-drawer__body {
  padding: 0 20px !important;
}
</style>
<style lang="scss" scoped>
.flex {
  display: flex;
}

.demo-drawer__footer {
  margin-left: 120px;
}

::v-deep .el-input.is-disabled .el-input__inner {
  background-color: #fff;
  color: rgb(96, 98, 102);
}
</style>
