<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-form ref="queryForm" :model="listQuery" label-width="100px">
        <el-row>
          <el-col :span="4">
            <el-form-item label="手机号">
              <el-input v-model.number="listQuery.username" placeholder="请输入手机号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="导入时间">
              <el-date-picker
                v-model="listQuery.startTime"
                type="date"
                :editable="true"
                format="yyyy-MM-dd"
                placeholder="选择日期"
              ></el-date-picker>~
              <el-date-picker
                v-model="listQuery.endTime"
                type="date"
                :editable="true"
                format="yyyy-MM-dd"
                placeholder="选择日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-button class="filter-item" type="primary" v-waves icon="search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item"  style="margin-left: 10px;" @click="newMember"
                 type="primary" icon="edit" v-if="memberEnter_btn_add">新增会员
      </el-button>

      <el-button class="filter-item"  style="margin-left: 10px;" @click="bulkUpload"
                 type="primary" icon="edit" v-if="memberEnter_btn_addIn">批量导入会员
      </el-button>
      <el-button class="filter-item" type="primary" v-waves @click="reloadPage">重置</el-button>
    </div>
    <el-table :key='tableKey' :data="list" v-loading.body="listLoading" border fit highlight-current-row
              style="width: 100%">
    <!--<el-table :key='tableKey' :data="list" v-loading.body="listLoading" border fit highlight-current-row-->
              <!--style="width: 100%">-->
      <el-table-column width="200" align="center" label="手机号">
        <template scope="scope">
          <span>{{scope.row.username}}</span>
        </template>
      </el-table-column>
      <el-table-column width="150" align="center" label="会员名">
        <template scope="scope">
          <span>{{scope.row.memberName}}</span>
        </template>
      </el-table-column>
      <el-table-column width="150" align="center" label="会员等级">
        <template scope="scope">
          <span>{{scope.row.memberLevel==3?"钻石会员": scope.row.memberLevel==2?"黄金会员":scope.row.memberLevel==1?"普通会员":"普通用户"}}</span>
        </template>
      </el-table-column>
      <el-table-column width="150" align="center" label="免费天数">
        <template scope="scope">
          <span>{{scope.row.totalNumber}}</span>
        </template>
      </el-table-column>
      <el-table-column width="150" align="center" label="剩余天数">
        <template scope="scope">
          <span>{{scope.row.rentFreeDays}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="录入时间">
        <template scope="scope">
          <span>{{scope.row.crtTimeStr}}</span>
        </template>
      </el-table-column>
      <el-table-column width="200" align="center" label="状态">
        <template scope="scope">
          <span>{{scope.row.status==1?"已核销":"未核销"}}</span>
        </template>
      </el-table-column>
      <el-table-column width="180" align="center" label="操作人">
        <template scope="scope">
          <span>{{scope.row.crtName}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="65" fixed="right">
        <template scope="scope">
          <el-button class="el-button el-button--text el-button--small" style="color:red" size="small" @click="deleteHandler(scope.row)" v-if="memberEnter_btn_del&&scope.row.status!=1">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page.sync="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit"
                     layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
    </div>

    <!--    新建会员窗口-->
    <el-dialog title="新建会员" :visible.sync="newMemberArea" width="10%">
      <el-form :model="newMemberObject" :rules="newMemberObjectVerify" ref="nmo" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="会员等级">
              <el-select class="filter-item" v-model="newMemberObject.memberLevel" placeholder="选择会员等级">
<!--                <el-option :key="undefined" label="无" :value="undefined"></el-option>-->
                <el-option v-for="(val, key, index) in memberLevelList " :key="val.id" :label="val.name"
                           :value="val.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="会员名" placeholder="会员名" prop="memberName">
              <el-input size="small " type="text" v-model="newMemberObject.memberName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="手机号" placeholder="手机号" prop="phone">
              <el-input size="small " type="text" v-model="newMemberObject.phone"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="免费天数" placeholder="免费天数" prop="totalNumber">
              <el-input size="small " type="number" v-model="newMemberObject.totalNumber" min="0" v-enterNumber></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="剩余天数" placeholder="剩余天数" prop="rentFreeDays">
              <el-input size="small " type="number" v-model="newMemberObject.rentFreeDays" min="0" v-enterNumber></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelNewMemberArea('nmo')">取消</el-button>
        <el-button type="primary" @click="setNewMemberObject('nmo')">确 定</el-button>
      </div>
    </el-dialog>

    <!--批量导入会员窗口-->
    <el-dialog title="导入会员" :visible.sync="bulkUploadMember">
      <el-form :model="fileForm">
        <el-form-item label="上传文件" :label-width="formLabelWidth">
          <el-button type="primary" icon="el-icon-download">
            <a class="el-icon-download" href="https://mgmt.dfangche.com/axshare/usermember.xlsx">下载模板
            </a>
          </el-button>

          <el-upload
            ref="uploadExcel"
            :limit=limitNum
            action="1111"
            :headers="getHeaderWithToken"
            accept=".xlsx"
            :http-request="upLoad"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :before-upload="beforeUploadFile"
            :on-change="fileChange"
            :on-exceed="exceedFile"
            :file-list="fileList">

            <el-button size="small" type="primary" icon="el-icon-edit">上传文件<i class="el-icon-upload el-icon--right">
            </i></el-button>
            <div slot="tip" class="el-upload__tip">只能上传xlsx(Excel2007以上版本)文件，且不超过10M</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="filter-item" @click="cancelNotDeleteForm">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getMemberEntryList,
    delMemberObj
  } from 'src/api/admin/userManagement/index';
  import {getToken} from 'src/utils/auth';
  import {mapGetters} from 'vuex';
  import {getUserMemberByUserId} from 'src/api/admin/baseUserMember/index';
  import {timestamp2Date} from 'src/utils/dateUtils';
  import {page} from 'src/api/order/memeber';
  import {
    UploadMembershipList,
    saveNewMemberObject
  } from 'src/api/admin/UserMember/index';
  import {formatDate} from "../../utils/dateFormattor";
  import ElRow from "element-ui/packages/row/src/row";
  import ElCol from "element-ui/packages/col/src/col";
  import {getMembers} from "src/api/admin/member/index"

  export default {
    components: {
      ElCol,
      ElRow},
    name: 'appUser',
    data() {
      return {
        validTime: '',
        userMembershipInformation: {
          memberLevel: undefined,
          validTime: '',
          buyCount: undefined,
          totalNumber: undefined,
          rentFreeDays: undefined,
          id: undefined,
          userId: undefined
        },
        memberLevelList: [],
        saveUserId: undefined,
        validityType: '无',
        userOrderMessage: {},
        BASE_API: process.env.BASE_API,
        userDetails: {},
        limitNum: 1,
        formLabelWidth: '80px',
        fileForm: {
          file: ''
        },
        fileList: [],
        errorHandler: true,
        list: null,
        total: null,
        orderTotal: null,
        listLoading: true,
        orderListLoading: true,
        newMemberObject: {
          memberName:undefined,
          phone: undefined,
          memberLevel: undefined,
          totalNumber: undefined,
          rentFreeDays: undefined
        },
        orderQuery: {
          limit: 10,
          page: 1,
          userId: undefined,
          type: undefined,
          status: undefined
        },
        newMemberObjectVerify: {
          phone: [
            {
              required: true,
              message: '手机号',
              trigger: 'blur'
            },
          ],
          memberLevel: [
            {
              required: true,
              message: '会员等级',
              trigger: 'blur'
            },
          ],
          totalNumber: [
            {
              required: true,
              message: '免费天数',
              trigger: 'blur'
            },
          ],
          rentFreeDays: [
            {
              required: true,
              message: '剩余总天天数',
              trigger: 'blur'
            },
          ],
        },
        listQuery: {
          page: 1,
          limit: 20,
          startTime: undefined,
          username: undefined,
          endTime: undefined,
        },
        newMemberArea: false,
        bulkUploadMember: false,
        dialogStatus: '',
        userManager_btn_del: false,
        myGroups: [],
        loading: false,

        tableKey: 0,
        selectedAccItem: undefined,
        memberEnter_btn_add: false,//添加一条
        memberEnter_btn_del:false,//删除
        memberEnter_btn_addIn: false,//批量上传
      }
    },
    created() {
      this.memberEnter_btn_add=this.elements['memberEnter:btn_add'];//添加一条
      this.memberEnter_btn_del=this.elements['memberEnter:btn_del'];//删除
      this.memberEnter_btn_addIn=this.elements['memberEnter:btn_addIn'];//批量上传

      let query =  localStorage.getItem("memberEnter");
      if(query !="null" && query){
        this.listQuery = JSON.parse(query);
      }
      this.getList();
     this. getMembersLevel()
    } ,
    computed: {
      ...
        mapGetters([
          'elements'
        ]),
      /**
       * 获取token
       */
      getHeaderWithToken() {
        return {Authorization: getToken()};
      },
    },
    methods: {
      getMembersLevel() {
        var _this = this;
        getMembers().then(res => {
            let members = res.data
            // console.log('getMembersLevel:{}'+JSON.stringify(members))
            // debugger
            members.map(function (ele) {

              _this.memberLevelList.push({id: ele.level, name: ele.name})
            })
            // console.log('this.queryMemberLevelList'+JSON.stringify(this.queryMemberLevelList))
          }
        )
      },
      /**
       *  上传
       */
      upLoad(file) {
        var form = new FormData();
        // 文件对象
        form.append("file", file.file);
        UploadMembershipList(form)
          .then(res => {
            if (res.rel) {
              this.$notify.success({
                title: '上传成功',
                message: `success`
              });
              this.bulkUploadMember = false;
              this.getList();
            } else {
              this.$notify.warning({
                title: '上传失败',
                message: `failed`
              })
            }
            this.getList();
          })
      },
      /**
       * 删除
       * */
      deleteHandler(row) {
        this.$confirm('确定删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delMemberObj(row.id).then(response => {
            if (response.status === 200) {
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              });
              this.getList();
            } else {
              this.$notify({
                title: '删除失败',
                message:response.message?response.message: '操作失败！',
                type: 'error',
                duration: 2000
              });
            }
          });
        })
      },
      //excel上传
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`);
      },

      // 文件超出个数限制时的钩子
      exceedFile(files, fileList) {
        this.$notify.warning({
          title: '警告',
          message: `只能选择 ${this.limitNum} 个文件，当前共选择了 ${files.length + fileList.length} 个`
        });
      },
      // 文件状态改变时的钩子
      fileChange(file, fileList) {
        console.log('change')
        console.log(file)
        this.fileForm.file = file.raw
        console.log(this.fileForm.file)
        console.log(fileList)
      },
      // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
      beforeUploadFile(file) {
        console.log('before upload')
        console.log(file)
        let extension = file.name.substring(file.name.lastIndexOf('.') + 1)
        let size = file.size / 1024 / 1024
        if (extension !== 'xlsx') {
          this.$notify.warning({
            title: '警告',
            message: `只能上传Excel 2007以上版本（即后缀是.xlsx）的文件`
          });
        }
        if (size > 10) {
          this.$notify.warning({
            title: '警告',
            message: `文件大小不得超过10M`
          });
        }
      },
      /**
       *  弹出导入窗体
       */
      bulkUpload() {
        this.bulkUploadMember = true
      },
      /**
       * 获取用户列表
       */
      getList() {
        let query = this.listQuery;
        console.log(typeof this.listQuery.startTime);
        if(this.listQuery.startTime && (typeof this.listQuery.startTime == "object")){
          this.listQuery.startTime = this.listQuery.startTime.getTime();
        }
        if(this.listQuery.endTime && (typeof this.listQuery.endTime == "object")){
          this.listQuery.endTime = this.listQuery.endTime.getTime();
        }
        if(this.listQuery){
          localStorage.setItem("memberEnter", JSON.stringify(this.listQuery));
        }
        getMemberEntryList(query)
          .then(response => {
            let totalCountRs = undefined;
            let listRs = undefined;
            if (!this.$utils.isEmpty(response.data.data) && this.$utils.isInteger(response.data.totalCount)) {
              listRs = response.data.data;
              totalCountRs = response.data.totalCount;
              listRs.map(function(item){
                item.visible2 = false;
                item.crtTimeStr = timestamp2Date(item.crtTime);
              });
            }
            this.list = listRs;
            this.total = totalCountRs;
            this.listLoading = false;
          })
      },
      /**
       * 重置
       * */
      reloadPage() {
        this.listQuery = {
          page: 1,
          limit: 20,
          startTime: undefined,
          username: undefined,
          endTime: undefined,
        };
        if(this.listQuery){
          localStorage.setItem("memberEnter", JSON.stringify(this.listQuery));
        }
        this.getList();
      },
      /**
       * 搜索
       */
      handleFilter() {
        this.listQuery.page = 1;
        this.getList();
      },
      handleSizeChange(val) {
        this.listQuery.limit = val;
        if(this.listQuery){
          localStorage.setItem("memberEnter", JSON.stringify(this.listQuery));
        }
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.page = val;
        if(this.listQuery){
          localStorage.setItem("memberEnter", JSON.stringify(this.listQuery));
        }
        this.getList();
      },
      handleCreate() {
        this.dialogStatus = 'create';
      },
      /**
       * 显示新增会员窗口
       * @param row
       */
      newMember() {
        this.newMemberArea = true
      },
      /**
       * 提交新增会员
       */
      setNewMemberObject(formName) {
       console.log(JSON.stringify(this.newMemberObject))
        saveNewMemberObject(this.newMemberObject)
          .then(res => {
              if (res.rel) {
                this.$notify.success({
                  title: '新增成功',
                  message: `success`
                })
              } else {
                this.$notify.warning({
                  title: '新增失败',
                  message: `failed`
                })
              }
              this.newMemberArea = false
              this.$refs[formName].resetFields()
              this.getList();
            })
        },
        /**
         * 关闭窗口,清除批量上传
         */
        cancelNotDeleteForm() {
          this.bulkUploadMember = false;
          this.$refs.uploadExcel.clearFiles();
        },
        //新增会员
        cancelNewMemberArea(formName) {
          this.newMemberArea = false
          this.$refs[formName].resetFields();
        }
      }
    }
</script>

