<template>
    <div class="mta-aframe-header">
        <div class="mta-logo-title">
            <img :src="logoImg" alt="logo">
            <span>{{logoText}}</span>
        </div>
        <nav>
            <ul style="display: flex;flex-direction: row;align-items: center">
                <li style="margin-right: 30px;" v-if="false">
                    <el-popover
                            placement="bottom"
                            width="200"
                            v-model="visible1"
                            trigger="click">
                        <div class="header-help-buttons">
                            <el-button type="primary" @click="resetHelpStatus">新手引导</el-button>
                            <el-button type="warning" @click="openHelpCenter">帮助文档</el-button>
                        </div>
                        <el-button slot="reference" style="background: none;color: #FFF" icon="el-icon-question">
                            帮助中心
                        </el-button>
                    </el-popover>
                </li>
                <li style="margin-right: 30px;" v-if="showAppFlag">
                    <el-button @click="goAppDownload" icon="el-icon-download" slot="reference"
                               style="background: none;color: #FFF">
                        APP下载
                    </el-button>
                </li>
                <li v-if="getcode !== 'admin'" style="margin-right: 30px;">
                    <popover-login></popover-login>
                </li>
                <li>
                    <el-popover
                            placement="bottom"
                            width="160"
                            trigger="click"
                            v-model="visible3"
                    >
                        <ul class="userControl">
                            <li>
                                <el-button type="text" icon="el-icon-key" @click="changePassword">修改密码</el-button>
                            </li>
                            <li v-if="!(getTenantCode === 'admin')">
                                <el-button type="text" icon="el-icon-s-order" @click="changeInformation">修改资料
                                </el-button>
                            </li>
                            <!--<li v-if="isDev">
                                <el-button type="text" icon="el-icon-location" @click="configThemeShow">系统配置
                                </el-button>
                            </li>-->
                            <li>
                                <el-button type="text" icon="el-icon-setting" @click="exitSystem">退出系统</el-button>
                            </li>
                        </ul>
                        <span class="h-right-img" slot="reference" @click="changeStatus">
                          <img :src="headerImg" alt="头像">
                          <span></span>
                        </span>
                    </el-popover>
                </li>
            </ul>
        </nav>
        <el-dialog
                title="修改密码"
                :visible.sync="headerPasswordDialog"
                :close-on-click-modal="false"
                @close="closePassDl"
                class="response-small-dialog"
                center>
            <el-form :model="HeaderPassChangeDate" status-icon :rules="HeaderPassRules" ref="ruleHeaderForm"
                     class="demo-ruleForm response-dialog-form-input" label-width="100px">
                <el-form-item label="原始密码：" prop="orgPass">
                    <el-input v-model="HeaderPassChangeDate.orgPass"></el-input>
                </el-form-item>
                <el-form-item label="新的密码：" prop="pass">
                    <el-input type="password" v-model="HeaderPassChangeDate.pass" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="确认密码：" prop="checkPass">
                    <el-input type="password" v-model="HeaderPassChangeDate.checkPass" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
        <el-button @click="headerPasswordDialog = false">取 消</el-button>
        <el-button type="primary" @click="saveHeaderPass">确 定</el-button>
      </span>
        </el-dialog>
        <el-dialog
                title="资料编辑"
                :visible.sync="editorMessage"
                :close-on-click-modal="false"
                @close="ClosePassDl2('editorUserInfo')"
                class="response-big-dialog"
                center>
            <el-form ref="formUserInfor" :rules="formRules3" status-icon :model="userInfoData" label-width="85px">
                <div class="editorUserWrap response-dialog-form-input">
                    <div>
                        <el-form-item label="用户名：" prop="userName">
                            <el-input v-model="userInfoData.userName"
                                      @blur="formatDataFun(userInfoData.userName)"></el-input>
                        </el-form-item>
                        <el-form-item label="真实姓名：" prop="realName">
                            <el-input v-model="userInfoData.realName"></el-input>
                        </el-form-item>
                        <el-form-item label="出生年月：" prop="birthday">
                            <el-date-picker
                                    v-model="userInfoData.birthday"
                                    type="date"
                                    :default-value="userInfoData.defaultBirthday"
                                    format="yyyy-MM-dd"
                                    value-format="yyyy-MM-dd"
                                    placeholder="选择日期">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label="电话号码：" prop="tel">
                            <el-input v-model="userInfoData.tel"></el-input>
                        </el-form-item>
                    </div>
                    <div>
                        <el-form-item label="性别：" prop="gender" label-width="90px">
                            <el-radio-group v-model="userInfoData.gender">
                                <el-radio border :label="1">男</el-radio>
                                <el-radio border :label="2">女</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="邮箱：" prop="email" label-width="90px">
                            <el-input v-model="userInfoData.email"></el-input>
                        </el-form-item>
                        <el-form-item label="身份证号：" prop="idcard" label-width="90px">
                            <el-input v-model="userInfoData.idcard"></el-input>
                        </el-form-item>
                    </div>
                    <div>
                        <!--<mta-upload-al-cloud :imageUrl="imageUrl"
                                             @uploadFileStart="uploadFileStart"></mta-upload-al-cloud>-->

                        <upload-file :imageUrl="imageUrl" :showBtnFlag="false"
                                     @getFileUrl="getImageUrl"></upload-file>
                        <h5 class="picture-size-h5">（最佳尺寸为65*65像素）</h5>
                    </div>
                </div>
            </el-form>
            <span slot="footer" class="dialog-footer">
        <el-button @click="cancelSaveUserInfo">取 消</el-button>
        <el-button type="primary" @click="saveUserInfo">确 定</el-button>
      </span>
        </el-dialog>
        <system-config :show="systemThemeDialog" @close="systemThemeDialogClose"></system-config>
        <!--<video-guid-content code="welcome" :visible.sync="wxyTestFun"></video-guid-content>
        <video-guid-content code="welcome2" :visible.sync="wxyTestFun2"></video-guid-content>-->

    </div>
