<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="addOrEdit('add')"
            >新增优惠券</el-button
          >
        </div>
        <div class="fr">
          <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="商户"
            prop="companyName"
            min-width="120"
          ></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">
              <el-button type="text" @click="checkCoupon(scope.row.couponId)"
                >查看</el-button
              >
              <el-button
                v-if="scope.row.releaseFlag === 'WAIT'"
                type="text"
                @click="addOrEdit('edit', scope.row.couponId)"
                >编辑</el-button
              >
              <el-popconfirm
                v-if="scope.row.releaseFlag === 'START'"
                style="margin-left: 10px"
                title="确定取消吗？"
                @confirm="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="确定补发业务员优惠券吗？"
                @confirm="reissueCoupon(scope.row.couponId)"
              >
                <el-button slot="reference" type="text"
                  >补发业务员优惠券</el-button
                >
              </el-popconfirm>
            </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="addFormType === 'add' ? '新增优惠券' : '编辑优惠券'"
      :visible.sync="addFormVisible"
      :show-close="false"
      width="50%"
      :close-on-click-modal="false"
      top="5vh"
    >
      <el-form
        ref="addForm"
        :model="addForm"
        :rules="addFormRules"
        label-position="right"
        label-width="110px"
        style="height: 70vh; overflow-y: scroll; padding-right: 20px"
      >
        <el-form-item label="优惠券名称" prop="couponName">
          <el-input
            v-model="addForm.couponName"
            autocomplete="off"
            placeholder="请输入优惠券名称"
            :disabled="addForm.flag === 'START'"
          ></el-input>
        </el-form-item>
        <el-form-item label="优惠券类型" prop="couponType">
          <el-radio-group
            v-model="addForm.couponType"
            :disabled="addForm.flag === 'START'"
          >
            <el-radio label="SATISFY">满减券</el-radio>
            <el-radio label="GOODS">商品券</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="领取条件" prop="receiveCrowd">
          <el-radio-group
            v-model="addForm.receiveCrowd"
            :disabled="addForm.flag === 'START'"
          >
            <el-radio :label="0">所有用户</el-radio>
            <el-radio :label="4">所有会员</el-radio>
            <el-radio :label="3">所有业务员</el-radio>
            <el-radio :label="1">指定标签</el-radio>
            <el-radio :label="2">指定会员</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          label="选择标签"
          prop="tagValue"
          v-if="addForm.receiveCrowd === 1"
        >
          <el-select
            v-model="tagValue"
            multiple
            placeholder="请选择标签"
            style="width: 100%"
            :disabled="addForm.flag === 'START'"
          >
            <el-option
              v-for="item in tagList"
              :value-key="item.value"
              :key="item.value"
              :label="item.name"
              :value="item"
            >
              <span style="float: left; color: #999999">{{
                item.groupName
              }}</span>
              <span style="float: left; margin: 0 5px; color: #999999">-</span>
              <span style="float: left">{{ item.name }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="选择会员"
          prop="memberList"
          v-if="addForm.receiveCrowd === 2"
        >
          <el-table
            :data="memberList"
            element-loading-text="Loading"
            border
            fit
            highlight-current-row
            stripe
            max-height="300px"
          >
            <el-table-column align="center" label="头像" prop="avatar">
              <template slot-scope="scope">
                <el-image
                  style="width: 40px; height: 40px; border-radius: 50%"
                  :src="$showImgUrl(scope.row.avatar)"
                  :preview-src-list="[$showImgUrl(scope.row.avatar)]"
                  fit="cover"
                ></el-image>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="名称"
              prop="nickName"
            ></el-table-column>
            <el-table-column
              align="center"
              label="电话"
              prop="mobile"
              min-width="120"
            ></el-table-column>
            <el-table-column
              align="center"
              label="性别"
              prop="sex"
            ></el-table-column>
            <el-table-column
              align="center"
              label="地区"
              prop="city"
              min-width="100"
            >
              <template slot-scope="scope">
                {{ scope.row.province }}{{ scope.row.city }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="角色"
              prop="memberName"
              min-width="100"
            >
              <template slot-scope="scope">
                {{ scope.row.type | MEMBER_CURRENT_TYPE_FILTER }}
              </template>
            </el-table-column>

            <el-table-column align="center" label="操作" fixed="right">
              <template slot-scope="scope">
                <el-popconfirm
                  title="确定删除吗？"
                  @confirm="deleteMember(scope.$index)"
                >
                  <el-button slot="reference" type="text">删除</el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
          <div class="addMember">
            <el-button type="text" @click="addMember">添加会员</el-button>
          </div>
        </el-form-item>

        <el-form-item
          label="指定商品"
          prop="goodsList"
          v-if="addForm.couponType == 'GOODS'"
        >
          <div class="goods-container">
            <div
              class="item clearfix"
              v-for="(item, index) in goodsList"
              :key="index"
            >
              <el-input
                class="fl"
                style="width: 70%; margin-right: 10px"
                readonly
                :value="item.goodsName"
              ></el-input>
              <el-button class="fl" @click="deleteGoods(index)">删除</el-button>
            </div>
            <div class="item clearfix" v-if="goodsList.length < maxGoodsCount">
              <el-input
                class="fl"
                style="width: 70%; margin-right: 10px"
                readonly
              ></el-input>
              <el-button type="primary" class="fl" @click="addGoods"
                >选择</el-button
              >
            </div>
          </div>
        </el-form-item>

        <el-form-item
          label="订单满足金额"
          prop="orderAmount"
          v-if="addForm.couponType == 'SATISFY'"
        >
          <el-input
            v-model="addForm.orderAmount"
            autocomplete="off"
            placeholder="请输入订单满足金额"
            :disabled="addForm.flag === 'START'"
          ></el-input>
        </el-form-item>

        <el-form-item label="优惠券面值" prop="couponValue">
          <el-input
            v-model="addForm.couponValue"
            autocomplete="off"
            placeholder="请输入优惠券面值"
            :disabled="addForm.flag === 'START'"
          ></el-input>
        </el-form-item>

        <el-form-item label="发放数量" prop="couponAmount" v-if="!isService">
          <el-input
            v-model="addForm.couponAmount"
            autocomplete="off"
            placeholder="请输入发放数量"
          ></el-input>
        </el-form-item>

        <el-form-item label="每人分享次数" prop="shareTimes" v-if="isService">
          <el-input
            v-model="addForm.shareTimes"
            autocomplete="off"
            placeholder="请输入每人分享次数"
            :disabled="addForm.flag === 'START'"
          ></el-input>
        </el-form-item>

        <el-form-item
          label="每人领用张数"
          prop="receiveLimitCount"
          v-if="!isService"
        >
          <el-input
            v-model="addForm.receiveLimitCount"
            autocomplete="off"
            placeholder="请输入每人领用张数"
            :disabled="addForm.flag === 'START'"
          ></el-input>
        </el-form-item>

        <el-form-item label="显示时间" prop="displayDate">
          <el-date-picker
            v-model="addForm.displayDate"
            style="width: 100%"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期时间"
            :disabled="addForm.flag === 'START'"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="领取时间" prop="receiveDate">
          <el-date-picker
            v-model="addForm.receiveDate"
            style="width: 100%"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :disabled="addForm.flag === 'START'"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="使用时间" prop="activeDate">
          <el-date-picker
            v-model="addForm.activeDate"
            style="width: 100%"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :disabled="addForm.flag === 'START'"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="有效时间" prop="activeDay">
          <div style="display: flex">
            自领优惠券后<el-input
              v-model="addForm.activeDay"
              autocomplete="off"
              placeholder="请输入"
              style="width: 100px; margin: 0 10px"
            ></el-input
            >天内有效
          </div>
        </el-form-item>
        <el-form-item label="使用说明" prop="note">
          <el-input
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 6 }"
            autocomplete="off"
            placeholder="请输入使用说明"
            v-model="addForm.note"
            maxlength="100"
            show-word-limit
          >
          </el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 6 }"
            autocomplete="off"
            placeholder="备注"
            v-model="addForm.remark"
            maxlength="100"
            show-word-limit
          >
          </el-input>
        </el-form-item>
        <el-upload
          class="avatar-uploader"
          style="height: 0"
          :action="baseURL + 'common/upload'"
          :headers="myHeaders"
          :show-file-list="false"
          :on-success="uploadSuccess"
          :before-upload="beforeUpload"
        >
        </el-upload>
        <el-form-item label="弹窗图片" prop="imgUrl">
          <div class="images">
            <div class="main-img">
              <div
                class="img"
                v-if="addForm.imgUrl"
                @mouseover="addForm.imgHover = true"
                @mouseout="addForm.imgHover = false"
              >
                <el-image
                  ref="img"
                  :src="$showImgUrl(addForm.imgUrl)"
                  :preview-src-list="[$showImgUrl(addForm.imgUrl)]"
                  style="width: 120px; height: 120px"
                  fit="contain"
                ></el-image>
                <div class="mask" v-show="addForm.imgHover">
                  <i class="el-icon-zoom-in" @click="previewImage()"></i>
                  <i class="el-icon-upload2" @click="uploadImage()"></i>
                </div>
              </div>
              <div class="add" v-else @click="uploadImage()">
                <i class="el-icon-plus avatar-uploader-icon"></i>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAddForm">取 消</el-button>
        <el-button type="primary" @click="submitAddForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 查看优惠券 -->
    <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 v-if="couponDetail.couponType == 'SATISFY'">满减券</span>
          <span v-if="couponDetail.couponType == 'GOODS'">商品券</span>
        </div>
        <div class="item clearfix">
          <span>领取条件：</span>
          <!-- <span v-if="couponDetail.receiveCrowd == 0">所有用户</span> -->
          <span v-if="couponDetail.receiveCrowd == 3">所有业务员</span>
          <span v-if="couponDetail.receiveCrowd == 4">所有会员</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="avatar">
                <template slot-scope="scope">
                  <el-image
                    style="width: 40px; height: 40px; border-radius: 50%"
                    :src="$showImgUrl(scope.row.avatar)"
                    :preview-src-list="[$showImgUrl(scope.row.avatar)]"
                    fit="cover"
                  ></el-image>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="名称"
                prop="nickName"
              ></el-table-column>
              <el-table-column
                align="center"
                label="电话"
                prop="mobile"
                min-width="120"
              ></el-table-column>
              <el-table-column
                align="center"
                label="性别"
                prop="sex"
              ></el-table-column>
              <el-table-column
                align="center"
                label="地区"
                prop="city"
                min-width="100"
              >
                <template slot-scope="scope">
                  {{ scope.row.province }}{{ scope.row.city }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="角色"
                prop="memberName"
                min-width="100"
              >
                <template slot-scope="scope">
                  {{ scope.row.type | MEMBER_CURRENT_TYPE_FILTER }}
                </template>
              </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>
          <div class="item clearfix">
            <span>每人领用张数：</span>
            <span>{{ couponDetail.receiveLimitCount }}</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">
          <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>

    <!-- 选择商品 -->
    <el-dialog
      title="选择商品"
      :visible.sync="addGoodsVisible"
      :show-close="false"
      width="50%"
      :close-on-click-modal="false"
    >
      <div class="dialog-container clearfix">
        <div class="left fl">
          <div class="item" @click="changeClassify('')">全部分类</div>
          <div class="group" v-for="(item, index) in classifyList" :key="index">
            <div class="item" @click="toggleOpen(index)">
              <i
                :class="
                  item.isOpen ? 'el-icon-caret-bottom' : 'el-icon-caret-right'
                "
              ></i>
              {{ item.name }}
            </div>
            <div class="child" v-if="item.isOpen">
              <div
                class="item"
                v-for="(childItem, childIndex) in item.children"
                :key="childIndex"
                @click="changeClassify(childItem.categoryId)"
              >
                {{ childItem.name }}
              </div>
            </div>
          </div>
        </div>
        <div class="right fl">
          <div class="search">
            <el-input
              placeholder="请输入商品名称进行搜索"
              v-model="goods_keyword"
              class="input-with-select"
              clearable
              size="small"
              style="width: 250px"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                size="small"
                @click="getGoodsListByScreen"
              ></el-button>
            </el-input>
          </div>
          <div class="table" style="margin: 10px 0 20px">
            <el-table
              v-loading="goodsTable_listLoading"
              :data="goodsTable_dataList"
              element-loading-text="Loading"
              tooltip-effect="dark"
              style="width: 100%"
              max-height="270"
              @selection-change="handleChooseGoods"
            >
              <el-table-column
                align="center"
                type="selection"
                :selectable="checkboxSelect"
                width="45"
              ></el-table-column>
              <el-table-column
                align="center"
                prop="goodsName"
                label="商品名称"
                min-width="200"
                show-overflow-tooltip
              ></el-table-column>
              <el-table-column
                align="center"
                prop="goodsPrice"
                label="价格"
                width="80"
              ></el-table-column>
              <el-table-column
                align="center"
                prop="stockNum"
                label="库存"
                width="80"
              ></el-table-column>
            </el-table>
          </div>
          <div class="pagination clearfix">
            <div class="fr">
              <el-pagination
                @current-change="goodsTableCurrentChange"
                :current-page="goodsTable_currentPage"
                :page-size="goodsTable_pageSize"
                background
                layout="prev, pager, next"
                :total="goodsTable_listTotal"
              >
              </el-pagination>
            </div>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAddGoods">保 存</el-button>
        <el-button @click="cancelAddGoods">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 选择会员 -->
    <el-dialog
      title="选择会员"
      :visible.sync="addMemberVisible"
      :show-close="false"
      width="65%"
      :close-on-click-modal="false"
    >
      <div class="dialog-container2 clearfix">
        <el-form
          ref="screenForm"
          :model="member_screenForm"
          size="small"
          label-position="left"
        >
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :lg="7">
              <el-form-item label="关键词" prop="keyword" label-width="55px">
                <el-input
                  v-model="member_screenForm.keyword"
                  placeholder="请输入会员名称/电话"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :lg="7">
              <el-form-item
                label="注册日期"
                prop="registerDate"
                label-width="70px"
              >
                <el-date-picker
                  style="width: 100%"
                  v-model="member_screenForm.registerDate"
                  type="daterange"
                  value-format="yyyy-MM-dd"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :lg="7">
              <el-form-item label="" prop="type" label-width="20px">
                <el-radio-group
                  v-model="member_screenForm.type"
                  :disabled="memberList.length > 0 ? true : false"
                >
                  <el-radio :label="'SERVICE'">业务员</el-radio>
                  <el-radio :label="'GENERAL'">普通用户</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :lg="2" class="tr">
              <el-button
                size="small"
                type="primary"
                @click="getMemberListByScreen"
                >搜索</el-button
              >
            </el-col>
          </el-row>
        </el-form>
        <div class="table memberTable" style="margin: 10px 0 20px">
          <el-table
            v-loading="memberTable_listLoading"
            :data="memberTable_dataList"
            element-loading-text="Loading"
            tooltip-effect="dark"
            style="width: 100%"
            max-height="360"
            @selection-change="handleChooseMember"
          >
            <el-table-column
              align="center"
              type="selection"
              :selectable="checkboxSelect"
              width="45"
            ></el-table-column>
            <el-table-column
              align="center"
              prop="nickName"
              label="会员名称"
              min-width="150"
            ></el-table-column>
            <el-table-column
              align="center"
              prop="sex"
              label="性别"
              min-width="100"
            ></el-table-column>
            <!-- <el-table-column align="center" label="地区" prop="city" min-width="100">
              <template slot-scope="scope">
                {{ scope.row.province }}{{ scope.row.city }}
              </template>
            </el-table-column> -->
            <el-table-column
              align="center"
              prop="mobile"
              label="注册手机"
              min-width="100"
            ></el-table-column>
            <!-- <el-table-column align="center" prop="createTime" label="注册时间" min-width="100"></el-table-column> -->
            <el-table-column
              align="center"
              prop="memberName"
              label="角色"
              min-width="100"
            >
              <template slot-scope="scope">
                {{ scope.row.type | MEMBER_CURRENT_TYPE_FILTER }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="memberName"
              label="状态"
              min-width="100"
            >
              <template slot-scope="scope">
                <el-tag :type="scope.row.status ? 'success' : 'danger'">{{
                  scope.row.status | MEMBER_CURRENT_STATUS_FILTER
                }}</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination clearfix">
          <div class="fr">
            <el-pagination
              @current-change="memberTableCurrentChange"
              :current-page="memberTable_currentPage"
              :page-size="memberTable_pageSize"
              background
              layout="prev, pager, next"
              :total="memberTable_listTotal"
            >
            </el-pagination>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAddMember">保 存</el-button>
        <el-button @click="cancelAddMember">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addCoupon,
  changeCouponFlag,
  editCoupon,
  getCouponDetail,
  getList,
  getClassifyList,
  getGoodsList,
  getTagList,
  getMemberList,
  reissueCoupon,
} from "@/api/coupon";
import { MEMBER_CURRENT_TYPE, COUPON_CURRENT_FLAG } from "@/utils/select_data";
import { downloadFiles } from "@/utils/util";
import { getToken } from "@/utils/auth";

export default {
  filters: {
    typeFilter(type) {
      const typeMap = {
        SATISFY: "满减券",
        DISCOUNT: "折扣券",
        RANDOM: "随机金额券",
        GOODS: "商品券",
      };
      return typeMap[type];
    },
  },
  data() {
    return {
      baseURL: process.env.VUE_APP_BASE_API,
      myHeaders: { "x-token": getToken() },
      tagList: [],
      tagValue: [],
      dataList: null, // 列表数据
      listLoading: true, // 列表加载loading
      screenForm: {
        // 筛选表单数据
        couponName: "", // 优惠券名称
        flag: "", // 标志
      },
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页数量
      listTotal: 0, // 列表总数
      select_flag: COUPON_CURRENT_FLAG,
      editId: null,
      addFormType: "add",
      addFormVisible: false,
      addForm: {
        activeDay: "", // 有效时间
        activeDate: [], // 使用时间
        receiveDate: [], // 领取时间
        displayDate: "", // 显示时间
        couponId: "",
        couponName: "", // 优惠券名称
        couponAmount: 0, // 发放数量
        couponType: "SATISFY", // 优惠券类型
        receiveCrowd: 3, // 领取条件
        orderAmount: 0, // 订单满足金额
        activeType: 1, // 用券时间类型（不需要填）
        receiveLimitCount: 1, // 每人领用张数
        shareTimes: 1, // 每人分享次数
        couponValue: 0, // 优惠券面值
        note: "", // 使用说明
        remark: "", // 备注
        flag: "",
        imgUrl: "",
        imgHover: false,
      },
      addFormRules: {
        couponName: [
          { required: true, message: "请填写优惠券名称", trigger: "blur" },
        ],
        couponType: [
          { required: true, message: "请选择优惠券类型", trigger: "change" },
        ],
        receiveCrowd: [
          { required: true, message: "请选择领取条件", trigger: "change" },
        ],
        receiveLimitCount: [
          { required: true, message: "请填写每人领用张数", trigger: "blur" },
        ],
        shareTimes: [
          { required: true, message: "请填写每人分享次数", trigger: "blur" },
        ],
        couponValue: [
          { required: true, message: "请填写优惠券面值", trigger: "blur" },
        ],
        couponAmount: [
          { required: true, message: "请填写发放数量", trigger: "blur" },
        ],
        orderAmount: [
          { required: true, message: "请输填写订单满足金额", trigger: "blur" },
        ],
        // activeDate: [
        //   { required: true, message: '请选择使用时间', trigger: 'change' }
        // ],
        receiveDate: [
          { required: true, message: "请选择领取时间", trigger: "change" },
        ],
        displayDate: [
          { required: true, message: "请选择显示时间", trigger: "change" },
        ],
        note: [{ required: true, message: "请填写使用说明", trigger: "blur" }],
      },

      goodsList: [], // 商品数据
      addGoodsVisible: false,
      maxGoodsCount: 10000000,
      classifyList: [],
      classifyCurrent: "",
      goods_keyword: "",
      goodsTable_dataList: null, // 列表数据
      goodsTable_listLoading: true, // 列表加载loading
      goodsTable_currentPage: 1, // 当前页码
      goodsTable_pageSize: 10, // 每页数量
      goodsTable_listTotal: 0, // 列表总数
      goodsTable_choose: [], // table中 当前选择商品

      memberList: [], // 会员数据
      addMemberVisible: false,
      member_screenForm: {
        // 筛选表单数据
        keyword: "", // 名称
        registerDate: [],
        type: "SERVICE",
      },
      memberTable_dataList: null, // 列表数据
      memberTable_listLoading: true, // 列表加载loading
      memberTable_currentPage: 1, // 当前页码
      memberTable_pageSize: 10, // 每页数量
      memberTable_listTotal: 0, // 列表总数
      memberTable_choose: [], // table中 当前选择会员

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

      select_type: MEMBER_CURRENT_TYPE,
    };
  },
  computed: {
    isService() {
      if (this.addForm.receiveCrowd == 3) {
        return true;
      }
      if (this.addForm.receiveCrowd == 2 && this.memberType == "SERVICE") {
        return true;
      }
      return false;
    },

    memberType() {
      if (this.memberList.length > 0) {
        return this.memberList[0].type;
      } else {
        return "";
      }
    },
  },
  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();
    },

    dateCompute(row, type) {
      if (type === 1) {
        return (
          row.activeStartTime.split(" ")[0].replaceAll("-", ".") +
          " - " +
          row.activeEndTime.split(" ")[0].replaceAll("-", ".")
        );
      } else {
        if (row.releaseStartTime) {
          return (
            row.releaseStartTime.split(" ")[0].replaceAll("-", ".") +
            " - " +
            row.releaseEndTime.split(" ")[0].replaceAll("-", ".")
          );
        }
        return "";
      }
    },

    // 获取标签列表
    getTagList() {
      getTagList({
        pageNum: 1,
        pageSize: 1000,
      }).then((res) => {
        res.data.records.forEach((item) => {
          item.value = item.tagId;
          item.tagName = item.name;
        });
        this.tagList = res.data.records;
      });
    },

    addOrEdit(type, id) {
      this.addFormType = type;
      this.addFormVisible = true;
      this.getTagList();
      if (type == "edit") {
        this.editId = id;
        getCouponDetail({ couponId: id }).then((res) => {
          this.addForm = {
            couponId: res.data.couponId,
            couponName: res.data.couponName,
            couponAmount: res.data.couponAmount,
            couponType: res.data.couponType,
            orderAmount: res.data.orderAmount,
            activeType: res.data.activeType,
            receiveCrowd: res.data.receiveCrowd,
            receiveLimitCount: res.data.receiveLimitCount,
            shareTimes: res.data.shareTimes,
            couponValue: res.data.couponValue,
            note: res.data.note,
            remark: res.data.remark,
            flag: res.data.flag,
            displayDate: res.data.displayTime,
            activeDay: res.data.activeDay,
            imgUrl: res.data.imgSrc,
            imgHover: false,
          };
          this.$set(this.addForm, "activeDate", [
            res.data.activeStartTime.split(" ")[0],
            res.data.activeEndTime.split(" ")[0],
          ]);
          this.$set(this.addForm, "receiveDate", [
            res.data.obtainStartTime.split(" ")[0],
            res.data.obtainEndTime.split(" ")[0],
          ]);
          this.goodsList = res.data.goodsList;
          this.memberList = res.data.userList;
          res.data.tagList.forEach((item) => {
            item.value = item.tagId;
          });
          this.tagValue = res.data.tagList;
        });
      } else {
        this.addForm.flag = "";
      }
    },

    // 取消 新增编辑
    cancelAddForm() {
      this.addFormVisible = false;
      this.$refs.addForm.resetFields();
    },

    // 提交 新增编辑
    submitAddForm() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          if (
            !this.addForm.activeDay &&
            (!this.addForm.activeDate || !this.addForm.activeDate.length)
          ) {
            return this.$errorMsg("请选择使用时间 或 填写有效时间");
          }
          let params = {
            couponName: this.addForm.couponName,
            couponAmount: this.addForm.couponAmount,
            couponType: this.addForm.couponType,
            activeType: this.addForm.activeType,
            activeDay: this.addForm.activeDay,
            activeStartTime:
              this.addForm.activeDate && this.addForm.activeDate[0]
                ? this.addForm.activeDate[0] + " 00:00:00"
                : "",
            activeEndTime:
              this.addForm.activeDate && this.addForm.activeDate[1]
                ? this.addForm.activeDate[1] + " 23:59:59"
                : "",
            obtainStartTime: this.addForm.receiveDate[0] + " 00:00:00",
            obtainEndTime: this.addForm.receiveDate[1] + " 23:59:59",
            displayTime: this.addForm.displayDate + " 00:00:00",
            receiveCrowd: this.addForm.receiveCrowd,
            receiveLimitCount: this.addForm.receiveLimitCount,
            shareTimes: this.addForm.shareTimes,
            couponValue: this.addForm.couponValue,
            note: this.addForm.note,
            remark: this.addForm.remark,
            imgSrc: this.addForm.imgUrl,
          };
          if (this.addForm.couponType == "SATISFY") {
            params.orderAmount = this.addForm.orderAmount;
          } else if (this.addForm.couponType == "GOODS") {
            params.goodsList = this.goodsList;
          }
          if (this.addForm.receiveCrowd === 1) {
            if (this.tagValue.length < 1) {
              return this.$errorMsg("请选择标签");
            }
            params.tagList = this.tagValue;
          } else if (this.addForm.receiveCrowd === 2) {
            if (this.memberList.length < 1) {
              return this.$errorMsg("请选择会员");
            }
            params.userList = this.memberList;
          }
          if (this.addFormType == "edit") {
            params.couponId = this.editId;
            editCoupon(params).then((res) => {
              this.$successMsg("编辑成功");
              this.getList();
              this.cancelAddForm();
            });
          } else {
            addCoupon(params).then((res) => {
              this.$successMsg("新增成功");
              this.getList();
              this.cancelAddForm();
            });
          }
        }
      });
    },

    // 获取分类列表
    getClassifyList() {
      getClassifyList({ categoryLevel: 1, status: true }).then((res) => {
        res.data.forEach((item) => {
          item.isOpen = false;
        });
        this.classifyList = res.data;
        this.classifyCurrent = "";
        this.getGoodsList();
      });
    },

    // 展开/收起 分类
    toggleOpen(index) {
      this.classifyList[index].isOpen = !this.classifyList[index].isOpen;
    },

    // 切换分类
    changeClassify(cid) {
      if (this.goodsTable_choose.length > 0) {
        return this.$errorMsg("当前已选择商品，不可切换分类");
      }
      this.classifyCurrent = cid;
      this.goodsTable_currentPage = 1;
      this.getGoodsList();
    },

    // 搜索
    getGoodsListByScreen() {
      if (this.goodsTable_choose.length > 0) {
        return this.$errorMsg("当前已选择商品，不可搜索");
      }
      this.goodsTable_currentPage = 1;
      this.getGoodsList();
    },

    // 获取商品列表
    getGoodsList() {
      getGoodsList({
        pageNum: this.goodsTable_currentPage,
        pageSize: this.goodsTable_pageSize,
        keyword: this.goods_keyword,
        categoryId: this.classifyCurrent,
      }).then((res) => {
        let oldGoodsList = this.goodsList;
        let newGoodsList = res.data.records;
        for (let i = 0; i < oldGoodsList.length; i++) {
          let oldItem = oldGoodsList[i];
          for (let j = 0; j < newGoodsList.length; j++) {
            let newItem = newGoodsList[j];
            if (newItem.goodsId === oldItem.goodsId) {
              newGoodsList[j].selected = true;
              break;
            }
          }
        }
        this.goodsTable_dataList = newGoodsList;
        this.goodsTable_listTotal = res.data.total;
        this.goodsTable_listLoading = false;
      });
    },

    // 查询重复值并禁选
    checkboxSelect(row, rowIndex) {
      if (row.selected) {
        return false; // 禁用
      } else {
        return true; // 不禁用
      }
    },

    // 更改列表当前页
    goodsTableCurrentChange(val) {
      if (this.goodsTable_choose.length > 0) {
        return this.$errorMsg("当前已选择商品，不可切换分页");
      }
      this.goodsTable_currentPage = val;
      this.getGoodsList();
    },

    // table点击选择商品
    handleChooseGoods(val) {
      this.goodsTable_choose = val;
    },

    // 添加商品
    addGoods() {
      this.addGoodsVisible = true;
      this.getGoodsList();
    },

    // 删除商品
    deleteGoods(index) {
      this.goodsList.splice(index, 1);
    },

    // 取消 选择商品
    cancelAddGoods() {
      this.addGoodsVisible = false;
    },

    // 提交 选择商品
    submitAddGoods() {
      // if(this.goodsTable_choose.length > 1) {
      //   return this.$errorMsg('每次只能选择一个商品');
      // }
      let oldGoodsList = this.goodsList;
      let newGoodsList = this.goodsTable_choose;
      this.goodsList = oldGoodsList.concat(newGoodsList);
      this.addGoodsVisible = false;
    },

    // 搜索
    getMemberListByScreen() {
      if (this.memberTable_choose.length > 0) {
        return this.$errorMsg("当前已选择会员，不可搜索");
      }
      this.memberTable_currentPage = 1;
      this.getMemberList();
    },

    // 获取会员列表
    getMemberList() {
      getMemberList({
        pageNum: this.memberTable_currentPage,
        pageSize: this.memberTable_pageSize,
        keyword: this.member_screenForm.keyword,
        type: this.member_screenForm.type,
        startTime:
          this.member_screenForm.registerDate &&
          this.member_screenForm.registerDate[0]
            ? this.member_screenForm.registerDate[0] + " 00:00:00"
            : null,
        endTime:
          this.member_screenForm.registerDate &&
          this.member_screenForm.registerDate[1]
            ? this.member_screenForm.registerDate[1] + " 23:59:59"
            : null,
      }).then((res) => {
        let oldMemberList = this.memberList;
        let newMemberList = res.data.records;
        for (let i = 0; i < oldMemberList.length; i++) {
          let oldItem = oldMemberList[i];
          for (let j = 0; j < newMemberList.length; j++) {
            let newItem = newMemberList[j];
            if (newItem.userId === oldItem.userId) {
              newMemberList[j].selected = true;
              break;
            }
          }
        }
        this.memberTable_dataList = newMemberList;
        this.memberTable_listTotal = res.data.total;
        this.memberTable_listLoading = false;
      });
    },

    // 更改列表当前页
    memberTableCurrentChange(val) {
      if (this.memberTable_choose.length > 0) {
        return this.$errorMsg("当前已选择会员，不可切换分页");
      }
      this.memberTable_currentPage = val;
      this.getMemberList();
    },

    // table点击选择会员
    handleChooseMember(val) {
      this.memberTable_choose = val;
    },

    // 添加会员
    addMember() {
      this.addMemberVisible = true;

      if (this.memberList.length > 0) {
        this.member_screenForm.type = this.memberList[0].type;
      }

      this.getMemberList();
    },

    // 删除会员
    deleteMember(index) {
      this.memberList.splice(index, 1);
    },

    // 取消 选择会员
    cancelAddMember() {
      this.addMemberVisible = false;
    },

    // 提交 选择会员
    submitAddMember() {
      // if(this.memberTable_choose.length > 1) {
      //   return this.$errorMsg('每次只能选择一个会员');
      // }
      let oldMemberList = this.memberList;
      let newMemberList = this.memberTable_choose;
      this.memberList = oldMemberList.concat(newMemberList);
      this.addMemberVisible = false;
    },

    // 操作 - 更改优惠券标志为取消
    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();
      });
    },

    uploadImage() {
      document.querySelector(".avatar-uploader input").click();
    },

    // 上传图片
    uploadSuccess(res, file) {
      this.addForm.imgUrl = res.data.url;
    },

    beforeUpload(file) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
      const whiteList = ["jpg", "jpeg", "png"];
      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$errorMsg("只支持上传jpg/jpeg/png文件!");
        return false;
      }
    },

    // 预览图片
    previewImage() {
      this.$refs.img.showViewer = true;
    },
  },
};
</script>

