<template>
    <div class="context">
        <div class="panel">
            <h5>临时会员</h5>
            <div class="panel-body">
                <div class="panel_control">
                    <el-row :gutter="20">
                        <el-col :span="5">
                            <em>姓名:</em>
                            <el-input v-model="panel.name" placeholder="请输入姓名"></el-input>
                        </el-col>
                        <el-col :span="5">
                            <em>手机号:</em>
                            <el-input v-model="panel.phone" placeholder="请输入手机号" type="number"></el-input>
                        </el-col>
                        <el-col :span="3">
                            <el-button size="" type="primary" @click="query" plain :disabled="serachBtnStatus">查询
                            </el-button>
                        </el-col>
                    </el-row>
                </div>
            </div>
        </div>
        <div class="change">
            <el-button @click="addMember"  type="primary" size="mini">新增临时会员</el-button>
            <el-button @click="delList" size="mini">删除临时会员</el-button>
        </div>
        <div class="table">
            <el-table
                    :data="tableData"
                    border
                    is-horizontal-resize
                    :default-sort="{prop: 'date', order: 'descending'}"
                    element-loading-background="rgba(0, 0, 0, 0.8)"
                    @selection-change="handleSelectionChange" @current-change="clickChange"
            >
                >
                <el-table-column label="选择" width="55">
                    <template slot-scope="scope">
                        <el-radio v-model="tableRadio" :label="scope.row"><i></i></el-radio>
                    </template>
                </el-table-column>
                <el-table-column
                        type="index"
                        label="序号"
                        align="center"
                        width="50"
                >
                </el-table-column>
                <el-table-column
                        prop="UserInfo.head"
                        label="头像"
                        width="50"
                >
                    <template slot-scope="scope">
                        <div class="demo-image__preview" v-if="scope.row.Head">
                            <el-image
                                    style="width: 25px; height: 25px"
                                    :src="scope.row.Head"
                                    :preview-src-list="[scope.row.Head]"

                            >
                            </el-image>
                        </div>
                        <img src="../assets/img/nav/head.png" alt="" v-else width="25px" height="25px">
                    </template>
                </el-table-column>
                <el-table-column
                        prop="UserName"
                        label="会员名"
                        width="90"
                >
                </el-table-column>
                <el-table-column
                        prop="Phone"
                        label="手机号"
                        width="110"
                >
                </el-table-column>
                <el-table-column
                        prop="StaticHr"
                        label="静态心率"
                        width="110"
                        sortable
                >
                </el-table-column>
                <el-table-column
                        prop="Height"
                        label="身高(CM)"
                        width="110"
                        sortable
                >
                </el-table-column>
                <el-table-column
                        prop="Weight"
                        label="体重(KG)"
                        width="110"
                        sortable
                >
                    <template slot-scope="scope">
                        <span>{{scope.row.Weight / 10}}</span>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="Sex"
                        label="类型"
                        align="center"
                        width="80px"
                        sortable
                >
                    <template slot-scope="scope">
                        <span v-if="scope.row.Sex == 1">男</span>
                        <span v-if="scope.row.Sex == 2">女</span>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="Birthday"
                        label="生日"
                        width="110"
                        :formatter="filterFmtDate"
                        sortable
                >
                </el-table-column>
                <!--<el-table-column-->
                <!--prop="ClassInfo"-->
                <!--label="会员课程"-->
                <!--width="220px"-->
                <!--&gt;-->
                <!--<template slot-scope="scope">-->
                <!--<span class="lessonSpan" :style="{background:lesson.ClassColor}"-->
                <!--v-for="lesson in scope.row.ClassInfo">{{ lesson.ClassName }}</span>-->
                <!--</template>-->
                <!--</el-table-column>-->
                <el-table-column
                        prop="UserInfo.Memo"
                        label="备注">
                    <template slot-scope="scope">
                        <el-popover
                                placement="top"
                                title=""
                                width="200"
                                trigger="hover"
                                :content="scope.row.Memo">
                            <span slot="reference"
                                  v-if="scope.row.Memo.length > 6">{{ scope.row.Memo.substr(0, 6) }} ....</span>
                        </el-popover>
                        <span v-if="scope.row.Memo.length <= 6">{{ scope.row.Memo }}</span>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="UserInfo.Status"
                        label="操作"
                        width="160px"
                >
                    <template slot-scope="scope">
                        <el-button class="btn" type="default" size="mini" @click="editMember(scope.row)"
                                   v-if="userLevel != 4">编辑
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <br>
            <el-pagination
                    background
                    :total="pageination.total"
                    :page-size="pageination.pageItem"
                    @current-change="pageChange"
            ></el-pagination>
        </div>

        <el-dialog :title="dialogTitle" :visible.sync="dialogMemberVisible"
                   :width="form.btnType == 1 ?'650px':'650px'">
            <div class="dialogContent">
                <div :class="['pull-left',{'tabwild':form.btnType == 1}]">
                    <el-form ref="form" :model="form" label-width="80px">
                        <el-form-item label="手机号" :required="true">
                            <el-input v-model="form.phone"></el-input>
                        </el-form-item>
                        <el-form-item label="会员名" :required="true">
                            <el-input v-model="form.name"></el-input>
                        </el-form-item>
                        <el-form-item label="备注">
                            <el-input v-model="form.memo"></el-input>
                        </el-form-item>
                        <el-form-item label="身高" :required="true">
                            <el-input v-model="form.height" placeholder="cm" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="体重" :required="true">
                            <el-input v-model="form.weight" placeholder="kg" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="静态心率">
                            <el-input v-model="form.staticHr" placeholder="请输入" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="性别" :required="true">
                            <el-select v-model="form.sex " placeholder="">
                                <el-option
                                        v-for="item in sexOptions"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="出生年份" :required="true">
                            <el-date-picker
                                    v-model="form.birthday"
                                    align="right"
                                    type="date"
                                    placeholder="选择日期"
                            >
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label="头像">
                            <div class="upload">
                                <el-upload
                                        class="avatar-uploader"
                                        :action=domain
                                        :http-request=upqiniu
                                        :show-file-list="false"
                                        :before-upload="beforeUpload">
                                    <!--<i v-else class="el-icon-plus avatar-uploader-icon"></i>-->
                                </el-upload>
                                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                                <cropper
                                        :width="300"
                                        :height="300"
                                        :fixed-number="[1,1]"
                                        @subUploadSucceed="getShopImages"
                                ></cropper>
                                <!--<ImgCutter v-on:cutDown="cutDown"></ImgCutter>-->
                            </div>
                        </el-form-item>
                    </el-form>
                </div>
            </div>
            <div class="dialogFooter">
                <el-button :disabled="addDisabled" :loading="addDisabled" type="primary" size="small"
                           v-if="form.btnType == 0"
                           @click="confirmMember">确定
                </el-button>
                <el-button type="primary" size="small" v-if="form.btnType == 1" @click="confirmEditMember">确定
                </el-button>
                <el-button size="small" @click="dialogMemberVisible = false">取消</el-button>
            </div>
        </el-dialog>
    </div>

