<template>
    <div class='personal-index'>
        <div class="plr15 ptb10 bgc-fff">
            <div class="kitbox">
                <div class="photo">
                    <van-image
                        width="80"
                        height="80"
                        round
                        src="https://img01.yzcdn.cn/vant/cat.jpeg"
                    />
                </div>
                <div class="pl15 lh20 kitbox box-v-middle">
                    <div>
                        <div class="fs-16 c-333">张三</div>
                        <div class="fs-14 c-666 pt5">
                            <div>15050505050</div>
                            <div>禾山街道社区卫生服务中心</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="mt10">
            <van-cell @click="gotoUrl('/personal/changePassword')" title="修改密码" is-link/>
            <!-- <van-cell title="帮助反馈" is-link/>
            <van-cell title="切换账号" is-link/> -->
        </div>
        

        <div class="mt20 plr15 bot-btn">
            <van-button color="#ff5e6c" round class='logoutBtn' @click='logout' block type="primary">退出当前账号</van-button>
        </div>
    </div>
</template>
<script>
    import {getPatient, updPatient, uploadStream} from '@/api/patient'
    import { ImagePreview } from 'vant';
    import {getMembers} from '@/api/family'
    import store from "@/store";
    import { Dialog } from 'vant';
    export default{
        name: 'meIndex',
        data(){
            return {
                fileList: [],
                screenWidth: document.body.clientWidth,
                family:[],
                patient:{},
                file: '',
                filename: '',
                defaultImg: '',
                members:[],
                

       
            }
        },
        created() {
            
        },
        methods:{
            activeList3Names(n){
                this.orgPage = 1;
                if(typeof n == 'number'){
                    this.getTeacherList(n)
                }
            },
            dataURLtoFile(dataurl, filename) { 
                var arr = dataurl.split(','),
                    mime = arr[0].match(/:(.*?);/)[1],
                    bstr = atob(arr[1]),
                    n = bstr.length,
                    u8arr = new Uint8Array(n);
                while (n--) {
                    u8arr[n] = bstr.charCodeAt(n);
                }
                return new File([u8arr], filename, { type: mime });
            },
            afterRead(){
                let that = this;
                that.patient.photo = that.fileList[0].content;
                that.file = that.fileList[0].content;
                that.filename = that.fileList[0].file.name;
                that.fileList = [];
                let param = new FormData();
                param.append('file', that.dataURLtoFile(that.file, that.filename));
                param.append('filename', that.filename);
                uploadStream(param).then(res => {
                    if(res.status == 200){
                        console.log(res)
                        that.patient.photo = res.obj.fullUri;
                        updPatient({'jsonData': {'patient':that.patient}}).then( res1 => {
                            if(res1.status == 200){
                                that.updLocalUser();
                            }
                            else{
                                that.$toast('修改失败');
                            }
                            console.log(res1)
                        })
                    }
                })
            },
            redirectToLogin() {
                let appId = process.env.VUE_APP_APPID,
                    protocol = window.location.protocol,
                    host = window.location.host,
                    redirctWxAuthUrl = encodeURIComponent(`${protocol}//${host}${process.env.VUE_APP_PRE_PATH}/login`),
                    wxAuthUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirctWxAuthUrl}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`
                
                location.replace(wxAuthUrl)
            },
            async logout(){
                await this.$store.dispatch('LogOut')
                localStorage.removeItem("Medical-Care-Wx-Logined-User-Agent")
                try{
                  localStorage.removeItem("Medical-Care-Wx-Proxy-User")
                }catch{

                }
                let isApp = this.$route.query.isApp || this.isSupportHtml5Plus
                if(!isApp) {
                  if(navigator.userAgent.toLowerCase().indexOf('micromessenger') !==-1) {
                    this.redirectToLogin()
                    return ;
                  }else{
                    this.gotoUrl('/login')
                  }
                }
            },
            Edit(str, value=''){
                this.$router.push({path: '/me/editMeInfo', query: {'key': str, 'value': value}})
            },
            imgPreview(){
                try{
                    if(this.patient.photo && this.patient.photo.toString().length>0){
                        ImagePreview({
                            images: [
                                this.patient.photo
                            ],
                            onClose() {
                                
                            },
                        });
                    }else{
                        ImagePreview({
                            images: [
                                require('@/assets/images/p-default.png')
                            ],
                            onClose() {
                                
                            },
                        });
                    }
                    
                }catch{
                    
                }
            },
            updLocalUser(){
                getPatient({id:this.patient.id}).then(res => {
                    if(res.status == 200){
                        let userInfo = _.assignIn(this.user, res.obj.patient)
                        store.dispatch('SetLoginUser', userInfo)
                        this.patient = this.user;
                        console.log(this.patient,"paskp")
                    }
                })
            },
            initMain(){
                let that = this;
                try{
                    that.patient = this.user;
                    getMembers({'patient': that.patient.id}).then(res => {
                        if(res.status == 200){
                            that.members = res.obj.normalmembers;
                            if(JSON.parse(localStorage.getItem("Medical-Care-Wx-Logined-User-Agent")).agent){
                            getMembers({'patient': JSON.parse(localStorage.getItem("Medical-Care-Wx-Logined-User-Agent")).agent}).then(res1 => {
                                console.log(res1)
                                if(res1.status == 200){
                                  if(that.members.length>0){
                                    res1.obj.normalmembers.forEach(el=>{
                                      let num = 0
                                      for(let i of that.members){
                                        if(i.id != el.id && this.user.id!=el.id){
                                          num += 1
                                        }else{
                                          el.isNotMembers = true
                                        }
                                      }
                                      if(num==that.members.length){
                                        el.isNotMembers = true
                                        that.members.push(el);
                                      }
                                    });
                                  }else{
                                    res1.obj.normalmembers.forEach(el=>{
                                      el.isNotMembers = true
                                    })
                                    that.members = res1.obj.normalmembers;
                                  }
                                }
                              })
                            }
                        }
                    })
                }catch{

                }
            },
            isSwitchLoginUser(item){
                Dialog.confirm({
                    title: '切换登录',
                    message: '是否要切换登录到'+item.name+"?",
                })
                .then(() => {
                    this.switchLoginUser(item)
                })
                .catch(() => {
                    // on cancel 
                });
            },
            async switchLoginUser(item){
                await switchLogin(item)
                this.initMain()
                this.$emitRefreshPage('homeIndex')
                this.gotoUrl('/home/index')
            },
            onCancel() {
                this.EditShow = false
            },
        },
        created(){
            this.initMain();
        },
        filters:{
            infoFliter(m){
                if(m && m.length>0){
                    return m.substr(0, m.length-8) + '****' + m.substr(m.length-4, 4);
                }
            },
            relationFilter(r){
                if(r.sex == 1){
                    switch(r.familyRelation){
                        case 2:
                            return '父亲';
                        case 4:
                            return '老公';
                        case 6:
                            return '儿子';
                    }
                }else if(r.sex == 2){
                    switch(r.familyRelation){
                        case 1:
                            return '母亲';
                        case 3:
                            return '老婆';
                        case 5:
                            return '女儿';
                    }
                }
                return r.familyRelationName;
            }
        }
    }
</script>
<style lang='scss' scoped>
.personal-index{
    .bot-btn{
        position: absolute;
        bottom: 60px;
        width: 100%;
    }
    .van-image{
        display: block;
    }
}
</style>