<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px" size="medium" class="ry_form">
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="券ID" prop="stockId">
        <el-input
          v-model="queryParams.stockId"
          placeholder="请输入券ID"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="券名称" prop="stockName">
        <el-input
          v-model="queryParams.stockName"
          placeholder="请输入券名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="券类型" prop="stockType">
        <el-select v-model="queryParams.stockType" placeholder="请选择券类型" clearable size="small">
            <el-option label="微信满减券" value="NORMAL" />
            <el-option label="微信折扣券" value="DISCOUNT" />
            <el-option label="微信换购券" value="EXCHANGE" />
            <el-option label="平台满减券" value="PNORMAL" />
            <el-option label="平台折扣券" value="PDISCOUNT" />
            <el-option label="平台体验券" value="PTRAIL" />
        </el-select>
      </el-form-item>
      <el-form-item label="券码" prop="couponCode">
        <el-input
          v-model="queryParams.couponCode"
          placeholder="请输入券码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--       <el-form-item label="可用开始时间" prop="availableStartTime">
        <el-date-picker
            clearable
            size="small"
            v-model="queryParams.availableStartTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择可用开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="过期时间" prop="expireTime">
        <el-date-picker
            clearable
            size="small"
            v-model="queryParams.expireTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择过期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="发放时间" prop="receiveTime">
        <el-date-picker
            clearable
            size="small"
            v-model="queryParams.receiveTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择发放时间">
        </el-date-picker>
      </el-form-item> -->
      <el-form-item label="商家券状态" prop="couponState">
        <el-input
          v-model="queryParams.couponState"
          placeholder="请输入商家券状态"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <template v-if="showMoreCondition">
<!--       <el-form-item label="使用时间" prop="useTime">
        <el-date-picker
            clearable
            size="small"
            v-model="queryParams.useTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择使用时间">
        </el-date-picker>
      </el-form-item> -->
    </template>
      <el-form-item class="flex_one tr">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <!-- <el-button :icon="showMoreCondition ? 'el-icon-arrow-up' : 'el-icon-arrow-down'" size="mini" @click="showMoreCondition = !showMoreCondition">{{showMoreCondition ? '收起条件' : '展开条件'}}</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="['mall:wechatMemberCoupon:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleSend"
          v-hasPermi="['mall:wechatMemberCoupon:add']"
        >券发放</el-button>
      </el-col>
