<template>
  <div class="app-container">
    <!-- 筛选条件 -->
    <div class="screen-container">
      <div class="top clearfix">
        <div class="title fl">条件筛选</div>
      </div>
      <el-form ref="screenForm" :model="screenForm" label-width="90px" size="small" label-position="left">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="优惠券名称" prop="couponName">
              <el-input v-model="screenForm.couponName" placeholder="请输入优惠券名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="12" :lg="6">
            <el-form-item label="发布状态" prop="flag">
              <el-select v-model="screenForm.flag" placeholder="全部发布状态" size="small">
                <el-option label="全部" value=""></el-option>
                <el-option :label="item.label" :value="item.value" v-for="(item, index) in select_flag" :key="index"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :lg="12" class="tr">
            <el-form-item label="">
              <el-button size="small" @click="resetScreenForm">清空</el-button>
              <el-button size="small" type="primary" @click="submitScreenForm">搜索</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="mymain-container">
      <div class="btn-group clearfix">
        <div class="fl">
          <el-button size="small" type="primary" icon="el-icon-plus" @click="toAddData()">新增优惠券</el-button>
        </div>
        <div class="fr">
          <el-upload
            style="display: inline-block; margin-right: 10px"
            :action="'coupon/import'"
            :http-request="handleImport2"
            :file-list="importFileList2"
          >
            <el-button size="small" type="primary" :loading="importLoading2">{{ importLoading2 ? '导入中...' : '导入' }}</el-button>
          </el-upload>

          <el-button size="small" @click="handleDownload">下载导入模板</el-button>

          <el-button size="small" type="primary" icon="el-icon-download" @click="handleExport">导出</el-button>
        </div>
      </div>

      <div class="table">
        <el-table v-loading="listLoading" :data="dataList" element-loading-text="Loading" border fit highlight-current-row stripe>
          <el-table-column align="center" label="券名称" prop="couponName" min-width="120"></el-table-column>
          <el-table-column align="center" label="券类型" prop="couponType" min-width="120">
            <template slot-scope="scope">
              {{ scope.row.couponType | typeFilter}}
            </template>
          </el-table-column>
          <el-table-column align="center" label="券面额" prop="couponValue"></el-table-column>
          <el-table-column align="center" label="满足金额" prop="orderAmount"></el-table-column>
          <el-table-column align="center" label="发放总量" prop="couponAmount"></el-table-column>
          <el-table-column align="center" label="限领次数" prop="receiveLimitCount"></el-table-column>
          <el-table-column align="center" label="领取数量" prop="receivedCount"></el-table-column>
          <el-table-column align="center" label="使用数量" prop="usedCount"></el-table-column>
          <el-table-column align="center" label="显示时间" min-width="160">
            <template slot-scope="scope">
              {{ scope.row.displayTime }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="领取时间" min-width="200">
            <template slot-scope="scope">
              {{ scope.row.obtainStartTime | dateToDayFilter }} 至 {{ scope.row.obtainEndTime | dateToDayFilter }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="使用时间" min-width="200">
            <template slot-scope="scope">
              {{ scope.row.activeStartTime | dateToDayFilter }} 至 {{ scope.row.activeEndTime | dateToDayFilter }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="状态" class-name="status-col">
            <template slot-scope="scope">
              {{ scope.row.releaseFlag | COUPON_CURRENT_FLAG_FILTER }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="创建时间" prop="createTime" min-width="160"></el-table-column>
          <el-table-column align="center" label="操作" fixed="right" width="220">
            <template slot-scope="scope">
              <template>
                <el-button type="text" @click="checkCoupon(scope.row.couponId)">查看</el-button>
                <el-popconfirm v-if="scope.row.releaseFlag === 'START'" style="margin-left: 10px;" title="确定取消吗？" @onConfirm="changeFlag(scope.row.couponId)" >
                  <el-button slot="reference" type="text">取消</el-button>
                </el-popconfirm>
                <el-popconfirm v-if="scope.row.releaseFlag === 'START'" style="margin-left: 10px;" title="确定补发业务员优惠券吗？" @onConfirm="reissueCoupon(scope.row.couponId)" >
                  <el-button slot="reference" type="text">补发业务员优惠券</el-button>
                </el-popconfirm>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination clearfix">
        <div class="fr">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="listTotal">
          </el-pagination>
        </div>
      </div>
    </div>

    <!-- 查看优惠券 -->
    <el-dialog title="查看优惠券" :visible.sync="checkCouponVisible" :show-close="false" width="50%" top="10vh" :close-on-click-modal="false">
      <div class="couponDetail">
        <div class="item clearfix">
          <span>优惠券名称：</span>
          <span>{{couponDetail.couponName}}</span>
        </div>
        <div class="item clearfix">
          <span>优惠券类型：</span>
          <span>{{couponDetail.couponType | typeFilter}}</span>
        </div>
        <div class="item clearfix">
          <span>领取条件：</span>
          <span v-if="couponDetail.receiveCrowd == 0">所有用户</span>
          <span v-if="couponDetail.receiveCrowd == 4">所有会员</span>
          <span v-if="couponDetail.receiveCrowd == 3">所有业务员</span>
          <span v-if="couponDetail.receiveCrowd == 1">指定标签</span>
          <span v-if="couponDetail.receiveCrowd == 2">指定会员</span>
        </div>
        <div class="item clearfix" v-if="couponDetail.receiveCrowd === 1">
          <span>选择标签：</span>
          <span>
            <el-tag size="small" v-for="(item, index) in couponDetail.tagList" :key="index" style="margin-right: 5px">{{item.tagName}}</el-tag>
          </span>
        </div>
        <div class="item clearfix" v-if="couponDetail.receiveCrowd === 2">
          <span>选择会员：</span>
          <span class="table-span">
            <el-table :data="couponDetail.userList" element-loading-text="Loading" border fit highlight-current-row stripe max-height="300px">
              <el-table-column align="center" label="名称" prop="nickName" v-if="couponDetail.couponType !== 'NO_DOOR'"></el-table-column>
              <el-table-column align="center" label="电话" prop="mobile" min-width="120"></el-table-column>
              <el-table-column align="center" label="角色" prop="memberName" min-width="100" v-if="couponDetail.couponType !== 'NO_DOOR'">
                <template slot-scope="scope">
                  {{ scope.row.type | MEMBER_CURRENT_TYPE_FILTER }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="数量" prop="num" min-width="120" v-if="couponDetail.couponType == 'NO_DOOR'"></el-table-column>
            </el-table>
          </span>
        </div>
        <div class="item clearfix" v-if="couponDetail.couponType == 'SATISFY'">
          <span>订单满足金额：</span>
          <span>{{couponDetail.orderAmount}}</span>
        </div>
        <div class="item clearfix" v-if="couponDetail.couponType == 'GOODS'">
          <span>指定商品：</span>
          <span>
            <div v-for="(item, index) in couponDetail.goodsList" :key="index" style="margin-bottom: 10px;">
              {{item.goodsName}}
            </div>
          </span>
        </div>
        <div class="item clearfix">
          <span>优惠券面值：</span>
          <span>{{couponDetail.couponValue}}</span>
        </div>
        
        <template v-if="couponDetail.receiveCrowd == 3 || (couponDetail.receiveCrowd == 2 && couponDetail.userList.length>0 && couponDetail.userList[0].type == 'SERVICE')">
          <div class="item clearfix">
          <span>每人分享次数：</span>
          <span>{{couponDetail.shareTimes}}</span>
        </div>
        </template>
        <template v-else>
          <div class="item clearfix">
            <span>发放数量：</span>
            <span>{{couponDetail.couponAmount}}</span>
          </div>
        </template>
        <div class="item clearfix">
          <span>显示时间：</span>
          <span>{{couponDetail.displayTime}}</span>
        </div>
        <div class="item clearfix">
          <span>领取时间：</span>
          <span>{{couponDetail.obtainStartTime.slice(0, 10)}} - {{couponDetail.obtainEndTime.slice(0, 10)}}</span>
        </div>
        <div class="item clearfix">
          <span>使用时间：</span>
          <span>{{couponDetail.activeStartTime.slice(0, 10)}} - {{couponDetail.activeEndTime.slice(0, 10)}}</span>
        </div>

        <div class="item clearfix" v-if="couponDetail.couponType == 'NO_DOOR'">
          <span>可多张使用：</span>
          <span>{{couponDetail.isMore ? '是':'否'}}</span>
        </div>
        <div class="item clearfix" v-if="couponDetail.couponType == 'NO_DOOR'">
          <span>可叠加活动使用：</span>
          <span>{{couponDetail.isActivity ? '是':'否'}}</span>
        </div>
        <div class="item clearfix" v-if="couponDetail.couponType == 'NO_DOOR'">
          <span>可转发分享：</span>
          <span>{{couponDetail.transferType ? '是':'否'}}</span>
        </div>
        <div class="item clearfix" v-if="couponDetail.couponType == 'NO_DOOR'">
          <span>使用后可分佣：</span>
          <span>{{couponDetail.isAmount ? '是':'否'}}</span>
        </div>
        <div class="item clearfix" v-if="couponDetail.couponType == 'NO_DOOR'">
          <span>发送短信通知：</span>
          <span>{{couponDetail.isSms ? '是':'否'}}</span>
        </div>
        <div class="item clearfix" v-if="couponDetail.couponType == 'NO_DOOR' && couponDetail.isSms">
          <span>发送短信内容：</span>
          <span>{{couponDetail.smsContent}}</span>
        </div>

        <div class="item clearfix">
          <span>使用说明：</span>
          <span>{{couponDetail.note}}</span>
        </div>
        <div class="item clearfix">
          <span>备注：</span>
          <span>{{couponDetail.remark}}</span>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="checkCouponVisible = false">关 闭</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { changeCouponFlag, getCouponDetail, getList, reissueCoupon} from "@/api/coupon";
import { MEMBER_CURRENT_TYPE, COUPON_CURRENT_FLAG } from "@/utils/select_data";
import { downloadFiles, findElem, handleImport } from '@/utils/util'

export default {
  filters: {
    typeFilter(type) {
      const typeMap = {
        'SATISFY': '满减券',
        'GOODS': '商品券',
        'NO_DOOR': '无门槛优惠券',
      }
      return typeMap[type]
    }
  },
  data() {
    return {
      dataList: null, // 列表数据
      listLoading: true, // 列表加载loading
      screenForm: { // 筛选表单数据
        couponName: '', // 优惠券名称
        flag: '' // 标志
      },
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页数量
      listTotal: 0, // 列表总数
      select_flag: COUPON_CURRENT_FLAG,

      checkCouponVisible: false, // 查看优惠券弹窗
      couponDetail: {
        activeStartTime: '',
        activeEndTime: '',
        obtainStartTime: '',
        obtainEndTime: '',
      }, // 优惠券详情

      select_type: MEMBER_CURRENT_TYPE,

      importLoading2: false, // 导入加载loading
      importFileList2: [], // 导入列表
    }
  },
  
  created() {
    this.getList();
  },

  methods: {
    getList() {
      this.listLoading = true;

      let params = {
        couponName: this.screenForm.couponName,
        flag: this.screenForm.flag,
        pageNum: this.currentPage,
        pageSize: this.pageSize
      }

      getList(params).then(res => {
        this.dataList = res.data.records;
        this.listTotal = res.data.total;
        this.listLoading = false;
      })
    },

    // 提交筛选表单
    submitScreenForm() {
      this.currentPage = 1;
      this.getList();
    },

    // 重置筛选表单
    resetScreenForm() {
      this.$refs.screenForm.resetFields();
      this.currentPage = 1;
      this.getList();
    },

    // 更改每页数量
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.getList();
    },

    // 更改当前页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getList();
    },

    toAddData() {
      this.$router.push({
        path: '/activity/coupon_add',
        query: {}
      })
    },

    
    // 操作 - 更改优惠券标志为取消
    changeFlag(couponId) {
      let params = {
        couponId: couponId,
        flag: 'CANCEL',
      }
      changeCouponFlag(params).then(() => {
        this.getList();
        this.$successMsg('取消成功');
      })
    },

    // 查看优惠券
    checkCoupon(couponId) {
      this.checkCouponVisible = true;
      getCouponDetail({ couponId }).then(res => {
        this.couponDetail = res.data;
      })
    },

    // 导出
    handleExport() {
      let screenData = {
        couponName: this.screenForm.couponName,
        flag: this.screenForm.flag,
      };
      downloadFiles('coupon/list/export', screenData);
    },

    // 补发业务员优惠券
    reissueCoupon(couponId) {
      reissueCoupon({couponId}).then(res => {
        this.getList();
        this.$successMsg();
      })
    },

    // 导入
    async handleImport2(param) {
      console.log(param);
      this.importLoading2 = true;
      const file = param.file;
      const formData = new FormData();
      formData.append("file", file);
      let result = await handleImport('coupon/import', formData);
      this.importLoading2 = false;
      this.importFileList2 = [];
      if(result.code == 200) {
        this.$alert(result.message, '导入成功', {
          confirmButtonText: '确定'
        });
        this.getList();
      }else {
        this.$alert(result.message, '导入失败', {
          confirmButtonText: '确定'
        });
      }
    },

    // 下载导入模版
    handleDownload() {
      downloadFiles('coupon/template');
    },

  }
}
</script>

<style scoped lang="scss">
  .couponDetail {
    height: 60vh;
    overflow-y: scroll;
    padding-right: 20px;
    .item {
      font-size: 16px;
      margin-bottom: 20px;
      &>span {
        float: left;
        &:first-child {
          width: 140px;
          text-align: right;
          margin-right: 10px;
          font-weight: 500;
        }
      }
      .table-span {
        width: calc(100% - 170px);
      }
    }
  }
</style>
