<template>
  <div class="hy_">
    <div class="tab-box">
      <div class="tab_" :class="{active:index== tabindex }" @click="getindex(index)" v-for="(item,index) in  tabs"
           :key="index">
        {{ item.name }}
      </div>
    </div>

    <div class="cot-box" v-if="tabindex==0">
      <div style="display: flex;align-items: center;justify-content: space-between">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
          <el-form-item label="" prop="userNo">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入会员昵称"
              clearable
              style="width: 210px;"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="" prop="userNo">
            <el-input
              v-model="queryParams.userNo"
              placeholder="请输入会员号"
              clearable
              style="width: 210px;"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="" prop="gradeId">
            <el-select
              v-model="queryParams.gradeId"
              clearable
              style="width: 210px"
              placeholder="请选择会员等级"
            >
              <el-option v-for="grade in userGradeList" :key="grade.id+''" :label="grade.name" :value="grade.id+''"/>
            </el-select>
          </el-form-item>
          <el-form-item label="" prop="gradeId">
            <el-select
              v-model="queryParams.gradeId"
              clearable
              style="width: 210px"
              placeholder="请选择会员标签"
            >
              <el-option v-for="grade in userGradeList" :key="grade.id+''" :label="grade.name" :value="grade.id+''"/>
            </el-select>
          </el-form-item>
          <el-form-item label="" prop="userNo">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入车牌号"
              clearable
              style="width: 210px;"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label=""  prop="gradeId">
            <el-select
              v-model="queryParams.gradeId"
              clearable
              style="width: 210px"
              placeholder="请选择性别"
            >
              <el-option v-for="grade in userGradeList" :key="grade.id+''" :label="grade.name" :value="grade.id+''"/>
            </el-select>
          </el-form-item>
          <el-form-item label="" style="margin-right: 0px" prop="mobile">
            <el-input
              v-model="queryParams.mobile"
              placeholder="请输入手机号"
              clearable
              style="width: 210px;"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="" prop="gradeId">
            <el-select
              v-model="queryParams.userStatus"
              clearable
              style="width: 210px"
              placeholder="请选择状态"
            >
              <el-option v-for="grade in userStatusList"
                         :key="grade.value"
                         :label="grade.label"
                         :value="grade.value"/>
            </el-select>
          </el-form-item>
          <el-form-item label="">
            <el-input
              v-model="queryParams.age"
              placeholder="请输入年龄"
              clearable
              style="width: 140px;"
              @keyup.enter.native="handleQuery"
            />
         至
            <el-input
              v-model="queryParams.age"
              placeholder="请输入年龄"
              clearable
              style="width: 140px;"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="">
            <el-date-picker
              v-model="beginTime"
              style="width: 140px"
              type="date"
              placeholder="开始日期">
            </el-date-picker>
            至
            <el-date-picker
              v-model="endTime"
              style="width: 140px"
              type="date"
              placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="">
            <el-input
              v-model="queryParams.age"
              placeholder="请输入剩余积分"
              clearable
              style="width: 140px;"
              @keyup.enter.native="handleQuery"
            />
            至
            <el-input
              v-model="queryParams.age"
              placeholder="请输入剩余积分"
              clearable
              style="width: 140px;"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <div style="float: right">
            <el-button style="background: linear-gradient( 180deg, #FF8646 0%, #FFA360 100%); border: transparent "
                       type="primary" @click="handleQuery">搜索
            </el-button>
            <el-button @click="resetQuery">重置</el-button>
            <!--          <el-button type="primary" @click="handleAdd" v-hasPermi="['member:index:add']" >新增</el-button>-->
            <el-button type="primary" @click="addOne"
                       v-hasPermi="['member:index:add']"

            >新增会员
            </el-button>
            <el-button type="primary" @click="addMult"
                       v-hasPermi="['member:index:add']"

            >批量新增
            </el-button>
            <el-button type="primary" @click="handleMassSend"
                       v-hasPermi="['member:index:add']"

            >会员群发
            </el-button>
          </div>


        </el-form>
      </div>
      <div style="height: 62vh;overflow: auto;margin-top: 15px;margin-bottom: 15px">
        <el-table ref="tables" v-loading="loading" :data="list" border
                  @selection-change="handleSelectionChange" :default-sort="defaultSort"
                  @sort-change="handleSortChange">
          <el-table-column type="index" width="50" align="center" label="序号"/>
          <el-table-column label="会员名称" align="center" prop="name">
            <template slot-scope="scope">
              <span style="color: #fe8c4a;cursor: pointer  "
                    @click="goDedi(scope.row.id)">{{ scope.row.name ? scope.row.name : "--" }}</span>
            </template>
          </el-table-column>
          <el-table-column label="会员卡号" align="center" prop="userNo" />
          <el-table-column label="会员等级" align="center" prop="gradeId" >
            <template slot-scope="scope">
              <span>{{ scope.row.gradeId ? getName(allUserGrade, scope.row.gradeId) : '--' }}</span>
            </template>
          </el-table-column>

          <el-table-column label="会员标签" align="center" prop="userLabelName" >
            <template slot-scope="scope">
              <span>{{ scope.row.userLabelName || '--' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="车牌号" align="center" prop="carNo" >
            <template slot-scope="scope">
              <span>{{ scope.row.carNo || '--' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="手机号" align="center" prop="mobile" >
            <template slot-scope="scope">
              <span>{{ scope.row.mobile ? scope.row.mobile : '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="生日" align="center" prop="birthday" >
            <template slot-scope="scope">
              <span>{{ scope.row.birthday || '--' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="userStatus">
            <template slot-scope="scope">
              <div v-if="scope.row.userStatus == '0' " style="color: #00CAFF;">使用中</div>
              <div v-else style="color: #F44522">已注销</div>
            </template>
          </el-table-column>
          <el-table-column label="充值次数" align="center" prop="rechargeNum">
            <template slot-scope="scope">
              <div>{{ scope.row.rechargeNum || 0 }}</div>
            </template>
          </el-table-column>
          <el-table-column label="余额（元）" align="center" prop="cardBalance">
            <template slot-scope="scope">
              <div>{{ scope.row.cardBalance ? scope.row.cardBalance.toFixed(2) : 0 }}</div>
            </template>
          </el-table-column>
          <el-table-column label="已使用金额（元）" align="center" prop="usedAmount">
            <template slot-scope="scope">
              <div>{{ scope.row.usedAmount || 0 }}</div>
            </template>
          </el-table-column>
          <el-table-column label="剩余积分" align="center" prop="points">
            <template slot-scope="scope">
              <div><span>{{ scope.row.points ? scope.row.points : 0 }}</span></div>
            </template>
          </el-table-column>
          <el-table-column label="已使用积分" align="center" prop="points">
            <template slot-scope="scope">
              <div><span>{{ scope.row.usedPoints || 0 }}</span></div>
            </template>
          </el-table-column>
          <el-table-column label="成长值" align="center" prop="growthValue">
            <template slot-scope="scope">
              <div>{{ scope.row.growthValue || '0' }}</div>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" width="160" prop="balCreateTime"/>
          <el-table-column label="操作" align="center" width="150" fixed='right'>
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.userStatus == '0'"
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >修改
              </el-button>
              <el-button
                v-if="scope.row.userStatus == '0'"
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleLogOff(scope.row)"
              >会员注销
              </el-button>
              <el-button
                v-if="scope.row.userStatus == '1'"
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <div class="cot-box" v-if="tabindex==1">
      <div>
        <el-form :model="queryParams2" ref="queryForm" size="small" :inline="true" label-width="68px">

          <el-form-item label="" prop="activityName" style="width: 210px">
            <el-input
              v-model="queryParams2.activityName"
              placeholder="请输入群发名称"
              clearable
              @keyup.enter.native="handleQuery1"></el-input>
          </el-form-item>
          <el-form-item label="" prop="groupName" style="width: 210px">
            <el-select v-model="queryParams2.status" placeholder="请选择">
              <el-option label="已发送" value="0"></el-option>
              <el-option label="发送失败" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="">
            <el-date-picker
              v-model="beginTime2"
              style="width: 160px"
              type="date"
              placeholder="开始日期">
            </el-date-picker>
            至
            <el-date-picker
              v-model="endTime2"
              style="width: 160px"
              type="date"
              placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item style="float: right;margin-right: 0px">
            <el-button type="primary" icon="el-icon-search" @click="handleQuery1">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery1">重置</el-button>
          </el-form-item>

        </el-form>
      </div>
      <!--      -->
      <div style="height: 72vh;overflow: auto">
        <el-table
          :data="massSendRecordList"
          border
          style="width: 100%">
          <el-table-column type="index" width="50" align="center" label="序号"/>
          <el-table-column prop="activityName" label="活动名称" width="180">
            <template slot-scope="scope">
              <span>{{ scope.row.activityName || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="sendGift" label="群发礼品">
            <template slot-scope="scope">
              <span>{{ scope.row.sendGift || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="sendWay" label="群发方式">
            <template slot-scope="scope">
              <span>{{ scope.row.sendWay || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="massContent" label="群发内容" width="220">
            <template slot-scope="scope">
              <span>{{ scope.row.massContent || 0 }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="userNum" label="群发会员数量" width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.userNum || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="successNum" label="成功数量">
            <template slot-scope="scope">
              <span>{{ scope.row.successNum || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="failNum" label="失败数量">
            <template slot-scope="scope">
              <span>{{ scope.row.failNum || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态">
            <template slot-scope="scope">
              <div v-if="scope.row.status == 0" style="color: #0DC291">已发送</div>
              <div v-if="scope.row.status == 1" style="color: #F44522">发送失败</div>
            </template>
          </el-table-column>
          <el-table-column prop="address" label="已领取数量">
            <template slot-scope="scope">
              <span>{{ scope.row.userNum || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="address" label="已核销数量">
            <template slot-scope="scope">
              <span>{{ scope.row.userNum || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="address" label="未核销数量">
            <template slot-scope="scope">
              <span>{{ scope.row.userNum || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="accountName" label="操作人员"></el-table-column>
          <el-table-column prop="createTime" label="群发时间" width="160"></el-table-column>
          <el-table-column align="center" label="操作" width="120">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="handleDelete1(scope.row)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <pagination
        v-show="total2>0"
        :total="total2"
        :page.sync="queryParams2.page"
        :limit.sync="queryParams2.pageSize"
        @pagination="getList1"
      />
    </div>
    <div style="width: 100%;height: 10px;"></div>

    <!--    添加会员信息，选择是否批量录入-->
    <el-dialog center :close-on-click-modal="false" :title="title" width="40%" :visible.sync="openUser" append-to-body>
      <el-alert
        type="info"
        :closable="false">
        <p v-for="(item,index) in addMember" :id="index">
          {{ item }}
        </p>
      </el-alert>
      <div style="margin: 10px 0">
        <el-button type="primary"
                   icon="el-icon-edit-outline" @click="addOne" round>录入单个会员
        </el-button>
        <el-button type="primary"
                   icon="el-icon-connection" @click="addMult" round>批量导入会员
        </el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改对话框 -->
    <el-dialog center :close-on-click-modal="false" :title="title" width="30%" :visible.sync="open" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="会员名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入会员名称" maxlength="30"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="form.mobile" placeholder="请输入手机号" maxlength="30"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="性别" prop="sex">
              <div class="d-s">
                <div class="icon-type" v-for="(item,index) in sexTypelist" :key="index"
                     :class="{ 'acvtive1' : index === tindex }" @click="Typeindex(index)">
                  <img src="../../assets/images/wx.png" style="width: 20px;height: 20px" v-if="index != tindex">
                  <img src="../../assets/images/xz.png" style="width: 20px;height: 20px" v-if="index == tindex">
                  {{ item }}
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="会员号" prop="userNo">
              <el-input v-model="form.userNo" :disabled="form.id" placeholder="请输入会员号，为空系统将自动分配" maxlength="30"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="会员等级" prop="gradeId">
              <el-select
                v-model="form.gradeId"
                placeholder="请选择会员等级"
                style="width: 100%"
              >
                <el-option v-for="grade in userGradeList" :key="grade.id+''" :label="grade.name" :value="grade.id"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="会员标签" prop="userLabelId">
              <el-select
                multiple
                v-model="form.userLabelId"
                placeholder="请选择会员标签（多选）"
                style="width: 100%"
              >
                <el-option v-for="(item,index) in userLabelList" :key="index" :label="item.labelName"
                           :value="item.id+''"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="会员生日" prop="birthday">
              <el-date-picker
                v-model="form.birthday"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="车牌号" prop="carNo">
              <el-input v-model="form.carNo" placeholder="请输入车牌号" maxlength="30"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="所属机构" prop="storeId" v-if="form.id">
              <el-select
                v-model="form.mubStoreId"
                placeholder="请选择所属机构"
                style="width: 100%"
              >
                <el-option v-for="(item,index) in storeList" :key="index" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="身份证号" prop="idcard">
              <el-input v-model="form.idcard" placeholder="请输入身份证号" maxlength="30"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="初始积分" prop="points" v-if="!form.id">
              <el-input v-model="form.points" placeholder="请输入会员初始积分"
                        maxlength="30"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="初始成长值" prop="growthValue" v-if="!form.id">
              <el-input v-model="form.growthValue" placeholder="请输入会员初始成长值"
                        maxlength="30"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="储值余额" prop="cardBalance" v-if="!form.id">
              <el-input v-model="form.cardBalance" placeholder="请输入储值卡初始余额"
                        maxlength="30"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="会员状态" prop="userStatus">
              <el-switch
                v-model="form.userStatus"
                active-value="0"
                inactive-value="1"
                active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </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 center :close-on-click-modal="false" :title="title" width="30%" :visible.sync="openMassSend" append-to-body>
      <el-form ref="form1" :model="form1" :rules="rules1" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="群发名称" prop="name">
              <el-input v-model="form1.name" placeholder="请输入群发名称" maxlength="30"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="群发方式" prop="sendWay">
              <div style="display: flex">
                <el-checkbox-group v-model="form1.sendWay">
                  <el-checkbox label="短信消息"></el-checkbox>
                </el-checkbox-group>
                <el-tooltip class="item" effect="light" content="仅对有手机号的会员进行群发" placement="right">
                  <img style="width: 16px;height: 16px;margin-top: 9px;margin-left: 10px"
                       src="@/assets/images/wenhao.png">
                </el-tooltip>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="群发礼品" prop="senfGift">
              <el-checkbox-group v-model="form1.senfGift">
                <el-checkbox label="积分"></el-checkbox>
                <el-checkbox label="优惠券"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="短信模板" prop="messageId" v-if="title != '修改会员'">
              <el-select v-model="form1.messageId" placeholder="请选择短信模板名称" style="width: 100%">
                <el-option v-for="(item,index) in messageList" :key="index" :label="item.name"
                           :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="群发会员数量">
          {{ form1.sendUserNum }}
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm1">确 定</el-button>
        <el-button @click="openMassSend = false">取 消</el-button>
      </div>
    </el-dialog>

    <!--    批量录入会员信息-->
    <el-dialog center :title="title" :close-on-click-modal="false" width="500px" :visible.sync="openUpload" append-to-body>
      <el-form ref="form1" :model="form1" :rules="rules1" label-width="90px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="会员等级" prop="messageId" v-if="title != '修改会员'">
              <el-select v-model="form1.messageId" placeholder="请选择短信模板名称" style="width: 100%">
                <el-option v-for="(item,index) in messageList" :key="index" :label="item.name"
                           :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="会员标签" prop="" v-if="title != '修改会员'">
              <el-select v-model="form1.messageId" placeholder="请选择短信模板名称" style="width: 100%">
                <el-option v-for="(item,index) in messageList" :key="index" :label="item.name"
                           :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="会员导入">
          <div style="display: flex">
            <el-upload
              class="avatar-uploader"
              style="border-radius: 8px;"
              action="https://jsonplaceholder.typicode.com/posts/"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <div v-else>
                <img src="./imgs/imgbk.png" style="width: 100px;height: 100px">
              </div>
            </el-upload>
            <div style="height: 15px;margin-top: 72px;margin-left: 10px">
              <el-link  type="primary">导入下载模版</el-link>
            </div>

          </div>
          <div style="width: 100%;font-size: 12px;color: #999999;line-height: 20px;">
            批量导入会员，单次最大支持5000个会员手机号认证，请确保用户手机号
            未注册过油站会员，否则无法添加会员信息
          </div>
        </el-form-item>


      </el-form>
      <div  style=" width: 100%; display: flex;align-items: center; justify-content: center">
        <el-button @click="openUpload = fasle">取 消</el-button>
        <el-button type="primary" @click="submitForm">导 入</el-button>

      </div>
    </el-dialog>

    <!--    批量导入结果-->
    <el-dialog center width="400px" style="margin-top: 150px" :title="title" :visible.sync="openResult" append-to-body>
      <div class="huiyuan">
        会员总数：<span class="num">{{ result.total }}</span> 人
      </div>
      <div class="huiyuan">
        成功人数：<span class="num">{{ result.success }}</span> 人
      </div>
      <div class="huiyuan">
        失败人数：<span class="num">{{ result.error }}</span> 人
        <span v-if="result.error!=0" style="color: red;font-size: 12px">手机号不可为空</span>
      </div>
      <div class="huiyuan">
        重复人数：<span class="num">{{ result.repeat }}</span> 人
      </div>
    </el-dialog>

    <!-- 余额充值对话框 -->
    <balanceRecharge :showDialog="openBalance" :userId="userId" @closeDialog="closeDialog" @close="closeDialog"/>

    <!-- 积分充值对话框 -->
    <pointRecharge :showDialog="openPoint" :userId="userId" @closeDialog="closeDialog" @close="closeDialog"/>
  </div>
</template>

<script>
import {updateMemberStatus} from "@/api/member";
import balanceRecharge from "./balanceRecharge";
import pointRecharge from "./pointRecharge";
import {
  addUser,
  delUser,
  getUser, getUserPhone,
  listStatistic,
  listUser, listUserStatistic, logOffUsers,
  updateUser
} from "@/api/staff/user/user";
import {allUserGrade, listUserGrade} from "@/api/staff/user/usergrade";
import {storesList} from "@/api/staff/store";
import {getSysConfig} from "@/api/staff/user/sysconfig";
import {getToken} from "@/utils/auth";
import {getListApi} from "@/api/setting/message";
import {addUserMassSend} from "@/api/userGroup/userMassSend";
import {deleteUserMassSendRecord, listUserMassSendRecord} from "@/api/userGroup/userMassSendRecord";
import {listUserLabel} from "@/api/staff/user/userlabel";

export default {
  name: "MemberIndex",
  components: {balanceRecharge, pointRecharge},
  dicts: ['official', 'zhzt'],
  data() {
    return {
      tabindex: 0,
      imageUrl: '',
      tabs: [
        {
          name: "会员信息",
        },
        {
          name: "群发记录",
        },
      ],
      baseUrl: process.env.VUE_APP_BASE_API,
      result: {},
      // 是否自动上传
      isUpload: false,
      headers: {
        'Access-Token': getToken(),
      },
      // 文件上传信息
      fileList: [],
      userStatusList:[
        {
          label: "使用中",
          value: 0
        },
        {
          label: "已注销",
          value: 1
        }
      ],

      addMember: [],
      // 余额
      balance: '',
      // 积分
      point: '',
      // 升数卡
      literCard: '',
      // 加油金
      refuelMoney: '',
      // 今日新增
      addNum: '',
      // 昨日新增
      yesterdayAddNum: '',
      rechargeTotal: "",
      // 遮罩层
      loading: true,
      uploading: false,
      uploadingFile: 0,
      // 标题
      title: "",
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      total1: 0,

      total2: 0,
      queryParams2: {
        page: 1,
        pageSize: 10
      },
      beginTime2: '',
      endTime2: "",
      massSendRecordList: [],

      // 表格数据
      list: [],
      // 会员表格数据
      userList: [],
      // 当前店铺会员等级列表
      userGradeList: [],
      userLabelList:[],
      // 所有等级信息
      allUserGrade: [],
      // 店铺列表
      storeList: [],
      storeIds: [],
      // 是否显示修改对话框
      open: false,
      openUser: false,
      openUpload: false,
      openResult: false,
      openMassSend: false,
      // 当前操作用户
      userId: '',
      // 是否弹层充值
      openBalance: false,
      // 是否弹层积分
      openPoint: false,
      // 日期范围
      dateRange: [],
      beginTime: new Date(),
      endTime: new Date(),
      // 默认排序
      defaultSort: {prop: 'updateTime', order: 'descending'},
      // 表单参数
      form: {
        id: '', name: '', gradeId: '', mobile: '', userNo: '', points: 0, startTime: '',
        endTime: '', refuelMoney: '0', official: 'wgz',
        cardBalance: 0, literCard: '0', sex: 1, idcard: '', birthday: '', address: '', status: "qy", description: ''
      },
      sexTypelist:[
        "女","男","不详"
      ],
      tindex:0,
      form1: {},
      messageList: [],
      // 查询参数
      queryParams: {
        page: 1,
        pageSize: 10,
        mobile: '',
        id: '',
        userNo: '',
        name: '',
        gradeId: '',
        status: '',
        storeId: '',
        official: '',
        cardBalance: '',
      },
      ifBalance: '',
      // 表单校验
      rules: {
        name: [
          {required: true, message: "会员名称不能为空", trigger: "blur"},
          // { min: 2, max: 200, message: '会员名称长度必须介于2 和 100 之间', trigger: 'blur' }
        ],
        gradeId: [{required: true, message: "请选择会员等级", trigger: "blur"}],
        status: [{required: true, message: "请选择会员状态", trigger: "blur"}],
        mobile: [
          {required: true, message: "请输入手机号", trigger: "blur"},
          {min: 11, max: 11, message: '请输入正确的手机号', trigger: 'blur'}
        ],
        userStatus:[
          {required: true, message: "请选择会员状态", trigger: "blur"},
        ]
      },
      // 表单校验
      rules1: {
        name: [
          {required: true, message: "群发名称不能为空", trigger: "blur"},
        ],
        sendWay: [{required: true, message: "请选择群发方式", trigger: "blur"}],
        senfGift: [{required: true, message: "请选择群发礼品", trigger: "blur"}],
        messageId: [
          {required: true, message: "短信模板不能为空", trigger: "blur"},
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getStatistic();
    this.getConfig();
    this.getUserList();
    this.getMessageList()
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    getMessageList() {
      getListApi({page: 1, pageSize: 10000, status: '1'}).then(res => {
        this.messageList = res.data.records;
      })
    },
    // 定时器
    queryUserList() {
      // let _this = this;
      // setInterval(function (){
      //   _this.getList();
      //   _this.getStatistic();
      // },5000)
    },
    // 跳转详情页
    goDedi(id) {
      this.$router.push({
        path: "/member/userInfo",
        query: {
          id: id
        }
      })
    },
    getUserList() {
      this.loading = true;
      listUserStatistic().then(response => {
        this.userList = response.data.records;
        this.total1 = response.data.total;
        this.loading = false;
      });
    },
    // 查询列表
    getList() {

      this.loading = true;

      let dateRange = []
      if (this.beginTime && this.endTime) {
        dateRange.push(this.beginTime.toLocaleDateString())
        dateRange.push(this.endTime.toLocaleDateString())
      }
      listUser(this.addDateRange(this.queryParams, dateRange)).then(response => {
        this.list = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    getList1() {
      let dateRange = []
      if (this.beginTime2 && this.endTime2) {
        dateRange.push(this.beginTime2.toLocaleDateString())
        dateRange.push(this.endTime2.toLocaleDateString())
      }
      listUserMassSendRecord(this.addDateRange(this.queryParams2, dateRange)).then(res => {
        this.massSendRecordList = res.data.records
        this.total2 = res.data.total
      })
    },
    // 获得统计信息
    getStatistic() {
      let dateRange = []
      if (this.beginTime && this.endTime) {
        dateRange.push(this.beginTime.toLocaleDateString())
        dateRange.push(this.endTime.toLocaleDateString())
      }
      listStatistic(this.addDateRange(this.queryParams, dateRange)).then(response => {
        this.addNum = response.data.addNum;
        this.yesterdayAddNum = response.data.yesterdayAddNum;
        this.rechargeTotal = response.data.rechargeTotal;
        if (!response.data.balance) {
          this.balance = 0
        } else {
          this.balance = response.data.balance;
        }
        if (!response.data.point) {
          this.point = 0
        } else {
          this.point = response.data.point;
        }
      });
      allUserGrade().then(response => {
        this.allUserGrade = response.data
      });
      listUserGrade({page: 1, pageSize: 20}).then(response => {
        this.userGradeList = response.data.records;
      });
      storesList().then(response => {
        this.storeList = response.data
      });
    },
    // 搜索按钮操作
    handleQuery1() {
      this.queryParams2.page = 1;
      this.getList1();
    },
    // 重置按钮操作
    resetQuery1() {
      this.queryParams2 = {
        page: 1,
        pageSize: 10,
      }
      this.beginTime2 = ''
      this.endTime2 = ''
      this.handleQuery1();
    },
    // 搜索按钮操作
    handleQuery() {
      this.queryParams.page = 1;
      if (this.ifBalance == 'haveBalance') {
        this.queryParams.cardBalance = 1;
      } else {
        this.queryParams.cardBalance = 2;
      }
      if (this.ifBalance == '') {
        this.queryParams.cardBalance = ''
      }
      this.getList();
      this.getStatistic();
    },
    // 重置按钮操作
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.storeId = '';
      this.queryParams.official = "";
      this.ifBalance = ""
      this.storeIds = [];
      this.beginTime = ""
      this.endTime = ""
      this.$refs.tables.sort(this.defaultSort.prop, this.defaultSort.order);
      this.handleQuery();
    },
    // 状态修改
    handleStatusChange(row) {
      let text = row.status == "A" ? "启用" : "禁用";
      this.$modal.confirm('确认要' + text + '"' + row.name + '"吗？').then(function () {
        return updateMemberStatus(row.id, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function () {
        row.status = row.status === "N" ? "A" : "N";
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.multiple = !selection.length
    },
    // 排序触发事件
    handleSortChange(column, prop, order) {
      this.queryParams.orderByColumn = column.prop;
      this.queryParams.isAsc = column.order;
      this.getList();
    },
    // 余额充值操作
    handleBalance(userId) {
      this.openBalance = true;
      this.userId = userId.toString();
    },
    // 导入会员信息
    importUser() {
      this.openResult = true;
      this.title = "会员创建结果";
      this.getList();
      this.getUserList();
    },
    // 积分变更操作
    handlePoint(userId) {
      this.openPoint = true
      this.userId = userId.toString();
    },
    // 关闭对话框
    closeDialog(dialog) {
      if (dialog == 'balance') {
        this.openBalance = false;
      }
      if (dialog == 'point') {
        this.openPoint = false;
      }
      this.userId = "";
      this.getList();
    },
    // 新增按钮操作
    handleAdd() {
      this.openUser = true;
      this.title = "新增会员";
    },
    Typeindex(index) {
      this.tindex = index
      this.form.sex = index
    },
    // 新增按钮操作
    addOne() {
      this.tindex = 1
      this.reset();
      this.open = true;
      this.title = "新增会员";
    },
    addMult() {
      this.openUpload = true;
      this.title = "批量新增会员";
    },
    handleMassSend() {
      this.form1 = {
        sendWay: [],
        senfGift: [],
        sendUserNum: this.total
      }
      this.openMassSend = true
      this.title = "会员群发";
    },
    // 获取配置信息
    getConfig() {
      getSysConfig('addMember').then(response => {
        this.addMember = response.data.split(";")
      });
      listUserLabel({page: 1, pageSize: 10, status: 'qy'}).then(res => {
        this.userLabelList = res.data.records
      })
    },
    // 表单重置
    reset() {
      this.resetForm("form");
      this.form = {
        name: '',
        gradeId: '',
        mobile: '',
        userNo: '',
        points: '',
        startTime: '',
        endTime: '',
        refuelMoney: '0',
        official: 'wgz',
        cardBalance: '',
        literCard: '0',
        sex: 1,
        idcard: '',
        birthday: '',
        address: '',
        status: "qy",
        description: '',
        userStatus:'0'
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 提交按钮
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.userLabelId) this.form.userLabelId = this.form.userLabelId.toString()
          if (this.form.id) {
            updateUser(this.form).then(response => {
              if (response.data == 1) {
                this.$modal.msgSuccess("修改会员成功");
                this.open = false;
                this.getList();
              } else {
                this.$modal.msgError("手机号已存在");
              }
            });
          } else {
            getUserPhone({mobile: this.form.mobile}).then(response => {
              if (response.data) {
                this.$modal.msgError("手机号已存在");
              } else {
                addUser(this.form).then(res => {
                  this.$modal.msgSuccess("新增会员成功");
                  this.open = false;
                  this.openUser = false;
                  this.getList();
                  this.getUserList();

                });
              }
            })
          }
        }
      });
    },
    // 提交按钮
    submitForm1: function () {
      this.$refs["form1"].validate(valid => {
        if (valid) {
          this.form1.sendWay = this.form1.sendWay.toString()
          this.form1.senfGift = this.form1.senfGift.toString()
          addUserMassSend(this.form1).then(res => {
            this.$message.success("添加成功")
            this.openMassSend = false
            this.queryParams.page = 1;
            this.getList();
          })

        }
      });
    },
    // 修改按钮操作
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getUser(id).then(response => {
        this.form = response.data;
        if (response.data.sex) this.tindex = response.data.sex
        if (response.data.userLabelId) this.form.userLabelId = response.data.userLabelId.split(",")
        this.open = true;
        this.title = "修改会员";
      });
    },
    // 删除按钮操作
    handleDelete(row) {
      const name = row.name
      this.$modal.confirm('是否删除本条数据，删除后无法恢复').then(function () {
        // return deleteMember(row.id);
        return delUser(row.id);
      }).then(() => {
        this.queryParams.page = 1
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    // 删除按钮操作
    handleDelete1(row) {
      const name = row.labelName || this.id;
      this.$modal.confirm('是否删除本条数据，删除后无法恢复！').then(function () {
        return deleteUserMassSendRecord(row.id);
      }).then(() => {
        this.queryParams2.page = 1
        this.getList1();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    // 注销按钮操作
    handleLogOff(row) {
      const name = row.name
      this.$modal.confirm('是否注销本会员数据，注销后无法恢复').then(function () {
        return logOffUsers(row.balanceId);
      }).then(() => {
        this.queryParams.page = 1
        this.getList();
        this.$modal.msgSuccess("注销成功");
      }).catch(() => {
      });
    },
    handleChange(file, fileList) {
      this.uploading = true;
      if (file.status === 'success') {
        this.uploading = false;
        this.openUpload = false;
        this.openUser = false;
        this.importUser();
        this.fileList.splice(0, 1)
        this.result = file.response.data
      }
    },
    getindex(index) {
      this.tabindex = index
      if (index == 0) {
        this.getList()
      } else if (index == 1) {
        this.getList1()
      }
    }
  }
};
</script>

<style scoped lang="scss">

.app-container {
  width: 100%;
  background: #f6f8f9;
  box-sizing: border-box;
  padding-bottom: 15px;
  margin: 0;
  padding: 0;
}
.el-form--inline .el-form-item {
  margin-right: 26px;
}
.sta {
  height: 100px;
  margin-top: 10px;
  background: #f6f8f9;
  padding-top: 30px;
}

.huiyuan {
  height: 30px;
  line-height: 30px;
  font-size: 16px;
}

.num {
  font-weight: bold;
  color: red;
  font-size: 18px;
}

.ds-dbox {
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
  padding: 15px;
}

.k-one {
  width: 19%;
  border-radius: 10px;
  border: 1px solid #F5DF1A;
  background: rgba(252, 238, 109, 0.1);
  box-sizing: border-box;
  padding: 20px;
  position: relative;
  overflow: hidden;
}

.k-two {
  width: 19%;
  border-radius: 10px;
  border: 1px solid #0ECB98;
  background: rgba(14, 203, 152, 0.10);
  box-sizing: border-box;
  padding: 20px;
  position: relative;
  overflow: hidden;
}

.k-three {
  width: 19%;
  border-radius: 10px;
  border: 1px solid #fe8c4a;
  background: rgba(64, 158, 255, 0.1);
  box-sizing: border-box;
  padding: 20px;
  position: relative;
  overflow: hidden;
}

.k-four {
  width: 19%;
  border-radius: 10px;
  border: 1px solid #FF8E8D;
  background: rgba(255, 142, 141, 0.1);
  box-sizing: border-box;
  padding: 20px;
  position: relative;
  overflow: hidden;
}

.k-five {
  width: 19%;
  border-radius: 10px;
  border: 1px solid #647CFF;
  background: rgba(100, 124, 255, 0.1);
  box-sizing: border-box;
  padding: 20px;
  position: relative;
  overflow: hidden;
}

.r-bot-img {
  position: absolute;
  bottom: 5px;
  right: 5px;
  width: 54px;
  height: 50px;

}

.title_ {
  font-weight: 400;
  font-size: 14px;
  color: #999999;
  margin-bottom: 10px;
}

.num-size {
  font-size: 28px;
  color: #333333;
  font-weight: bold;
}

.tab-box {
  width: 100%;
  height: 40px;
  background: #fff;
  display: flex;
  box-sizing: border-box;
  margin-bottom: 10px;
  border-top: 1px solid #eceff1;

}

.tab_ {
  width: 75px;
  height: 100%;
  //border-bottom: 2px solid #FF770F;
  display: flex;
  font-weight: 500;
  font-size: 14px;
  color: #999999;
  align-items: center;
  justify-content: center;
  margin-left: 50px;
  cursor: pointer;
}

.active {
  border-bottom: 2px solid #FF770F !important;
  color: #FF770F !important;
}

.cot-box {
  width: 99%;
  border-radius: 8px;
  background: #fff;
  box-sizing: border-box;
  padding: 20px;
  margin: 0 auto;
  height: 87vh;


}

.d-s {
  display: flex;
  align-items: center;
}

.icon-type {
  display: flex;
  align-items: center;
  font-weight: 400;
  font-size: 14px;
  color: #999999;
  margin-right: 20px;
  cursor: pointer;
}

.acvtive1 {
  color: #FF770F !important;
}
.hy_{
  background: #f9f9f9;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