</template>

<script>
    import {
        getAdminUserMypass,
        getAdminUserMyUpdate,
        getAdminUserMyInfo,
        getExitStatus,
    }                              from '@/api/user';
    import MtaUploadAlCloud        from '@/components/management/Layout/UploadAlCloud/UploadAlCloud';
    import uploadFile              from '@/components/management/Layout/UploadAlCloud/uploadFile';
    import SystemConfig            from '@/components/management/Layout/SystemConfig/SystemThemeConfig';
    import { mapGetters }          from 'vuex';
    import { setAuth, removeAuth } from '@/utils/auth';
    import {
        setUserIcon,
        checkUrlIsNotHttpUrl,
        aliUploadAndDownLoadFun,
        getTrimData,
    }                              from '@/utils/common';
    import videoGuidContent        from '@/components/management/Layout/videoBanner/dialogGuideContent';
    import { setGuide }            from '@/utils/guide';
    import PopoverLogin            from '@/components/management/Layout/popoverLogin/popoverLogin';

    export default {
        name:       'Header',
        data() {
            const validatePass2 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'));
                } else if (value !== this.HeaderPassChangeDate.pass) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };

            return {
                visible1:             false,
                visible2:             false,
                visible3:             false,
                isDev:                process.env.NODE_ENV !== 'production',
                wxyTestFun:           false,
                wxyTestFun2:          false,
                visible:              false,
                headerPasswordDialog: false,
                HeaderPassChangeDate: {
                    orgPass:   '',
                    pass:      '',
                    checkPass: '',
                },
                HeaderPassRules:      {
                    orgPass:   [
                        { message: '请输入原始密码', trigger: 'blur', required: true },
                    ],
                    pass:      [
                        { message: '请输入新密码', trigger: 'blur', required: true },
                    ],
                    checkPass: [
                        { validator: validatePass2, trigger: 'blur', required: true },
                    ],
                },
                editorMessage:        false,
                userInfoData:         {
                    userName:        '',
                    birthday:        '',
                    defaultBirthday: '',
                    email:           '',
                    gender:          '',
                    userId:          '',
                    idcard:          '',
                    realName:        '',
                    tel:             '',
                },
                formRules3:           {
                    userName: [
                        { trigger: 'blur', required: true, message: '请输入用户名' },
                    ],
                },
                imageUrl:             '',
                systemThemeDialog:    false,
                headerimgUrl:         require('../../../assets/images/default/user-img.png'),
                showAppFlag:          false,
            };
        },
        components: {
            MtaUploadAlCloud,
            SystemConfig,
            videoGuidContent,
            PopoverLogin,
            uploadFile,
        },
        computed:   {
            //个人头像
            headerImg() {
                return checkUrlIsNotHttpUrl(this.getReplaceIcon.headImg)
                       ? this.headerimgUrl
                       : this.getReplaceIcon.headImg;
            },
            logoImg() {
                if (this.getReplaceContext === null) {
                    return;
                }
                return this.getReplaceContext.logoImg;
            },
            logoText() {
                if (this.getReplaceContext === null) {
                    return;
                }
                return this.getReplaceContext.logoText;
            },
            getcode() {
                return this.getTenantCode;
            },
            getClient() {
                if (this.getAuth === null) {
                    return;
                }
                return this.getAuth.client;
            },
            getAframe() {
                if (this.getAuth === null) {
                    return;
                }
                return this.getAuth.aframe;
            },
            //个人头像
            ...mapGetters([
                              'getReplaceContext',
                              'getTenantCode',
                              'getAuth',
                              'getReplaceIcon',
                              'getGuide',
                          ]),
        },
        methods:    {
            getImageUrl(data) {
                this.imageUrl = data;
            },
            formatDataFun(data) {
                this.userInfoData.userName = getTrimData(data);
            },
            goAppDownload() {
                let url = this.getAuth.appUrl;
                window.open(url);
            },
            checkString(data) {
                if (data === '') {
                    return '';
                }

                if (data === null) {
                    return '';
                }

                if (data === undefined) {
                    return '';
                }

                return data;
            },
            resetHelpStatus() {
                let guide = this.getGuide;
                guide = {
                    show:    true,
                    details: {},
                };
                setGuide(guide);
                location.reload();
                this.visible1 = false;
            },
            /**
             * 主题配置
             */
            configThemeShow() {
                this.visible3 = false;
                this.systemThemeDialog = true;
            },
            /**
             * 主题配置弹窗关闭
             */
            systemThemeDialogClose(data) {
                this.systemThemeDialog = data;
            },
            openHelpCenter() {
                this.visible1 = false;
                /* if (process.env.VUE_APP_PROJECT === 'sa') {
                     window.location.href = this.getAuth.docMaita;
                 }
                 if (process.env.VUE_APP_PROJECT === 'qinggu') {
                     window.location.href = this.getAuth.docQinggu;
                 }*/

            },
            // 保存用户信息
            saveUserInfo() {
                const option = {
                    birthday: this.userInfoData.birthday,
                    email:    this.userInfoData.email,
                    gender:   this.userInfoData.gender,
                    icon:     this.imageUrl === undefined ? '' : this.imageUrl,
                    idcard:   this.userInfoData.idcard,
                    realName: this.userInfoData.realName,
                    userId:   this.userInfoData.userId,
                    userName: this.userInfoData.userName,
                    tel:      this.userInfoData.tel,
                };
                // 请求后台
                getAdminUserMyUpdate(option)
                .then(res => {
                    if (res.data) {
                        this.editorMessage = false;
                        // 个人头像 待定
                        const opt = {
                            headImg: option.icon,
                        };
                        setUserIcon(opt);
                        this.$message.success('修改成功');
                    }
                }).catch(err => {
                    // this.$message.error('请确定验证是否通过');
                    console.error('错误', err);
                });
            },
            // 取消
            cancelSaveUserInfo() {
                this.editorMessage = false;
            },
            changeStatus() {
                this.visible = !this.visible;
            },
            changePassword() {
                this.headerPasswordDialog = true;
                this.visible3 = false;
            },
            // 确认修改
            saveHeaderPass() {
                this.$refs.ruleHeaderForm.validate((valid) => {
                    if (valid) {
                        // 请求后台
                        const options = {
                            passwordNew: this.HeaderPassChangeDate.pass,
                            passwordOld: this.HeaderPassChangeDate.orgPass,
                        };

                        getAdminUserMypass(options)
                        .then(res => {
                            if (res.code === 0 && res.data) {
                                this.headerPasswordDialog = false;
                                this.$message.success('修改成功');
                            } else {
                                this.$message.error('修改失败');
                            }
                        });
                    } else {
                        this.$message.error('请确定验证是否通过');
                        return false;
                    }
                });
            },
            //
            closePassDl() {
                this.$refs.ruleHeaderForm.resetFields();
            },
            ClosePassDl2() {
                this.$refs.formUserInfor.resetFields();
            },
            /**
             * 上传文件
             */
            uploadFileStart(params) {
                if (!params) {
                    return;
                }
                aliUploadAndDownLoadFun(params, 'resource/', 'images/')
                .then(res => {
                    this.imageUrl = `${res.downloadUrl}/${res.key}`;
                })
                .catch(err => {
                    console.log(err);
                });
            },
            changeInformation() {
                this.visible3 = false;
                getAdminUserMyInfo()
                .then(res => {
                    const userInfoObj = res.data;
                    this.userInfoData.userName = userInfoObj.userName;
                    this.userInfoData.birthday = userInfoObj.birthday === null
                                                 ? new Date('1991-05-01')
                                                 : new Date(userInfoObj.birthday);
                    this.userInfoData.defaultBirthday = new Date(userInfoObj.birthday);
                    this.imageUrl = userInfoObj.icon;
                    this.userInfoData.email = userInfoObj.email;
                    this.userInfoData.gender = userInfoObj.gender;
                    this.userInfoData.idcard = userInfoObj.idcard;
                    this.userInfoData.realName = userInfoObj.realName;
                    this.userInfoData.tel = userInfoObj.tel;
                    this.userInfoData.userId = userInfoObj.userId;
                    this.editorMessage = true;
                }).catch(err => {
                    console.error('获取用户信息', err);
                });
            },
            exitSystem() {
                this.visible3 = false;
                getExitStatus().then(res => {
                    if (res.code === 0 && res.data) {
                        setTimeout(() => {
                            removeAuth();
                        }, 500)
                        this.$router.push({ path: '/a/login' });
                        // setAuth({});
                        this.$message.success('系统退出成功');
                    } else {
                        this.$message.error('系统退出失败');
                    }

                });

            },
        },
        created() {
            if (this.getAuth && this.getAuth.appUrl) {
                this.showAppFlag = true;
            }
        },
    };
</script>