<!--       <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['mall:wechatMemberCoupon:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['mall:wechatMemberCoupon:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['mall:wechatMemberCoupon:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="wechatMemberCouponList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" /> -->
      <el-table-column label="手机号" align="center" prop="phone" v-if="columns[12].visible"/>
      <el-table-column label="券id" align="center" prop="stockId" v-if="columns[0].visible"/>
      <el-table-column label="券名称" align="center" prop="stockName" v-if="columns[1].visible"/>
      <el-table-column label="券类型" align="center" prop="stockType" v-if="columns[2].visible">
        <template slot-scope="scope">
          <span>{{ getStockTypeName(scope.row.stockType) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="券码" align="center" prop="couponCode" v-if="columns[3].visible"/>
      <el-table-column label="可用开始时间" align="center" prop="availableStartTime" width="180" v-if="columns[4].visible">
        <template slot-scope="scope">
            <span>{{ parseTime(scope.row.availableStartTime, '')}}</span>
        </template>
      </el-table-column>
      <el-table-column label="过期时间" align="center" prop="expireTime" width="180" v-if="columns[5].visible">
        <template slot-scope="scope">
            <span>{{ parseTime(scope.row.expireTime, '')}}</span>
        </template>
      </el-table-column>
      <el-table-column label="发放时间" align="center" prop="receiveTime" width="180" v-if="columns[6].visible">
        <template slot-scope="scope">
            <span>{{ parseTime(scope.row.receiveTime, '')}}</span>
        </template>
      </el-table-column>
      <el-table-column label="发放请求号" align="center" prop="sendRequestNo" v-if="columns[7].visible"/>
      <el-table-column label="核销请求号" align="center" prop="useRequestNo" v-if="columns[8].visible"/>
      <el-table-column label="使用时间" align="center" prop="useTime" width="180" v-if="columns[9].visible">
        <template slot-scope="scope">
            <span>{{ parseTime(scope.row.useTime, '')}}</span>
        </template>
      </el-table-column>
      <el-table-column label="商家券状态" align="center" prop="couponState" v-if="columns[10].visible">
        <template slot-scope="scope">
          <span>{{ getCouponStateName(scope.row.couponState) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="小程序openid" align="center" prop="openid" v-if="columns[11].visible"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['mall:wechatMemberCoupon:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['mall:wechatMemberCoupon:remove']"
          >删除</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"
    />

    <!-- 添加或修改会员券发放记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="108px" inline class="dialog-form-two">
        <el-form-item label="券id" prop="stockId">
          <el-input v-model="form.stockId" placeholder="请输入券id" />
        </el-form-item>
        <el-form-item label="券名称" prop="stockName">
          <el-input v-model="form.stockName" placeholder="请输入券名称" />
        </el-form-item>
        <el-form-item label="券类型" prop="stockType">
          <el-select v-model="form.stockType" placeholder="请选择券类型">
            <el-option label="微信满减券" value="NORMAL" />
            <el-option label="微信折扣券" value="DISCOUNT" />
            <el-option label="微信换购券" value="EXCHANGE" />
            <el-option label="平台满减券" value="PNORMAL" />
            <el-option label="平台折扣券" value="PDISCOUNT" />
            <el-option label="平台体验券" value="PTRAIL" />
          </el-select>
        </el-form-item>
        <el-form-item label="券码" prop="couponCode">
          <el-input v-model="form.couponCode" placeholder="请输入券码" />
        </el-form-item>
        <el-form-item label="可用开始时间" prop="availableStartTime">
          <el-date-picker clearable size="small"
                        v-model="form.availableStartTime"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="选择可用开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="过期时间" prop="expireTime">
          <el-date-picker clearable size="small"
                        v-model="form.expireTime"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="选择过期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="发放时间" prop="receiveTime">
          <el-date-picker clearable size="small"
                        v-model="form.receiveTime"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="选择发放时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="发放请求号" prop="sendRequestNo">
          <el-input v-model="form.sendRequestNo" placeholder="请输入发放请求号" />
        </el-form-item>
        <el-form-item label="核销请求号" prop="useRequestNo">
          <el-input v-model="form.useRequestNo" placeholder="请输入核销请求号" />
        </el-form-item>
        <el-form-item label="使用时间" prop="useTime">
          <el-date-picker clearable size="small"
                        v-model="form.useTime"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="选择使用时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="商家券状态" prop="couponState">
          <el-input v-model="form.couponState" placeholder="请输入商家券状态" />
        </el-form-item>
        <el-form-item label="小程序openid" prop="openid">
          <el-input v-model="form.openid" placeholder="请输入小程序openid" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 发放会员券对话框 -->
    <el-dialog :title="title" :visible.sync="open2" width="50%" append-to-body>
      <el-form ref="form2" :model="form2" :rules="rules" label-width="108px" inline class="dialog-form-two">
        <el-form-item label="优惠券" prop="stockId">
          <CouponSelect v-model="form2.stockId" @change="onCouponChange"></CouponSelect>
        </el-form-item>
        <el-form-item label="会员" prop="phone">
          <MemberSelect v-model="form2.phone" @change="onMemberChange"></MemberSelect>
        </el-form-item>
      </el-form>  
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="sendForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listWechatMemberCoupon, getWechatMemberCoupon, delWechatMemberCoupon, addWechatMemberCoupon, updateWechatMemberCoupon, exportWechatMemberCoupon, sendCoupon } from "@/api/marketing/wechatMemberCoupon";
import CouponSelect from "@/views/components/CouponSelector/index.vue";
import MemberSelect from "@/views/components/MemberSelect.vue";

export default {
  name: "WechatMemberCoupon",
  components: {
    CouponSelect, MemberSelect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 会员券发放记录表格数据
      wechatMemberCouponList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      open2: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: "create_time",
        isAsc: "desc",
        stockId: null,
        stockName: null,
        stockType: null,
        couponCode: null,
        availableStartTime: null,
        expireTime: null,
        receiveTime: null,
        sendRequestNo: null,
        useRequestNo: null,
        useTime: null,
        couponState: null,
        openid: null,
        phone: null,
      },
      // 表单参数
      form: {},
      // 表单参数
      form2: {},
      // 表单校验
      rules: {
        stockId: [
          { required: true, message: "券id不能为空", trigger: "blur" }
        ],
        stockName: [
          { required: true, message: "券名称不能为空", trigger: "blur" }
        ],
        stockType: [
          { required: true, message: "券类型不能为空", trigger: "change" }
        ],
        couponCode: [
          { required: true, message: "券码不能为空", trigger: "blur" }
        ],
        availableStartTime: [
          { required: true, message: "可用开始时间不能为空", trigger: "blur" }
        ],
        expireTime: [
          { required: true, message: "过期时间不能为空", trigger: "blur" }
        ],
        receiveTime: [
          { required: true, message: "发放时间不能为空", trigger: "blur" }
        ],
        couponState: [
          { required: true, message: "商家券状态", trigger: "blur" }
        ],
        openid: [
          { required: true, message: "小程序openid不能为空", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "手机号不能为空", trigger: "blur" }
        ],
      },
      columns: [
            { key: 1, label: "券ID", visible:  true  },
            { key: 2, label: "券名称", visible:  true  },
            { key: 3, label: "券类型", visible:  true  },
            { key: 4, label: "券码", visible:  true  },
            { key: 5, label: "可用开始时间", visible:  true  },
            { key: 6, label: "过期时间", visible:  true  },
            { key: 7, label: "发放时间", visible:  true  },
            { key: 8, label: "发放请求号", visible:  false  },
            { key: 9, label: "核销请求号", visible:  false  },
            { key: 10, label: "使用时间", visible:  true  },
            { key: 11, label: "商家券状态", visible:  true  },
            { key: 12, label: "小程序openid", visible:  false  },
            { key: 13, label: "手机号", visible:  true  },
                         ],
      showMoreCondition: false
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询会员券发放记录列表 */
    getList() {
      this.loading = true;
      listWechatMemberCoupon(this.queryParams).then(response => {
        this.wechatMemberCouponList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.open2 = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        stockId: null,
        stockName: null,
        stockType: null,
        couponCode: null,
        availableStartTime: null,
        expireTime: null,
        receiveTime: null,
        sendRequestNo: null,
        useRequestNo: null,
        useTime: null,
        couponState: null,
        openid: null,
        phone: null,
        createBy: null,
        createTime: null,
        updateTime: null,
        updateBy: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      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.reset();
      this.open = true;
      this.title = "添加会员券发放记录";
    },
    /** 新增按钮操作 */
    handleSend() {
      this.reset();
      this.open2 = true;
      this.title = "发放会员券";
    },
    onCouponChange(value){
      this.form2.stockId = value
    },
    onMemberChange(value){
      this.form2.phone = value
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getWechatMemberCoupon(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改会员券发放记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateWechatMemberCoupon(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addWechatMemberCoupon(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** send按钮 */
    sendForm() {
      this.$refs["form2"].validate(valid => {
          console.log(this.form2);
          sendCoupon(this.form2).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open2 = false;
              this.getList();
            });
        })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除会员券发放记录编号为"' + ids + '"的数据项？').then(function() {
        return delWechatMemberCoupon(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$modal.confirm('是否确认导出所有会员券发放记录数据项？').then(() => {
        this.exportLoading = true;
        return exportWechatMemberCoupon(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {});
    },
    /** 获取券类型中文名称 */
    getStockTypeName(type) {
      const map = {
        'NORMAL': '微信满减券',
        'DISCOUNT': '微信折扣券',
        'EXCHANGE': '微信换购券',
        'PNORMAL': '平台满减券',
        'PDISCOUNT': '平台折扣券',
        'PTRAIL': '平台体验券'
      };
      return map[type] || type;
    },
    /** 获取商家券状态中文名称 */
    getCouponStateName(state) {
      const map = {
        'UNUSED': '未使用',
        'USED': '已使用',
        'EXPIRED': '已过期',
        'CANCELLED': '已作废',
        'SENDING': '发放中',
        'SEND_FAILED': '发放失败'
      };
      return map[state] || state;
    }
  }
};
</script>
