<template>
  <div class="app-container">
    <h3 style="margin-bottom: 30px">新增优惠券</h3>

    <div class="form-contaner">
      <el-form ref="addForm" :model="addForm" :rules="addFormRules" label-position="right" label-width="120px">
        <el-form-item label="优惠券名称" prop="couponName">
          <el-input v-model="addForm.couponName" autocomplete="off" placeholder="请输入优惠券名称"></el-input>
        </el-form-item>
        <el-form-item label="优惠券类型" prop="couponType">
          <el-radio-group v-model="addForm.couponType">
            <el-radio label="SATISFY">满减券</el-radio>
            <el-radio label="GOODS">商品券</el-radio>
            <el-radio label="NO_DOOR">无门槛优惠券</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="领取条件" prop="receiveCrowd" v-if="addForm.couponType != 'NO_DOOR'">
          <el-radio-group v-model="addForm.receiveCrowd">
            <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="importUserList" v-if="addForm.couponType == 'NO_DOOR'">
          <div class="clearfix">
            <el-upload
              style="display: block; margin-right: 10px;"
              class="fl"
              :action="'import'"
              :http-request="handleImport"
			        :show-file-list="false"
            >
              <el-button size="small" type="primary" style="display: block;" :loading="importLoading">{{ importLoading ? '导入中...' : '导入' }}</el-button>
            </el-upload>
            <el-button size="small" class="fl" @click="handleDownload">下载导入模板</el-button>
            <el-button size="small" class="fl" @click="importUserList = []; importId = null;">清空</el-button>
          </div>
          <el-table 
            border
            :data="importUserList" 
            tooltip-effect="dark" 
            style="width: 400px" 
            max-height="400">
            <el-table-column align="center" prop="mobile" label="电话"></el-table-column>
            <el-table-column align="center" prop="num" label="发送数量"></el-table-column>
          </el-table>
          <el-pagination
            style="margin-top: 10px"
            @current-change="importUserListChange"
            :current-page="importUserListCurPage"
            :page-size="10"
            background
            layout="prev, pager, next"
            :total="importUserListTotal">
          </el-pagination>
        </el-form-item>

        <el-form-item label="选择标签" prop="tagValue" v-if="addForm.receiveCrowd === 1 && addForm.couponType != 'NO_DOOR'">
          <el-select v-model="tagValue" multiple placeholder="请选择标签" style="width: 100%">
            <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 && addForm.couponType != 'NO_DOOR'">
          <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="$imageUrl + scope.row.avatar" :preview-src-list="[$imageUrl + 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="确定删除吗？" @onConfirm="deleteMember(scope.row.userId)" >
                  <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">删除</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="请输入订单满足金额"></el-input>
        </el-form-item>

        <el-form-item label="优惠券面值" prop="couponValue">
          <el-input v-model="addForm.couponValue" autocomplete="off" placeholder="请输入优惠券面值"></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="receiveLimitCount" v-if="!isService">
          <el-input v-model="addForm.receiveLimitCount" autocomplete="off" placeholder="请输入每人领用张数"></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="选择日期时间"
           >
          </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="结束日期"
           >
          </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="结束日期"
           >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="可多张使用" prop="canMultiple">
          <el-radio-group v-model="addForm.canMultiple">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="可叠加活动使用" prop="canOverlying">
          <el-radio-group v-model="addForm.canOverlying">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="可转发分享" prop="canShare">
          <el-radio-group v-model="addForm.canShare">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="使用后可分佣" prop="canCommission">
          <el-radio-group v-model="addForm.canCommission">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发送短信通知" prop="canMessage">
          <el-radio-group v-model="addForm.canMessage">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发送短信内容" prop="msgContent" v-if="addForm.canMessage">
          <el-input
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 6}"
            autocomplete="off"
            placeholder="请输入发送短信内容"
            v-model="addForm.msgContent"
            maxlength="100"
            show-word-limit>
          </el-input>
        </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; opacity: 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="addForm.imgUrl" :preview-src-list="[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>

    <div class="page-footer">
      <div class="footer">
        <el-button type="primary" @click="submitAddForm" :loading="formLoading">{{ formLoading ? '保存中 ...' : '保 存' }}</el-button>
        <el-button @click="goBack">关 闭</el-button>
      </div>
    </div>


    <!-- 选择商品 -->
    <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, getClassifyList, getGoodsList, getTagList, getMemberList, getRequestId, getImportList} from "@/api/coupon";
import { downloadFiles, findElem, handleImport } from '@/utils/util'
import { getToken } from '@/utils/auth'

