<template>
    <el-row class="container">
        <v-tour name="myTour" :steps="steps" :options="myOptions" :callbacks="myCallbacks" v-if="tourFlg"></v-tour>

        <el-col :span="24" class="header">
            <div class="contentMask" v-if="vTourFlg"></div>
            <el-col :span="10" class="logo" :class="collapsed?'logo-collapse-width':'logo-width'" :style="collapsed?'padding:0':''">
                <img v-if="collapsed" class="headImg" src="../assets/image/head_logo.png" />
                <div v-else class="logo-sys">
                    <img class="headImg" src="../assets/image/head_logo.png" />
                    <!-- <span>{{$t('workingHoursHousekeeper')}}</span> -->
                    <span>{{ themesType == 'dark' ? '临床工时通' : '工时管家' }}</span>
                </div>
            </el-col>
            <el-col :span="6">
                <div class="tools"  style="position: relative;">
                    <i class="fa fa-align-justify" @click.prevent="collapse" style="position: relative;z-index: 10;"></i>
                    <div class="gongshimingz">
                        {{user.companyName}}
                        <i v-if="user.roleName == '超级管理员' && user.companyName != '成都明夷电子科技有限公司'" class="el-icon-edit" @click="editCompanyNamedialog=true,companyForm.name = user.companyName"  style="position: relative;z-index: 15; margin-left: 5px;"></i>
                    </div>                    
                </div>
            </el-col>

            <el-col :span="12" class="userinfo" style="display: flex;align-items: center;justify-content: flex-end;">
                <!-- 中英文切换入口 -->
                <!-- <el-dropdown trigger="click" @command="langChange" style="margin-right:30px;">
                    <span class="el-dropdown-link userinfo-inner">
                        {{language}} <i class="el-icon-caret-bottom"></i>
                    </span>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item divided  command="zh">中文</el-dropdown-item>
                        <el-dropdown-item divided  command="en">English</el-dropdown-item>
                    </el-dropdown-menu> 
                </el-dropdown> -->
                <div style="margin-right: 10px;cursor: pointer;" @click="applicationMarket">
                    <i class="el-icon-menu" style="font-size:18px" ></i>
                    应用市场
                </div>
                <el-dropdown trigger="hover" style="margin-right:30px;">
                    <span class="el-dropdown-link userinfo-inner">
                        <i class="el-icon-user" style="font-size:18px" ></i>
                        <!-- {{$t('other.customerService')}} -->
                        {{ $t('bangZhuZhongXin') }} 
                    </span> 
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item >
                            <div v-if="!isCorpWX">
                                <!-- <div>{{$t('other.sweepWeChatYards')}}</div> -->
                                <!-- <div>扫码添加企业微信客服</div> -->
                                <div>{{ $t('ke-fu-wei-xin') }}</div>
                                <img
                                style="width: 120px; height: 120px"
                                src="../assets/image/code.jpg" />
                            </div>
                            <div v-if="isCorpWX">
                                <div>{{ $t('saoMaTianJiaQiYeWeiXinKeFu') }}</div>
                                <img
                                style="width: 153px; height: 153px"
                                src="../assets/image/qwcode.png" />
                            </div>
                            <div>
                                <div>
                                    <el-link type="primary" :underline="false" href="https://www.ttkuaiban.com/download/%E5%B7%A5%E6%97%B6%E7%AE%A1%E5%AE%B6%E7%AE%A1%E7%90%86%E7%B3%BB%E7%BB%9F%E4%BD%BF%E7%94%A8%E8%AF%B4%E6%98%8E%E4%B9%A6.pdf">{{ $t('dianJiChaKanCaoZuoShouCe') }}</el-link>
                                </div>
                            </div>
                        </el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown> 
                {{$t('time.dueDate')}}：{{remainingTime}}
                <el-badge class="itemNew" :value="num" :hidden="num == 0">
                    <i class="el-icon-message-solid" style="font-size:24px" v-popover:popover1 @click="drawer = true"></i>
                </el-badge>
                <el-drawer :title="$t('other.messageCenter')" :visible.sync="drawer" direction="rtl" :with-header="false" size="35%">
                    <el-table :data="popoverData" :height="tableHeight" size="small">
                        <el-table-column property="type" :label="$t('other.messageContent')" align="left">
                            <template slot-scope="scope">
                                <el-link type="primary" :underline="false" @click="locationHerf(scope.row.id, scope.row.content, scope.row.type, scope.row)">
                                    <span style="font-size:13px;">
                                        <span v-if="scope.row.msg == null">
                                            {{msgTypeTxt[scope.row.type]}}
                                        </span>
                                        <span v-else>
                                            <span v-if="user.userNameNeedTranslate != 1">
                                                {{scope.row.msg}}
                                            </span>
                                            <span v-if="user.userNameNeedTranslate == 1">
                                                {{scope.row.omg.textOne}}
                                                <TranslationOpenDataText v-if="user.corpwxUserid != null" type='userName' :openid='scope.row.omg.textTwo'></TranslationOpenDataText>
                                                <dt-open-data v-if="user.dingdingUserid != null" open-type='userName' :open-id='scope.row.omg.textTwo'></dt-open-data>
                                                {{scope.row.omg.textThree}}
                                            </span>
                                        </span>
                                        <!-- {{scope.row.msg==null?msgTypeTxt[scope.row.type]:scope.row.msg}} -->
                                    </span>
                                </el-link>
                            </template> 
                        </el-table-column>
                        <el-table-column property="type" :label="$t('state.states')" align="center" width="60">
                            <template slot-scope="scope">
                                <span v-if="scope.row.checked == 0" style="color:red">{{$t('other.unread')}}</span>
                                <span v-else style="color:green">{{$t('other.read')}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column property="time" :label="$t('time.times')" align="center" width="120"></el-table-column>
                    </el-table>
                </el-drawer>                
                <el-dropdown trigger="hover" style="margin-left:10px;">
                    <span class="el-dropdown-link userinfo-inner">
                        <img src="../assets/image/userHead.png" />
                        <!-- <span v-if="user.userNameNeedTranslate == 1">
                            <TranslationOpenDataText type='userName' :openid='sysUserName'></TranslationOpenDataText>
                        </span>
                        <span v-if="user.dingdingUserid">
                            <dt-open-data open-type='userName' :open-id='user.dingdingUserid'></dt-open-data>
                        </span>
                        <span v-if="user.userNameNeedTranslate != 1">
                            {{sysUserName}}
                        </span> -->
                        <TranslationOpenData :configurationItems="{ openType: 'userName', openId: sysUserName, renderIndex: 0 }" />
                        <!-- {{sysUserName}} -->
                    </span>
                    <el-dropdown-menu slot="dropdown">
                        <!-- <el-dropdown-item disabled ><span style="font-size:12px;"><i class="el-icon-view" ></i>{{roleArray[user.role]}}</span></el-dropdown-item> -->
                        <el-dropdown-item disabled ><span style="font-size:12px;"><i class="el-icon-view" ></i>{{user.roleName}}</span></el-dropdown-item>
                        <el-dropdown-item disabled ><span style="font-size:12px;"><i class="el-icon-medal" v-if="user.jobNumber"></i>{{user.jobNumber}}</span></el-dropdown-item>
                        <el-dropdown-item @click.native="reset" v-if="user.userNameNeedTranslate != 1">{{$t('other.changeThePassword')}}</el-dropdown-item>
                        <!-- <el-dropdown-item @click.native="editInfoOpen">修改信息</el-dropdown-item> -->
                        <el-dropdown-item divided @click.native="logout" v-if="!isCorpWX" >{{$t('other.launchTheLogin')}}</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </el-col>
        </el-col>

        <el-col :span="24" class="main">

            <aside :class="collapsed?'menu-collapsed':'menu-expanded'">
                <el-scrollbar style="height:100%">
                <!--导航菜单-->
                <el-menu :default-active="$route.path" class="el-menu-vertical-demo" unique-opened router v-if="!collapsed" :default-openeds="['zhan']">
                    <template v-for="(item, index) in $router.options.routes" v-if="!item.hidden">
                        <!-- <el-submenu :index="index+''" v-if="!item.leaf"> -->
                        <el-submenu :index="'zhan'" v-if="!item.leaf">
                            <template slot="title"> 
                                <i :class="item.iconCls"></i>
                                <!-- <span class="itemName">{{item.name}}</span> -->
                                <span class="itemName bosx" v-if="$t(item.meta.text).length < 16">{{$t(item.meta.text)}}</span>
                                <el-tooltip class="itemName bosx"  v-if="$t(item.meta.text).length > 16" effect="dark" :content="$t(item.meta.text)" placement="top">
                                    <span>{{$t(item.meta.text)}}</span>
                                </el-tooltip>
                            </template>
                            <el-menu-item v-for="child in item.children" :index="child.path" :key="child.path" v-if="!child.hidden" :data-v-step="child.path"><i :class="child.iconCls"></i>
                                <!-- {{child.name}} -->
                                <span class="bosx" v-if="$t(child.meta.text).length < 16">{{$t(child.meta.text)}}</span>
                                <el-tooltip class="bosx"  v-if="$t(child.meta.text).length > 16" effect="dark" :content="$t(child.meta.text)" placement="top">
                                    <span>{{$t(child.meta.text)}}</span>
                                </el-tooltip>
                            </el-menu-item>
                        </el-submenu>
                        <el-menu-item v-if="item.leaf && item.children.length > 0" :index="item.children[0].path" :data-v-step="item.children[0].path">
                            <i :class="item.iconCls"></i> 
                            <!-- {{item.children[0].name}} -->
                            <span class="bosx" v-if="$t(item.meta.text).length <= 16">{{$t(item.meta.text)}}</span>
                            <el-tooltip class="itemName bosx"  v-if="$t(item.meta.text).length > 16" effect="dark" :content="$t(item.meta.text)" placement="top">
                                <span>{{$t(item.meta.text)}}</span>
                            </el-tooltip>
                            <!-- {{$t('navigation.reports')}} -->
                            <!-- this.$t('navigation.reports')  // js-->
                        </el-menu-item>
                    </template>
                </el-menu>

                <!--导航菜单-折叠后-->
                <ul class="el-menu el-menu-vertical-demo collapsed" v-if="collapsed" ref="menuCollapsed">
                    <li v-for="(item,index) in $router.options.routes" v-if="!item.hidden" class="el-submenu item" :style="{overflow:!item.leaf?'':'hidden'}">
                        <template v-if="!item.leaf">
                            <div class="el-submenu__title" style="padding-left: 20px;" @mouseover="showMenu(index,true)" @mouseout="showMenu(index,false)">
                                <i :class="item.iconCls"></i>
                            </div>
                            <ul class="el-menu submenu" :class="'submenu-hook-'+index" @mouseover="showMenu(index,true)" @mouseout="showMenu(index,false)">
                                <li v-for="child in item.children" v-if="!child.hidden" :key="child.path" class="el-menu-item" style="padding-left: 40px;" :class="$route.path==child.path?'is-active':''" @click="$router.push(child.path)">
                                    {{child.name}}
                                </li>
                            </ul>
                        </template>
                        <template v-else>
                            <li class="el-submenu">
                                <div class="el-submenu__title el-menu-item" :class="$route.path==item.children[0].path?'is-active':''" @click="$router.push(item.children[0].path)"
                                    style="padding-left: 20px;height: 56px;line-height: 56px;padding: 0 20px;">
                                    <i :class="item.iconCls"></i>
                                </div>
                            </li>
                        </template>
                    </li>
                </ul>
                </el-scrollbar>
            </aside>

            <section class="content-container">
                <div class="contentMask" v-if="vTourFlg"></div>
                <div class="grid-content h-full bg-purple-light">
                    <el-col :span="24" class="content-wrapper h-full">
                        <transition name="fade" mode="out-in">
                            <router-view></router-view>
                        </transition>
                    </el-col>
                </div>

                <!--修改密码-->
                <el-dialog :title="$t('other.changeThePassword')" width='450px' v-if="editPassWord" :visible.sync="editPassWord" :close-on-click-modal="false" customClass="customWidth">
                    <el-form :model="addForm" label-width="auto" :rules="passRule" ref="addForm">
                        <el-form-item :label="$t('lable.originalPassword')" prop="originPassword">
                            <el-input v-model="addForm.originPassword" autocomplete="off" :placeholder="$t('defaultText.pleaseEnterTheOldPassword')" show-password></el-input>
                        </el-form-item>
                        <el-form-item :label="$t('lable.newPassword')" prop="newPassword">
                            <el-input v-model="addForm.newPassword" autocomplete="off" :placeholder="$t('defaultText.pleaseEnterTheNewPassword')" show-password></el-input>
                        </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click.native="editPassWord = false">{{$t('btn.cancel')}}</el-button>
                        <el-button type="primary" @click.native="resetPwd" :loading="editLoading">{{$t('btn.submit')}}</el-button>
                    </div>
                </el-dialog>

                <!--修改信息-->
                <el-dialog :title="$t('title.modifyTheInformation')" width='450px' v-if="editInformation" :visible.sync="editInformation" :close-on-click-modal="false" customClass="customWidth">
                    <el-form :model="editInfoForm" label-width="auto" :rules="passRule" ref="editInfoForm">
                        <el-form-item :label="$t('lable.name')" prop="username">
                            <el-input v-model="editInfoForm.username" autocomplete="off" :placeholder="$t('defaultText.PleaseEnterYourName')"></el-input>
                        </el-form-item>
                    </el-form>
                    <el-form :model="editInfoForm" label-width="auto" :rules="passRule" ref="editInfoForm">
                        <el-form-item :label="$t('lable.phone')" prop="mobile">
                        <el-input v-model="editInfoForm.mobile" autocomplete="off" :placeholder="$t('defaultText.PleaseEnterYourPhone')" :disabled="true"></el-input>
                        </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click.native="editInformation = false">{{$t('btn.cancel')}}</el-button>
                        <el-button type="primary" @click.native="editInfo" :loading="editLoading2">{{$t('btn.submit')}}</el-button>
                    </div>
                </el-dialog>

                <el-dialog
                    :title="$t('xiuGaiGongSiMingCheng')"
                    :visible.sync="editCompanyNamedialog"
                    width="30%">
                    <el-form :model="companyForm" :rules="rules" ref="companyForm" label-width="100px" class="demo-ruleForm">
                        <el-form-item :label="$t('gongSiMingCheng')" prop="name">
                            <el-input v-model.trim="companyForm.name"></el-input>
                        </el-form-item>
                    </el-form>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="editCompanyNamedialog = false">{{ $t('quXiao') }}</el-button>
                        <el-button type="primary" @click="editCompanyName('companyForm')">{{ $t('queDing') }}</el-button>
                    </span>
                </el-dialog>
            </section>
        </el-col>

        <!-- 完善工号弹窗 -->
        <el-dialog :title="$t('wanShanGongHao')" :visible.sync="perfectJobNumber" width="500px" :show-close="false">
            <el-form :model="perfectForm" :rules="rules" ref="perfectForm" label-width="80px" class="demo-ruleForm">
                <el-form-item :label="$t('Worknumber')" prop="jobNumber">
                    <el-input v-model.trim="perfectForm.jobNumber"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="editPerfectJobNumber('perfectForm')">{{ $t('queDing') }}</el-button>
            </span>
        </el-dialog>

        <!-- 完善名称弹窗 -->
        <el-dialog :title="$t('wanShanXingMing')" :visible.sync="perfectName" width="500px" :show-close="false">
            <el-form :model="perfectFormName" :rules="rules" ref="perfectFormName" label-width="80px" class="demo-ruleForm">
                <el-form-item :label="$t('lable.name')" prop="userName">
                    <el-input v-model.trim="perfectFormName.userName"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="editPerfectName('perfectFormName')">{{$t('queDing')}}</el-button>
            </span>
        </el-dialog>
    </el-row>
</template>

<script>
    import util from "../common/js/util";
    export default {
        // 引用 app.vue reloads 方法
        inject:['reloads'],
        data() {
            return {
                themesType: 'default',
                textLength: 16,
                companyForm:{
                    name: '',
                },
                perfectForm:{
                    jobNumber: '',
                },
                perfectFormName: {
                    userName: '',
                },
                rules: {
                    name: [
                        { required: true, message: this.$t('qingShuRuGongSiMingCheng'), trigger: 'blur' },
                        { min: 1, max: 20, message: this.$t('changDuWei_120GeZiFu'), trigger: 'blur' }
                    ],
                    jobNumber: [
                        { required: true, message: this.$t('qingShuRuGongHao'), trigger: 'blur' }
                    ],
                    userName: [
                        { required: true, message: this.$t('defaultText.PleaseEnterYourName'), trigger: 'blur' }
                    ]
                },
                tourFlg: false,
                editCompanyNamedialog:false,
                firstTourFalse: localStorage.getItem('firstTourFalse') | true, // 是否需要新手指导
                steps: [
                    {
                        target: '[data-v-step="/timetype"]',
                        content: `第一步，查看基础设置，按照企业情况进行调整`,
                        params: {
                            placement: 'right',
                            highlight: true 
                        }
                    },{
                        target: '[data-v-step="/list"]',
                        content: `第二步，创建项目和任务`,
                        params: {
                            placement: 'right',
                            highlight: true 
                        }
                    },{
                        target: '[data-v-step="/daily"]',
                        content: `第三步，填写每日工时报告`,
                        params: {
                            placement: 'right',
                            highlight: true 
                        }
                    },{
                        target: '[data-v-step="/review"]',
                        content: `第四步，项目报告审核`,
                        params: {
                            placement: 'right',
                            highlight: true 
                        }
                    },{
                        target: '[data-v-step="/cost"]',
                        content: `第五步，查看工时成本统计结果`,
                        params: {
                            placement: 'right',
                            highlight: true 
                        }
                    },{
                        target: '[data-v-step="/finance"]',
                        content: `第六步，导入薪资，校准成本并生成财务报表`,
                        params: {
                            placement: 'right',
                            highlight: true 
                        }
                    }
                ],
                myOptions:{
                    useKeyboardNavigation: false,    //不使用←、→和ESC键来导航tour
                    startTimeout: 1000,   //1秒后执行
                    highlight: true,
                    labels: {
                        buttonSkip: this.$t('tiaoGuo'),
                        buttonPrevious: this.$t('btn.previousstep'),
                        buttonNext: this.$t('btn.nextStep'),
                        buttonStop: this.$t('Shutdown')
                    }
                },
                myCallbacks: {
                    onSkip: this.onSkip,   //在data中定义两个回调
                    onFinish: this.onFinish
                },

                isCorpWX: false,
                // roleArray:["普通员工","超级管理员", "系统管理员", "公司高层","财务管理员", "项目管理员","公司领导"],
                roleArray:[this.$t('role.ordinaryEmployees'),this.$t('role.superAdministrator'),this.$t('role.systemAdministrator'),this.$t('role.companyTop'),this.$t('role.financialAdministrator'),this.$t('role.projectManager'),this.$t('role.companyLeadership')],
                helpImg: '../assets/image/userHead.png',
                user: sessionStorage.getItem("user"),
                collapsed: sessionStorage.collapsed!=null?(sessionStorage.collapsed=='true'?true:false):false,
                sysUserName: "",
                menu: [],
                // msgTypeTxt:["审批未通过","有新任务啦","任务有新进展","项目日报审核通过"],
                msgTypeTxt:[this.$t('state.notApproved'),this.$t('state.ThereIsAnewTask'),this.$t('state.TheresBeen'),this.$t('state.approvedProject')],
                editInformation: false,
                editPassWord: false,
                editLoading: false,
                editLoading2: false,
                addForm: {
                    id: "",
                    originPassword: "",
                    newPassword: ""
                },
                editInfoForm: {
                    id: "",
                    username: "",
                    mobile: "",
                    companyName: ""
                },
                passRule: {
                    originPassword: [{ required: true, message: this.$t('defaultText.pleaseEnterTheOldPassword'), trigger: "blur" }],
                    newPassword: [{ required: true, message: this.$t('defaultText.pleaseEnterTheNewPassword'), trigger: "blur" }],
                    username: [{ required: true, message: this.$t('defaultText.PleaseEnterYourName'), trigger: "blur" }]
                },

                //时间
                activeDate: new Date(),

                timer: null,
                remainingTime: '',

                drawer: false,
                tableHeight: 0,
                popoverData: [],
                num: 0,

                language: '',
                setTimeLoad: null,

                // 遮罩
                vTourFlg: false,

                
                perfectJobNumber: false, // 完善工号弹窗
                perfectName: false, // 完成名称弹窗
                jobNumberCheckCompanyId: [936], // 定制需求，需要完善工号的公司id
            };
        },
        created() {
            this.firstTourFalse = localStorage.getItem('firstTourFalse') || true
            console.log(this.firstTourFalse, '数据书数据')
            console.log(localStorage.getItem('firstTourFalse'))
        },
        methods: {
            applicationMarket() {
                window.location.href = 'https://www.ttkuaiban.com/appMarket.html'
                // window.open('https://www.ttkuaiban.com/appMarket.html', '_blank'); 
            },
            getSkipGuidance() {
                this.http.post('/user/skipGuidance', {},
                res => {
                    if (res.code == "ok") {
                        let users = JSON.parse(sessionStorage.getItem("user"))
                        users.isFirstLogin == 0
                        sessionStorage.setItem("user", JSON.stringify(users))
                    }
                },
                error => {
                });
            },
            onSkip(currentStep) {
                console.log('看看')
                this.vTourFlg = false
                this.firstTourFalse = false
                localStorage.setItem('firstTourFalse', false)
                console.log(this.user, '用户信息')
                if(this.user.corpwxUserid != null) {
                    this.getSkipGuidance()
                }
            },
            onFinish(currentStep) {
                console.log('数据')
                this.vTourFlg = false
                this.firstTourFalse = false
                localStorage.setItem('firstTourFalse', false)
                this.getSkipGuidance()
                if(this.user.corpwxUserid != null) {
                    this.getSkipGuidance()
                }
            },

            // 中英文切换
            langChange(command) {
                let flg = this.language
                this.$i18n.locale = command
                localStorage.setItem("lang", command)
                if(command == 'en') {
                    this.language = 'English'
                } else if (command == 'zh') {
                    this.language = '中文'
                }
                if(flg != this.language) {
                    this.reloads()
                }
            },
            
            //退出登录
            logout: function() {
                var _this = this;
                this.$confirm(this.$t('other.confirmExit') + '?', this.$t('other.prompts'), {
                    //type: 'warning'
                    confirmButtonText: this.$t('btn.submit'),
                    cancelButtonText: this.$t('btn.cancel'),
                }).then(() => {
                    sessionStorage.removeItem("user");
                    location.reload();
                    _this.$router.push("/login");
                });
            },

            //折叠导航栏
            collapse: function() {
                this.collapsed = !this.collapsed;
                sessionStorage.collapsed = this.collapsed;
            },

            showMenu(i, status) {
                this.$refs.menuCollapsed.getElementsByClassName(
                    "submenu-hook-" + i
                )[0].style.display = status ? "block" : "none";
            },

            //打开编辑信息界面
            editInfoOpen() {
                this.editInformation = true;
                this.editInfoForm.id = JSON.parse(sessionStorage.getItem("user")).id;
                this.editInfoForm.username = JSON.parse(
                    sessionStorage.getItem("user")
                ).username;
                this.editInfoForm.mobile = JSON.parse(
                    sessionStorage.getItem("user")
                ).account;
                this.editInfoForm.companyName = JSON.parse(
                    sessionStorage.getItem("user")
                ).companyName;
            },

            //编辑信息
            editInfo() {
                this.$refs.editInfoForm.validate(valid => {
                    if (valid) {
                    this.editLoading2 = true;
                    this.http.post(
                        this.port.pwd.resetPwd,
                        { id: this.editInfoForm.id, username: this.editInfoForm.username },
                        res => {
                        this.editLoading2 = false;
                        this.editInformation = false;
                        if (res.code == "ok") {
                            this.$message({
                            message: this.$t('message.modifyTheSuccess'),
                            type: "success"
                            });
                            //读取并覆盖session storage
                            var userObject = JSON.parse(sessionStorage.getItem("user"));
                            userObject.username = this.editInfoForm.username;
                            sessionStorage.setItem("user", JSON.stringify(userObject));
                            this.sysUserName = this.editInfoForm.username;
                        } else {
                            this.$message({
                            message: res.msg,
                            type: "error"
                            });
                        }
                        },
                        error => {
                        this.editLoading2 = false;
                        this.editInformation = false;
                        this.$message({
                            message: error,
                            type: "error"
                        });
                        }
                    );
                    }
                });
            },

            
            //编辑公司名称
            editCompanyName(companyForm){
                this.$refs[companyForm].validate((valid) => {
                    if (valid) {
                        this.http.post("/company/editCompanyName", {name:this.companyForm.name},
                            res => {
                            if (res.code == "ok") {
                                this.editCompanyNamedialog = false;
                                let list = JSON.parse(sessionStorage.getItem("user") || '[]')
                                sessionStorage.removeItem('user')
                                this.user.companyName = this.companyForm.name
                                list.companyName = this.companyForm.name
                                sessionStorage.setItem("user",JSON.stringify(list))
                                this.$message({
                                message: res.msg,
                                type: "success"
                                });
                            } else {
                                this.$message({
                                message: res.msg,
                                type: "error"
                                });
                            }
                            },
                            error => {
                            this.$message({
                                message: error,
                                type: "error"
                            });
                        });
                    } else {
                        return false;
                    }
                });
            },

            reset() {
                this.editPassWord = true;
                this.addForm.id = JSON.parse(sessionStorage.getItem("user")).id;
                this.addForm.account = JSON.parse(sessionStorage.getItem("user")).account;
            },

            resetPwd() {
                this.$refs.addForm.validate(valid => {
                    if (valid) {
                        this.editLoading = true;
                        this.http.post( this.port.manage.editPassword, this.addForm,
                            res => {
                            this.editLoading = false;
                            this.editPassWord = false;
                            if (res.code == "ok") {
                                this.$message({
                                // message: "修改成功,请重新登录",
                                message: this.$t('message.logAganin'),
                                type: "success"
                                });
                                this.$router.push("/login");
                            } else {
                                this.$message({
                                message: res.msg,
                                type: "error"
                                });
                            }
                            },
                            error => {
                            this.editLoading = false;
                            this.editPassWord = false;
                            this.$message({
                                message: error,
                                type: "error"
                            });
                        });
                    }
                });
            },

            setTime() {
                var d = util.formatDate.cdTime(new Date(new Date().getTime() + this.user.remainingTime), new Date(), 'd');
                var h = util.formatDate.cdTime(new Date(new Date().getTime() + this.user.remainingTime), new Date(), 'h');
                var m = util.formatDate.cdTime(new Date(new Date().getTime() + this.user.remainingTime), new Date(), 'm');
                var s = util.formatDate.cdTime(new Date(new Date().getTime() + this.user.remainingTime), new Date(), 's');
                this.remainingTime = d+this.$t('time.day')+h+this.$t('shi')+m+this.$t('fen')+s+this.$t('miao');
            },

            // 加载消息
            loadNotice() {
                this.http.post( this.port.manage.msgList, {},
                res => {
                    if (res.code == "ok") {
                        var list = res.data;
                        if(this.user.userNameNeedTranslate == 1) {
                            let msgArr = res.data
                            for(var i in msgArr) {
                                if(msgArr[i].msg) {
                                    let caozuo = JSON.parse(JSON.stringify(msgArr[i].msg))
                                    if(caozuo.indexOf('$userName=') != '-1') {
                                        let textOne = caozuo.split('$userName=')[0]
                                        let textTwo = caozuo.split('$userName=')[1].split('$')[0]
                                        let textThree = caozuo.split('$userName=')[1].split('$')[1]
                                        msgArr[i].omg = {
                                            textOne: textOne,
                                            textTwo: textTwo,
                                            textThree: textThree
                                        }
                                    } else {
                                        msgArr[i].omg = {
                                            textOne: msgArr[i].msg,
                                            textTwo: '',
                                            textThree: ''
                                        }
                                    }
                                } else {
                                    msgArr[i].omg = {
                                        textOne: '',
                                        textTwo: '',
                                        textThree: ''
                                    }
                                }
                            }
                        }
                        this.popoverData = res.data;
                        var num = 0;
                        for(var i in list) {
                            if(list[i].checked != 1) {
                                num ++;
                            }
                        }
                        this.num = num;
                    } else {
                        this.$message({
                            message: res.msg,
                            type: "error"
                        });
                    }
                },
                error => {
                    this.$message({
                        message: error,
                        type: "error"
                    });
                });
            },

            //点击消息的跳转
            locationHerf(id, date, type, row) {
                this.http.post( this.port.manage.check, { id: id },
                res => {
                    if (res.code == "ok") {
                        this.loadNotice();
                        if (type == 0) {
                            //审批未通过的消息， 也包括审批通过的通知
                            sessionStorage.msg = date;
                            sessionStorage.from = 1;
                            //本页面再点的话强制转移一下
                            var currentRoute = this.$route.path.split("/");
                            if (currentRoute[1] == "daily") {
                                this.$router.go(0);
                                this.drawer = false;
                                return false;
                            }
                            this.$router.push("/daily");
                            this.drawer = false;
                        } else if (type == 1) {
                            //1- 有新任务待执行
                            this.$router.push("/projectInside/"+date);
                            this.drawer = false;
                        } else if (type == 2) {
                            //2- 任务有新进展
                            this.$router.push("/projectInside/"+date);
                            this.drawer = false;
                        } else if (type == 3) {
                            //3- 费用报销
                            this.$router.push("/expense");
                            this.drawer = false;
                        } else if (type == 4) {
                            //4- 请假消息
                            this.$router.push("/leave");
                            this.drawer = false;
                        } else if (type == 5) {
                            //5- 出差消息
                            this.$router.push("/awayOffice");
                            this.drawer = false;
                        } else if (type == 6 || type == 7 || type == 8) {
                            // 6、7 合同通过、驳回
                            this.$router.push("/contract");
                            this.drawer = false;
                        } else if (type == 10) {
                            // 10 预估工时审核 通过 驳回
                            var action = '';
                            //跳转进入项目的任务看板
                            date = decodeURIComponent(date);
                            if (date.includes('@adjustBudget-')) {
                                //需要打开分组预估工时设置
                                action = date.split('@')[1];
                                date = date.split('@')[0];
                            }
                            sessionStorage.action = action
                            this.$router.push("/projectInside/"+date);
                            this.drawer = false;
                        } else if(type == 11) {
                            console.log(row, '<====== ganttData')
                            const { taskId, ganttData } = row
                            this.$router.push({
                                path: '/list',
                                query: { 
                                    messageTaskId: taskId,
                                    ganttData: JSON.stringify(ganttData || {}) 
                                }
                            });
                            this.drawer = false;
                        }
                        
                        
                    } else {
                        this.$message({
                            message: res.msg,
                            type: "error"
                        });
                    }
                },
                error => {
                    this.$message({
                        message: error,
                        type: "error"
                    });
                });
            },

            // 获取企业微信的参数
            agentConfig() {
                var isCorpWX = true
                var ua = navigator.userAgent.toLowerCase();
                if (ua.indexOf("wxwork") > 0) {
                    isCorpWX = false;
                } 
                var curUrl = location.href.split("#")[0];
                this.http.post("/wxcorp/getCorpWXConfig", {url: curUrl, token: this.user.id}, (res) => {
                    if (res.code == "ok") {
                        wx.config({ 
                        beta: true,
                        debug: isCorpWX, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                        appId: res.data.appid, // 必填，公众号的唯一标识 
                        timestamp: res.data.timestamp, // 必填，生成签名的时间戳 
                        nonceStr: res.data.noncestr, // 必填，生成签名的随机串 
                        signature: res.data.sign, // 必填，签名，见附录1 
                        jsApiList: ['chooseImage','previewImage','uploadImage','downloadImage','previewFile','getLocation','agentConfig', 'getLocalImgData'] 
                        });
                        var that = this;
                        wx.ready(function(){
                            // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
                                that.http.post("/wxcorp/getCorpWXAgentConfig", {url: curUrl, token: that.user.id}, (res) => {
                                    if (res.code == "ok") {
                                    console.log()
                                        wx.agentConfig({
                                            corpid: res.data.corpid, // 必填，企业微信的corpid，必须与当前登录的企业一致
                                            agentid: res.data.agentid, // 必填，企业微信的应用id （e.g. 1000247）
                                            timestamp: res.data.timestamp, // 必填，生成签名的时间戳
                                            nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
                                            signature: res.data.signature, // 必填，签名，见附录-JS-SDK使用权限签名算法
                                            jsApiList: ['selectExternalContact', 'selectEnterpriseContact', 'openAppManage'], //必填，传入需要使用的接口名称
                                            success: function (result) {
                                                console.log(result, '请求微信成功')
                                                console.log(window, 'window')
                                                //  wx.agentConfig成功回调后，WWOpenData 才会注入到 window 对象上面
                                                if(window.WWOpenData) {
                                                    window.WWOpenData.bind(document.querySelector('TranslationOpenDataText'))
                                                    if (WWOpenData.initCanvas) {
                                                        WWOpenData.initCanvas()
                                                        console.log('我企业微信 canvas 应该执行了吧')
                                                    }
                                                }
                                            },
                                            fail: function (res) {
                                                console.log('查看错误信息', res)
                                                if (res.errMsg.indexOf('function not exist') > -1) {
                                                    alert(that.$t('banBenGuoDiQingShengJi'))
                                                }
                                            },
                                        })
                                    }
                                }, (error) => {
                                    console.log('查看错误信息' + res)
                                    if (error.errMsg.indexOf('function not exist') > -1) {
                                        alert(that.$t('banBenGuoDiQingShengJi'))
                                    }
                                })
                        });
                    }
                }, (error) => {
                    console.log(error, '哦耶')
                })
            },

            // 完善工号
            editPerfectJobNumber(perfectForm) {
                this.$refs[perfectForm].validate((valid) => {
                    if (valid) {
                        const { id } = this.user
                        this.http.post("/user/updateUserJobNumber", {
                            jobNumber: this.perfectForm.jobNumber,
                            userId: id
                        },
                        res => {
                            if (res.code == "ok") {
                                this.perfectJobNumber = false
                                let nerUser = {
                                    ...this.user,
                                    jobNumber: this.perfectForm.jobNumber
                                }
                                sessionStorage.setItem('user', JSON.stringify(nerUser));
                                this.$message({
                                    message: this.$t('operationissuccessful'),
                                    type: "success"
                                });
                            } else {
                                this.$message({
                                    message: res.msg,
                                    type: "error"
                                });
                            }
                        },
                        error => {
                            this.$message({
                                message: error,
                                type: "error"
                            });
                        });
                    } else {
                        return false;
                    }
                });
            },
            // 完善姓名
            editPerfectName(perfectForm) {
                this.$refs[perfectForm].validate((valid) => {
                    if (valid) {
                        this.http.post("/user/userRename", {
                            newName: this.perfectFormName.userName,
                        },
                        res => {
                            if (res.code == "ok") {
                                this.perfectName = false
                                let nerUser = {
                                    ...this.user,
                                    name: this.perfectFormName.userName
                                }
                                sessionStorage.setItem('user', JSON.stringify(nerUser));
                                this.$message({
                                    message: this.$t('operationissuccessful'),
                                    type: "success"
                                });
                            } else {
                                this.$message({
                                    message: res.msg,
                                    type: "error"
                                });
                            }
                        },
                        error => {
                            this.$message({
                                message: error,
                                type: "error"
                            });
                        });
                    } else {
                        return false;
                    }
                });
            },

            setDDOpenData() {
                const ddUrl = new URL(window.location.href);
                const ddCorpid = ddUrl.searchParams.get("corpid") || ''
                let ddOpenDataInit = window.DTOpenData.init(ddCorpid)
                console.log(ddOpenDataInit, '<=== 钉钉执行 window.DTOpenData.init(ddCorpid) 的判断')
                if (ddOpenDataInit) {
                    setTimeout(() => {
                        console.log('<==== 执行 window.DTOpenData.update(document.querySelectorAll(dt-open-data))')
                        window.DTOpenData.update(document.querySelectorAll('dt-open-data'));
                    }, 300)
                }else {
                    console.log('钉钉没有触发')
                }
            }
        },
        mounted() {
            var ua = navigator.userAgent.toLowerCase();
            this.themesType = localStorage.getItem('themes') || 'default';
            if (ua.indexOf("wxwork") > 0) {
                this.isCorpWX = true;
            } 
            let langse = localStorage.getItem("lang") || 'zh'
            if(langse == 'en') {
                this.language = 'English'
            } else if (langse == 'zh') {
                this.language = '中文'
            }

            let height = window.innerHeight;
            this.tableHeight = height - 15;
            const that = this;
            window.onresize = function temp() {
                that.tableHeight = window.innerHeight - 15;
            };

            if (this.user) {
                var user = JSON.parse(this.user);
                this.user = user;
                this.sysUserName = user.name || "";
                this.loadNotice();
                if(this.user.remainingTime != "" && this.user.remainingTime != 0) {
                    this.remainingTime = util.formatDate.format(new Date(new Date().getTime() + this.user.remainingTime), "yyyy-MM-dd")
                } else {
                    this.remainingTime = this.$t('other.expired');
                    clearInterval(this.timer);
                }
            } else {
                this.$router.push("/login");
            }

            // console.log('啊，我被触发了呀')
            // 获取企业微信参数
            if(this.user.userNameNeedTranslate == '1') {
                this.agentConfig()
            }

            // 判断是否为新用户
            if(this.user.isFirstLogin == 1 && this.user.roleName == this.$t('role.superAdministrator') && this.firstTourFalse != 'false' && this.user.createTime[0] > '2022') {
                var thats = this
                this.tourFlg = true
                setTimeout(() => {
                    thats.$tours['myTour'].start()
                    setTimeout(() => {
                        thats.vTourFlg = true
                    }, 1000)
                }, 200)
            }

            // 检查是否有工号
            const { jobNumber, companyId, userNameNeedTranslate, name, dingdingUserid } = this.user
            if(this.jobNumberCheckCompanyId.includes(companyId) && !jobNumber) {
                this.perfectJobNumber = true
            }
            // 检查是否需要完成姓名
            if(userNameNeedTranslate == 0 && (name == dingdingUserid)) {
                this.perfectName = true
            }
            if(this.user.dingdingUserid) {
                this.setDDOpenData()
            }

            // 中英文显示字符长度
            if(this.language == '中文') {
                this.textLength = 16
            } else {
                this.textLength = 17
            }
        },
    };
</script>

<style scoped lang="scss">
@import "../assets/scss/handle";
.contentMask {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    background: #000;
    opacity: .4;
    z-index: 99;
    // box-shadow: 0 0 0 99999px rgba(0,0,0,.4) !important;
}

.gongshimingz {
    width: 100%;
    position: absolute;
    left: 0px;
    display: inline-block;
    overflow: hidden; 
    white-space: nowrap;  
    text-overflow: ellipsis; 
    box-sizing: border-box;
    padding-left: 60px;
}
    .el-menu-vertical-demo i {
        margin-right: 10px;
    }

    .container {
        position: absolute;
        top: 0px;
        bottom: 0px;
        width: 100%;
        .header {
            height: 60px;
            line-height: 60px;
            @include background_color("background_color");
            color: #fff;
            position: relative;
            .userinfo {
                text-align: right;
                padding-right: 35px;
                float: right;
                .userinfo-inner {
                    cursor: pointer;
                    color: #fff;
                    img {
                        width: 40px;
                        height: 40px;
                        border-radius: 20px;
                        margin: 10px 10px 10px 10px;
                        float: left;
                    }
                }
                .itemNew {
                    height: 25px;
                    margin: 0 0 0 10px;
                    i {
                        vertical-align: top;
                    }
                }
            }
            .logo {
                height: 60px;
                font-size: 21px;
                padding-left: 20px;
                padding-right: 20px;
                border-color: rgba(238, 241, 146, 0.3);
                border-right-width: 1px;
                border-right-style: solid;
                img {
                    width: 40px;
                    float: left;
                    margin: 10px 10px 10px 18px;
                }
                img.headImg {
                    margin: 0;
                    width: 40px;
                    height: 40px;
                    margin: 10px 0 0 10px;
                }
                .logo-sys {
                    height: 100%;
                    line-height: 100%;
                    img.headImg {
                        width: 40px;
                        height: 40px;
                        margin: 7.5px 0 0 10px;
                        vertical-align: middle;
                    }
                    span {
                        display: inline-block;
                        height: 100%;
                        line-height: 60px;
                        margin-left: 15px;
                        font-size: 18px;
                        // margin: 20px 0 0 15px;
                        vertical-align: middle;
                    }
                }
                .txt {
                    color: #fff;
                }
            }
            .logo-width {
                width: 200px;
            }
            .logo-collapse-width {
                width: 60px;
            }
            .tools {
                padding: 0px 23px;
                // width: 14px;
                height: 60px;
                line-height: 60px;
                cursor: pointer;
            }
        }
        .main {
            display: flex;
            position: absolute;
            top: 60px;
            bottom: 0px;
            overflow: hidden;
            .h-full {
                height: 100%;
            }
            aside {
                flex: 0 0 230px;
                width: 230px;
                .el-menu {
                    height: 100%;
                }
                .collapsed {
                    width: 60px;
                    .item {
                        position: relative;
                    }
                    .submenu {
                        position: absolute;
                        top: 0px;
                        left: 60px;
                        z-index: 99999;
                        height: auto;
                        display: none;
                        box-shadow: 5px 5px 10px #ddd;
                    }
                }
            }
            .menu-collapsed {
                flex: 0 0 60px;
                width: 60px;
            }
            .menu-expanded {
                flex: 0 0 200px;
                width: 200px;
            }
            .content-container {
                flex: 1;
                width: 80%;
                overflow-y: auto;
                overflow-x: hidden;
                // position: relative;
                .breadcrumb-container {
                    .title {
                        width: 200px;
                        float: left;
                        color: #475669;
                    }
                    .breadcrumb-inner {
                        float: right;
                    }
                }
                .content-wrapper {
                    background-color: #fff;
                    box-sizing: border-box;
                    // position: relative;
                }
            }
        }
    }

    .popover-item {
        padding: 10px;
        border-bottom: 1px #eee solid;
    }

    .popover-item > div > p {
        margin: 0;
        line-height: 18px;
    }

    .popover-title {
        // color: #409eff;
        @include font_color("color");
        padding-bottom: 8px;
    }

    .popover-type {
        color: #aaa;
        font-size: 8px;
        float: right;
    }

    .popover-button {
        font-weight: 900;
        padding: 10px;
        text-align: center;
        cursor: pointer;
    }

    .isRead {
        color: #999 !important;
    }
    .bosx {
        width: 110px;
        display: inline-block;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    }
</style>