<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="6">
            <el-form-item label="手机号">
              <el-input v-model.number="listQuery.username" placeholder="请输入手机号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <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" 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 align="center" label="手机号">
        <template slot-scope="scope">
          <span>{{scope.row.username}}</span>
        </template>
      </el-table-column>
      <el-table-column  align="center" label="会员名">
        <template slot-scope="scope">
          <span>{{scope.row.memberName}}</span>
        </template>
      </el-table-column>
      <el-table-column width="150" align="center" label="会员等级">
        <template slot-scope="scope">
          <span>{{scope.row.memberLevelName}}</span>
        </template>
      </el-table-column>
      <el-table-column width="150" align="center" label="免费天数">
        <template slot-scope="scope">
          <span>{{scope.row.totalNumber}}</span>
        </template>
      </el-table-column>
      <el-table-column width="150" align="center" label="剩余天数">
        <template slot-scope="scope">
          <span>{{scope.row.rentFreeDays}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="录入时间">
        <template slot-scope="scope">
          <span>{{scope.row.crtTimeStr}}</span>
        </template>
      </el-table-column>
      <el-table-column width="200" align="center" label="状态">
        <template slot-scope="scope">
          <span>{{scope.row.status==1?"已核销":"未核销"}}</span>
        </template>
      </el-table-column>
      <el-table-column width="180" align="center" label="操作人">
        <template slot-scope="scope">
          <span>{{scope.row.crtName}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" fixed="right">
        <template slot-scope="scope">
          <el-button class="el-button el-button--text el-button--small" size="small" v-if="scope.row.status!=1 && memberEnter_btn_upd" @click="editHandler(scope.row)">编辑</el-button>
          <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="title" :visible.sync="newMemberArea">
      <el-form :model="newMemberObject" :rules="newMemberObjectVerify" ref="nmo" label-width="100px">
<!--				<el-row>-->
<!--				  <el-col :span="16">-->
<!--				    <el-form-item label="会员类型" prop="memberType">-->
<!--								<el-radio-group v-model="memberTypeName">-->
<!--								  <el-radio-button style="margin-bottom: 10px;" label="付费会员" :value="2"></el-radio-button>-->
<!--								  <el-radio-button style="margin-bottom: 10px;" label="兑换会员" :value="3"></el-radio-button>-->
<!--								</el-radio-group>-->
<!--				    </el-form-item>-->
<!--				  </el-col>-->
<!--				</el-row>-->
				<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')" v-if="!isClick">确 定</el-button>
        <el-button type="primary" v-if="isClick" style="opacity: 0.6;" >确 定</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 type="javascript">
  import {
    getMemberEntryList,
    delMemberObj
  } from 'src/api/admin/userManagement/index';
  import {getToken} from 'src/utils/auth';
  import {mapGetters} from 'vuex';
  import {timestamp2Date} from 'src/utils/dateUtils';
  import {
    UploadMembershipList,
    saveNewMemberObject
  } from 'src/api/admin/UserMember/index';
  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
        },
        isClick: false, // 是否已点击，防二次触发
        memberLevelList: [],
        saveUserId: undefined,
        validityType: '无',
				memberTypeName:'兑换会员',
        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: {
          id: undefined,
          memberName:undefined,
					memberType:undefined,
          phone: undefined,
          memberLevel: undefined,
          totalNumber: undefined,
          rentFreeDays: undefined
        },
        orderQuery: {
          limit: 10,
          page: 1,
          userId: undefined,
          type: undefined,
          status: undefined
        },
        title: '新增会员',
        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_upd: false, // 编辑
        memberEnter_btn_del:false,//删除
        memberEnter_btn_addIn: false,//批量上传
      }
    },
    created() {
      this.memberEnter_btn_add=this.elements['memberEnter:btn_add'];//添加一条
      this.memberEnter_btn_upd=this.elements['memberEnter:btn_upd'];//编辑一条

      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. 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})
            })
          _this.getList();
            // 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();
          })
      },
      /**
       * 编辑
       */
      editHandler(row){
        this.title = '编辑会员'
        this.newMemberObject = {
          id: row.id,
          memberName: row.memberName,
          memberType: row.memberType,
          phone: row.username,
          memberLevel: row.memberLevel,
          totalNumber: row.totalNumber,
          rentFreeDays: row.rentFreeDays
        }
        this.newMemberArea = true
      },
      /**
       * 删除
       * */
      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;
        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 _this = this
            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){
                _this.memberLevelList.map(function(iitem){
                  if(iitem.id == item.memberLevel){
                    item.memberLevelName = iitem.name
                  }
                })
                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.title = '新增会员'
        this.newMemberObject = {
          memberName:undefined,
          memberType:undefined,
          phone: undefined,
          memberLevel: undefined,
          totalNumber: undefined,
          rentFreeDays: undefined
        }
        this.newMemberArea = true
      },
      /**
       * 提交新增会员/编辑会员
       */
      setNewMemberObject(formName) {
          let _this = this
          const set = this.$refs;
          if (this.isClick) {
            return;
          }
          this.isClick = true;
          setTimeout(function(){
            _this.isClick = false
          }, 2000)
          set[formName].validate((valid) => {
            if (valid) {
              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>

