<template>
  <div class="app-container">

    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item :label="$t('标题')" prop="titleZh">
        <el-input v-model="queryParams.titleZh" :placeholder="$t('请输入标题')" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item> -->
      <!-- <el-form-item :label="$t('标题')" prop="titleEn">
        <el-input v-model="queryParams.titleEn" :placeholder="$t('请输入标题')" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item> -->
      <el-form-item :label="$t('类型')" prop="type">
        <dict-selector :type='DICT_TYPE.ECW_COUPON_TYPE' v-model="queryParams.type" clearable />
      </el-form-item>
      <el-form-item :label="$t('状态')" prop="status" clearable>
        <!-- <dict-selector :type="DICT_TYPE.ECW_COUPON_STATUS" v-model="queryParams.status"/> -->
        <el-select v-model="queryParams.status" :placeholder="$t('请选择')" clearable size="small">
          <el-option :label="$t('草稿')" value="0" />
          <el-option :label="$t('已发布')" value="1" />
          <el-option :label="$t('已过期')" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('关键字')" prop="searchKey">
        <el-input v-model="queryParams.searchKey" :placeholder="$t('请输入关键字')" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">{{ $t('搜索') }}</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">{{ $t('重置') }}</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="mini" @click="handleAdd"
                   v-hasPermi="['ecw:coupon:create']">{{ $t('新增') }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading"
                   v-hasPermi="['ecw:coupon:export']">{{ $t('导出') }}</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="list" border>
      <el-table-column :label="$t('优惠券ID')" align="center" prop="couponId" />
      <el-table-column :label="$t('类型')" align="center" prop="type">
        <template slot-scope="{row}">
          <dict-tag :type="DICT_TYPE.ECW_COUPON_TYPE" :value="row.type" />
        </template>
      </el-table-column>
      <el-table-column :label="$t('标题')" align="center" prop="titleZh" />
      <!-- <el-table-column :label="$t('描述')" align="center" prop="type">
        <template slot-scope="{row}">
          {{$l(row, 'content')}}
        </template>
      </el-table-column> -->
      <el-table-column :label="$t('发布人') + '/' + $t('发布时间')" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <div>{{ scope.row.creatorName }}</div>
          <div>{{ parseTime(scope.row.createTime) }}</div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('开始时间')" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('结束时间')" align="center" prop="endTime" width="180">
        <template slot-scope="{row}">
          <div :style="{red: row.overdueStatus == 0 ? 'red' : null}">{{ parseTime(row.endTime, '{y}-{m}-{d}') }}</div>
          <div v-if="row.overdueStatus == 0" style="color: red">{{ $t('已过期') }}</div>
        </template>
      </el-table-column>
      <!--
      <el-table-column :label="$t('创建时间')" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column-->
      <el-table-column :label="$t('更新人') + '/' + $t('更新时间')" align="center" width="180">
        <template slot-scope="scope">
          <div>{{ scope.row.updaterName }}</div>
          <div>{{ parseTime(scope.row.updateTime)}}</div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('状态')" align="center" prop="createTime" width="180">
        <template slot-scope="{row}">
          <dict-tag :type="DICT_TYPE.ECW_IS_DRAFT" :value="row.status" />
        </template>
      </el-table-column>
      <el-table-column :label="$t('操作')" align="center" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleDetail(scope.row, true)"
                     v-hasPermi="['ecw:coupon:show']">{{ $t('查看') }}</el-button>
          <el-button v-if="scope.row.status != 1" size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['ecw:coupon:update']">{{ $t('编辑') }}</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleCopy(scope.row)"
                     v-hasPermi="['ecw:coupon:copy']">{{ $t('复制') }}</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="updateEndtimeItem = scope.row" v-if="scope.row.endTime && scope.row.status"
                     v-hasPermi="['ecw:coupon:delay']">{{ $t('延期') }}</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['ecw:coupon:delete']">{{ $t('删除') }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <el-dialog :title="$t('延期活动时间')" :visible="!!updateEndtimeItem" :before-close="() => updateEndtimeItem=null">
      <div v-if="updateEndtimeItem">
        {{$t('优惠活动“{name}”的当前结束时间：{time}',{
          name: $l(updateEndtimeItem, 'title'),
          time: updateEndtimeItem.endTime || $t('永久有效')
          })}}
      </div>
      <div>{{$t('请问您确定延长活动吗？')}}</div>
      <el-form :model="updateEndtimeForm" :rules="updateEndtimeRules" label-position="left" >
        <el-form-item :label="$t('活动结束时间')" prop="endTime">
          <el-date-picker v-if="!updateEndtimeForm.forever" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" v-model="updateEndtimeForm.endTime" placeholder=""></el-date-picker>
          <el-checkbox :label="$t('永久有效')" v-model="updateEndtimeForm.forever" class="ml-10"></el-checkbox>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="updateEndtime">{{$t('确定')}}</el-button>
        <el-button type="default" @click="updateEndtimeItem = null">{{$t('取消')}}</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { createCoupon, updateCoupon, deleteCoupon, getCoupon, getCouponPage, exportCouponExcel, updateEndtime } from "@/api/ecw/coupon";

export default {
  name: "EcwCouponIndex",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 优惠券信息列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      dateRangeStartTime: [],
      dateRangeEndTime: [],
      dateRangeCreateTime: null,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        titleZh: null,
        titleEn: null,
        type: null,
        cashCondition: null,
        reduceAmount: null,
        conditionCurrencyId: null,
        reduceCurrencyId: null,
        afterReceiveDays: null,
        validDays: null,
        costType: null,
        discountDetailed: null,
        isSimilarSuperposition: null,
        couponIds: null,
        suitableUserType: null,
        suitableLineType: null,
        suitableProdType: null,
        limitNum: null,
        overdueStatus: null,
        putonStatus: null,
        getWay: null,
        orderAttr: null,
        isSiteContent: null,
        isCargoControl: null,
        documentDeclaration: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      updateEndtimeItem: null, // 延期操作的数据
      updateEndtimeForm:{} // 延长有效期的表单数据
    };
  },
  computed:{
    updateEndtimeRules(){
      return {
        endTime: [
          {required: !this.updateEndtimeForm.forever, message: "请填写结束时间"}
        ]
      }
    }
  },
  watch:{
    updateEndtimeItem(){
      this.updateEndtimeForm = {}
    }
  },
  created() {
    this.getList();
  },
  activated(){
    this.getList()
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 处理查询参数
      let params = {...this.queryParams};
      if(params.status == 2){
        params.overdueStatus=0
        params.status = null
      }
      this.addBeginAndEndTime(params, this.dateRangeStartTime, 'startTime');
      this.addBeginAndEndTime(params, this.dateRangeEndTime, 'endTime');
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, 'createTime');
      // 执行查询
      getCouponPage(params).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRangeStartTime = [];
      this.dateRangeEndTime = [];
      this.dateRangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      return this.$router.push('edit')
    },
    /** 修改按钮操作 */
    handleUpdate(row, readonly) {
      const couponId = row.couponId;
      let url = 'edit?id=' + couponId
      if(readonly){
        url += '&readonly=1'
      }
      return this.$router.push(url)
    },
    handleDetail(row){
      this.$router.push('detail?id=' + row.couponId + '&readonly=1')
    },
    handleCopy(row){
      this.$router.push('edit?action=copy&id=' + row.couponId)
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const couponId = row.couponId;
      this.$confirm(this.$t('是否确认删除优惠券信息编号为{couponId}的数据项?', {couponId})).then(function() {
          return deleteCoupon(couponId);
        }).then(() => {
          this.getList();
          this.$message.success(this.$t("删除成功"));
        }).catch(() => {});
    },
    // 延期
    updateEndtime(){
      if(!this.updateEndtimeForm.forever && !this.updateEndtimeForm.endTime){
        return this.$message.error(this.$t("请填写结束时间"))
      }
      let form = {couponId: this.updateEndtimeItem.couponId, ...this.updateEndtimeForm}
      form.isValidity = !form.forever // 是否设置有效期
      updateEndtime(form).then(res => {
        this.getList()
        this.updateEndtimeItem = null
        this.$message.success(this.$t('操作成功'))
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.addBeginAndEndTime(params, this.dateRangeStartTime, 'startTime');
      this.addBeginAndEndTime(params, this.dateRangeEndTime, 'endTime');
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, 'createTime');
      // 执行导出
      this.$confirm(this.$t('是否确认导出所有优惠券信息数据项?')).then(() => {
          this.exportLoading = true;
          return exportCouponExcel(params);
        }).then(response => {
          this.$download.excel(response, '${table.classComment}.xls');
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