</template>

<script>
    import Global from '../Global.js'
    import ImgCutter from 'vue-img-cutter'
    import {
        TmpUserQuery,
        TmpUserAdd,
        TmpUserEdit,
        TmpUserDel,
        testTable,
        testSelect
    } from "../api/getApiRes";
    import cropper from '@/components/cropper.vue'

    let qs = require('qs');
    export default {
        data() {
            return {
                imageUrl: '',
                token: {}, // 七牛云的上传地址，根据自己所在地区选择，我这里是华南区
                domain: 'https://up-z1.qiniup.com', // 这是七牛云空间的外链默认域名
                qiniuaddr: 'xhead.beswell.com',//xhead.beswell.com 旧的 qjzpcd34v.hb-bkt.clouddn.com
                tableData: [],
                tableRadio: [],
                userLevel: localStorage.userLevel,
                serachBtnStatus: false,
                addDisabled: false,
                start: 0,
                draw: 1,
                dialogTitle: '新增临时会员',
                dialogMemberVisible: false,//新增会员dialog
                sexOptions: [
                    {value: 1, label: '男'},//性别 1：男， 2：女
                    {value: 2, label: '女'},
                ],
                panel: {
                    usercode: '',
                    username: '',
                    compname: '',
                    keyword: '',
                    USERCODE: '',
                    endType: '',
                    taskstatus: 99,
                    draw: 1,
                    start: 0,
                    recordsTotal: 0,
                    tableData: [],
                    allTableData: [],
                    limit: '10',
                    multipleSort: false,
                    loading: false,
                    fileList: [],
                    multipleSelection: [],
                    detectedmac: '',
                    vipType: '',
                    expDay: '',
                    vipOptions: vipOptions(0),
                    endTypeOptions: endTypeOptions(),
                    time1: globalBt(),
                },
                multipleSelection: [],
                pageination: {
                    pageItem: 10,
                    pageoptions: pageOptions(),
                    total: 100,
                    pageIndex: 1,
                },
                form: {
                    phone: '',
                    name: '',
                    userCode: '',
                    shopId: '',
                    Id: '',
                    userId: '',
                    height: '',
                    weight: '',
                    staticHr: '',
                    head: '',
                    birthday: '',
                    sex: 1,
                    vipType: 1,
                    normalhour: 0,
                    newnormalhour: 0,
                    gifthour: 0,
                    newgifthour: 0,
                    btnType: 0,//0新建，1编辑编辑
                    memo: '',
                    expTime: '',
                    classlist: [],
                    dialogdata: [],//穿梭待选
                    dialogValue: [],//穿梭已选
                },
            }
        },
        mounted() {
            // 读取列表
            this.getTableQuery();
        },
        watch: {
            $route(to) {
                if (to.name == 'tempUser') {
                    // 读取列表
                    this.getTableQuery();
                }
            },
        },
        methods: {
            addMember() {
                this.clearForm();
                this.dialogMemberVisible = true;
                this.btnType = 0;
                this.form.btnType = 0;
                this.dialogTitle = '新增临时会员'
            },
            delList() {
                let that = this;
                if (this.tableRadio.length == 0) {
                    that.$message.error("请先选中一条记录");
                    return false
                }
                let detectorid = this.tableRadio.TuId;

                let param = {
                    token: localStorage.token,
                    tuId: detectorid,
                };
                let postdata = qs.stringify(param);

                this.$confirm('此操作将永久删除该临时会员, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    TmpUserDel(postdata).then(res => {
                        let json = res;
                        if (json.Code == 0) {
                            that.$message({
                                showClose: true,
                                message: '选中的临时会员已删除！',
                                type: 'success'
                            });
                            // 重载列表
                            that.getTableQuery();
                        } else {
                            that.$message.error(json.Memo + ' 错误码：' + json.Code);
                        }
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            clickChange(item) {
                this.tableRadio = item
            },
            // 确认提交新增会员
            confirmMember() {
                let that = this;
                // checkNum
                if (!that.form.phone) {
                    this.$message.error('错了哦，手机号不能为空');
                    return false
                }
                if (!globalCheckPhone(that.form.phone)) {
                    this.$message.error('错了哦，手机号格式不正确');
                    return false
                }
                if (!that.form.name) {
                    this.$message.error('错了哦，会员名不能为空');
                    return false
                }
                if (that.form.name.length > 8) {
                    this.$message.error('错了哦，会员名字数超过8个字');
                    return false
                }
                if (that.form.memo) {
                    if (that.form.memo.length > 200) {
                        this.$message.error('错了哦，备注字数超过200个字');
                        return false
                    }
                }
                if (!that.form.height) {
                    this.$message.error('错了哦，身高不能为空');
                    return false
                }
                if (!that.form.weight) {
                    this.$message.error('错了哦，体重不能为空');
                    return false
                }
                // if (!that.form.staticHr) {
                //     this.$message.error('错了哦，静态心率不能为空');
                //     return false
                // }
                if (!that.form.birthday) {
                    this.$message.error('错了哦，出生年份不能为空');
                    return false
                }


                let param = {
                    token: localStorage.token,
                    shopId: localStorage.shopId,
                    phone: that.form.phone,
                    name: that.form.name,
                    sex: that.form.sex,
                    birthday: nonTfmtDatetoLength(that.form.birthday, 10),
                    height: that.form.height,
                    weight: that.form.weight,
                    staticHr: that.form.staticHr,
                    head: that.form.head,
                    memo: that.form.memo,
                };
                let postdata = qs.stringify(param);
                TmpUserAdd(postdata).then(res => {
                    let json = res;
                    if (json.Code == 0) {
                        // 关闭弹窗
                        that.dialogMemberVisible = false;
                        // 重载列表
                        that.getTableQuery();
                        that.$message({
                            showClose: true,
                            message: '临时会员添加成功！',
                            type: 'success'
                        });
                    } else {
                        that.$message.error(json.Memo + ' 错误码：' + json.Code);
                    }
                })
            },
            // 编辑
            editMember(row) {
                let that = this;
                this.clearForm();
                this.form.phone = row.Phone;
                this.form.name = row.UserName;
                this.form.memo = row.Memo;
                this.imageUrl = row.Head;
                this.form.height = row.Height;
                this.form.weight = parseInt(row.Weight) / 10;
                this.form.staticHr = row.StaticHr;
                this.form.sex = row.Sex;
                this.form.birthday = row.Birthday;
                this.form.tuId = row.TuId;
                this.form.btnType = 1;
                this.form.shopId = localStorage.shopId;
                this.form.Id = row.Id;
                this.dialogMemberVisible = true;
                this.dialogTitle = '编辑会员'

            },
            confirmEditMember() {
                let that = this;
                // checkNum
                if (!that.form.phone) {
                    this.$message.error('错了哦，手机号不能为空');
                    return false
                }
                if (!globalCheckPhone(that.form.phone)) {
                    this.$message.error('错了哦，手机号格式不正确');
                    return false
                }
                if (!that.form.name) {
                    this.$message.error('错了哦，会员名不能为空');
                    return false
                }
                if (that.form.name.length > 8) {
                    this.$message.error('错了哦，会员名字数超过8个字');
                    return false
                }
                if (that.form.memo) {
                    if (that.form.memo.length > 200) {
                        this.$message.error('错了哦，备注字数超过200个字');
                        return false
                    }
                }

                if (!that.form.height) {
                    this.$message.error('错了哦，身高不能为空');
                    return false
                }
                if (!that.form.weight) {
                    this.$message.error('错了哦，体重不能为空');
                    return false
                }
                // if (!that.form.staticHr) {
                //     this.$message.error('错了哦，静态心率不能为空');
                //     return false
                // }
                if (!that.form.birthday) {
                    this.$message.error('错了哦，出生年份不能为空');
                    return false
                }
                let param = {
                    token: localStorage.token,
                    shopId: that.form.shopId,
                    userId: that.form.Id,
                    phone: that.form.phone,
                    name: that.form.name,
                    memo: that.form.memo,
                    head: that.form.head,
                    height: that.form.height,
                    weight: that.form.weight,
                    staticHr: that.form.staticHr,
                    sex: that.form.sex,
                    birthday: nonTfmtDatetoLength(that.form.birthday, 10),
                    tuId: that.form.tuId
                };
                let postdata = qs.stringify(param);
                TmpUserEdit(postdata).then(res => {
                    let json = res;
                    if (json.Code == 0) {
                        // 关闭弹窗
                        that.dialogMemberVisible = false;
                        // 重载列表
                        that.getTableQuery();
                        that.$message({
                            showClose: true,
                            message: '会员信息编辑成功！',
                            type: 'success'
                        });
                    } else {
                        that.$message.error(json.Memo + ' 错误码：' + json.Code);
                    }
                })
            },
            // 验证文件合法性
            beforeUpload(file) {
                const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
                const isLt2M = file.size / 1024 / 1024 < 70;
                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!')
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 70MB!')
                }
                return isJPG && isLt2M
            },
            cutDown(e) {
                console.log(e);
                this.imageUrl = e.dataURL;
                this.upqiniu(e);
            },
            // 上传文件到七牛云
            upqiniu(req) {
                let that = this;
                const config = {
                    headers: {'Content-Type': 'multipart/form-data'}
                };
                let filetype = '';
                if (req.file.type === 'image/png') {
                    filetype = 'png'
                } else {
                    filetype = 'jpg'
                }
                // 重命名要上传的文件
                const keyname = 'GoAllOut' + new Date().valueOf() + Math.floor(Math.random() * 100) + '.' + filetype;
                // 从后端获取上传凭证token
                let param = {
                    token: localStorage.token,
                };
                let postdata = qs.stringify(param);
                this.axios.post(headapi + 'v1/QiNiu/GetSimpleQiNiuToken', postdata).then(res => {
                    const formdata = new FormData();
                    formdata.append('file', req.file);
                    formdata.append('token', res.data.QiNinToken);
                    formdata.append('key', keyname);
                    // 获取到凭证之后再将文件上传到七牛云空间
                    this.axios.post(this.domain, formdata, config).then(res => {
                        this.imageUrl = 'http://' + this.qiniuaddr + '/' + res.data.key;
                        this.form.head = 'http://' + this.qiniuaddr + '/' + keyname;
                    })
                })
            },
            // 查询按钮
            query() {
                let that = this;
                that.serachBtnStatus = true;
                that.getTableQuery();
                that.$message.success('查询完毕');
                let totalTime = 2
                let clock = window.setInterval(() => {
                    totalTime--
                    if (totalTime < 0) {
                        totalTime = 2;
                        that.serachBtnStatus = false;
                    }
                }, 1000)
            },
            // 页面数据查询
            getTableQuery() {
                let that = this;
                that.loading = true;
                let param = {
                    token: localStorage.token,
                    shopId: that.panel.shopId,//
                    name: that.panel.name,//
                    expDay: that.panel.expDay,//
                    start: that.start,//
                    tableMax: 20,//
                };
                let postdata = qs.stringify(param);
                TmpUserQuery(postdata).then(res => {
                    let json = res;
                    if (json.Code == 0) {
                        that.loading = false;
                        if (json.Rs) {
                            that.allTableData = json.Rs;
                            that.recordsTotal = json.PageCount * that.pageination.pageItem;
                        } else {
                            that.allTableData = [];
                            that.recordsTotal = 0;
                        }
                        // 设置分页数据
                        that.setPaginations();
                    } else {
                        that.$message.error(json.Memo + ' 错误码：' + json.Code);
                    }
                })
            },
            clearForm() {
                // clear
                this.form.name = '';
                this.form.head = '';
                this.imageUrl = '';
                this.form.phone = '';
                this.form.memo = '';
                this.form.normalhour = 0;
                this.form.gifthour = 0;
                this.form.height = '';
                this.form.weight = '';
                this.form.staticHr = '';
                this.form.sex = 1;
                this.form.birthday = '';
                this.form.userCode = '';
                this.form.shopId = '';
                this.form.classlist = [];
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            // 设置分页数据
            setPaginations() {
                // 分页属性
                let that = this;
                that.pageination.total = that.recordsTotal;

                // 默认分页
                that.tableData = that.allTableData.filter((item, index) => {
                    return index < that.pageination.pageItem;
                });
            },
            // 每页显示数量
            handleSizeChange() {
                let that = this;
                that.tableData = that.allTableData.filter((item, index) => {
                    return index < that.pageination.pageItem;
                });
                that.draw = that.pageination.pageItem;
                // that.getTableQuery();
            },
            // 翻页
            pageChange(pageIndex) {
                let that = this;
                // 获取当前页
                let index = that.pageination.pageItem * (pageIndex - 1);
                // 数据总数
                let nums = that.pageination.pageItem * pageIndex;
                // 容器
                let tables = [];
                for (var i = index; i < nums; i++) {
                    if (that.allTableData[i]) {
                        tables.push(that.allTableData[i])
                    }
                    this.tableData = tables;
                }
                that.start = index * that.draw;
                console.log(index);
                console.log(that.draw);
                that.getTableQuery();
            },
            //            过滤时间
            filterFmtDate(value, row, column) {
                return nonTfmtDatetoLength(column, 11);
            },
            // 海报上传成功
            getShopImages(url) {
                this.imageUrl = url;
                this.form.head = url;
            }
        },
        components: {
            cropper
        }
    }
</script>

<style scoped>
    @import "../assets/css/panel.css";

    .context {
        border-radius: 12px;
        /* height: 770px; */
        overflow-y: scroll;
        display: block;
        margin: 0 auto;
        background-color: #fff !important;
        padding: 30px;
        padding-bottom: 30px;
    }

    .panel-body {
        padding: 20px;
        background: #F0F2F5;
    }

    .change {
        width: 100%;
        overflow: hidden;
        display: block;
        margin: 0 auto;
        padding-top: 10px;
        padding-bottom: 10px;
    }

    .change button {
        float: left;
    }

    .change button.pull-right {
        float: right;
    }

    .dialogContent {
        width: 100%;
        overflow: hidden;
        display: block;
        margin: 0 auto;
    }

    .dialogContent .pull-left {
        width: 100%;
        float: left;
    }

    .el-form-item {
        width: 50%;
        float: left;
    }
</style>