export default {
  data() {
    return {
      baseURL: process.env.VUE_APP_BASE_API,
      myHeaders: {'x-token': getToken()},
      formLoading: false,
      addForm: {
        activeDate: [], // 使用时间
        receiveDate: [], // 领取时间
        displayDate: '', // 显示时间
        couponId: '',
        couponName: '', // 优惠券名称
        couponAmount: 0, // 发放数量
        couponType: 'SATISFY', // 优惠券类型
        receiveCrowd: 3, // 领取条件
        orderAmount: 0, // 订单满足金额
        activeType: 1, // 用券时间类型（不需要填）
        receiveLimitCount: 1, // 每人领用张数
        couponValue: 0, // 优惠券面值
        note: '', // 使用说明
        remark: '', // 备注
        imgUrl: '',
        imgHover: false,
        canMultiple: true, // 可多张使用
        canOverlying: true, // 可叠加活动使用
        canShare: true, // 可转发分享
        canCommission: true, // 使用后可分佣
        canMessage: true, // 发送短信通知
        msgContent: '', // 发送短信内容
      },
      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' }],
        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' }],
        canMultiple: [{ required: true, trigger: 'change' }],
        canOverlying: [{ required: true, trigger: 'change' }],
        canShare: [{ required: true, trigger: 'change' }],
        canCommission: [{ required: true, trigger: 'change' }],
        canMessage: [{ required: true, trigger: 'change' }],
        msgContent: [{ required: true, message: '请填写发送短信内容', trigger: 'blur' }],
      },

      tagList: [],
      tagValue: [],

      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中 当前选择会员

      importId: null,
      importLoading: false, // 导入加载loading
      importUserList: [],
      importUserListCurPage: 1,
      importUserListTotal: 0,
    }
  },

  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.getTagList();
    this.getClassifyList();
  },

  methods: {
    // 获取标签列表
    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;
      })
    },

    // 获取分类列表
    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(id) {
      let index = findElem(this.goodsList, 'goodsId', id);
      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(id) {
      let index = findElem(this.memberList, 'userId', id);
      this.memberList.splice(index, 1);
    },

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

    // 提交 选择会员
    submitAddMember() {
      let oldMemberList = this.memberList;
      let newMemberList = this.memberTable_choose;
      this.memberList = oldMemberList.concat(newMemberList);
      this.addMemberVisible = false;
    },

    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;
    },

    goBack() {
      this.$router.go(-1)
    },

    async getRequestId() {
      const result = await new Promise((resolve, reject) => {
        getRequestId().then(res => {
          resolve(res.data)
        }).catch(err => {
          reject(err)
        })
      });
      return result;
    },

    // 导入会员
    async handleImport(param) {
      this.importId = await this.getRequestId();

      console.log(param)
      this.importLoading = true;
      const file = param.file;
      const formData = new FormData();
      formData.append("file", file);
      formData.append("reuqestId", this.importId);
      let result = await handleImport('coupon/tmp/import', formData);
      this.importLoading = false;
      if(result.code == 200) {
        this.$alert(result.message, '导入成功', {
          confirmButtonText: '确定'
        });
        this.getImportList();
      }else {
        this.$alert(result.message, '导入失败', {
          confirmButtonText: '确定'
        });
      }
    },

    // 获取导入列表
    getImportList() {
      getImportList({
        pageNum: this.importUserListCurPage,
        pageSize: 10,
        requestId: this.importId
      }).then(res => {
        this.importUserList = res.data.records;
        this.importUserListTotal = res.data.total;
      })
    },

    // 切换导入列表页码
    importUserListChange(val) {
      this.importUserListCurPage = val;
      this.getImportList();
    },

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

    // 提交 新增编辑
    submitAddForm() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          let params = {
            couponName: this.addForm.couponName,
            couponAmount: this.addForm.couponAmount,
            couponType: this.addForm.couponType,
            activeType: this.addForm.activeType,
            activeStartTime: this.addForm.activeDate[0] + ' 00:00:00',
            activeEndTime: 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,
            couponValue: this.addForm.couponValue,
            note: this.addForm.note,
            remark: this.addForm.remark,
            imgSrc: this.addForm.imgUrl,

            isMore: this.addForm.canMultiple,
            isActivity: this.addForm.canOverlying,
            transferType: this.addForm.canShare,
            isAmount: this.addForm.canCommission,
            isSms: this.addForm.canMessage,
            smsContent: this.addForm.msgContent,
          }
          if(this.addForm.couponType == 'SATISFY') {
            params.orderAmount = this.addForm.orderAmount;
          }else if(this.addForm.couponType == 'GOODS') {
            params.goodsList = this.goodsList;
          }else if(this.addForm.couponType == 'NO_DOOR') {
            if(!this.importId) return this.$errorMsg('请导入会员');
            params.requestId = this.importId;
            params.receiveCrowd = 2;
          }
          if(this.addForm.receiveCrowd === 1 && this.addForm.couponType != 'NO_DOOR') {
            if(this.tagValue.length < 1) {
              return this.$errorMsg('请选择标签');
            }
            params.tagList = this.tagValue;
          }else if(this.addForm.receiveCrowd === 2 && this.addForm.couponType != 'NO_DOOR') {
            if(this.memberList.length < 1) {
              return this.$errorMsg('请选择会员');
            }
            params.userList = this.memberList;
          }
          
          addCoupon(params).then(res => {
            this.$successMsg('新增成功');
            setTimeout(()=>{
              this.goBack();
            }, 1000)
          })
        }
      })
    },

  }

}
</script>

<style scoped lang="scss">
  ::v-deep .el-upload {
    display: block;
  }
  .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;
      }
    }
  }

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

  .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>