<style scoped lang="scss">
.dialog-container {
  .left {
    width: 140px;
    height: 350px;
    overflow-y: scroll;
    .group {
      margin-top: 10px;
    }
    .child {
      margin-top: 5px;
      .item {
        padding-left: 18px;
      }
    }
    .item {
      cursor: pointer;
      line-height: 24px;
    }
  }
  .right {
    width: calc(100% - 140px);
    height: 350px;
    box-sizing: border-box;
    padding-left: 20px;
  }
}
.goods-container {
  .item {
    margin-bottom: 10px;
    &:last-child {
      margin-bottom: 0;
    }
  }
}
.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);
    }
  }
}

.addMember {
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #ebeef5;
  border-top: none;
  height: 50px;
}

// .memberTable {
//   ::v-deep .el-table__header-wrapper .el-checkbox {
//     display: none;
//   }
// }

.images {
  display: flex;
  flex-wrap: wrap;
  .main-img {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 120px;
    margin-right: 20px;
    .img {
      border: 1px dashed #eaeaea;
      border-radius: 5px;
      overflow: hidden;
      position: relative;
      .el-image {
        display: block;
      }
      .mask {
        position: absolute;
        left: 0;
        top: 0;
        width: 120px;
        height: 120px;
        background: rgba($color: #000000, $alpha: 0.3);
        display: flex;
        align-items: center;
        justify-content: center;
        i {
          font-size: 20px;
          color: #ffffff;
          cursor: pointer;
          margin: 0 8px;
        }
      }
    }
    .text {
      font-size: 14px;
      color: #666666;
    }
  }
  .add {
    width: 120px;
    height: 120px;
    border: 1px dashed #eaeaea;
    border-radius: 5px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    i {
      font-size: 30px;
      color: #999;
    }
  }
}
</style>
