<template>
  <div class="app-container">
    <el-card shadow="never" style="min-height:85vh;">
      <el-tabs v-model="activeTab" v-loading="loading" tab-position="left">
        <el-tab-pane :label="$t('ec.user.basicInfo')" name="1">
          <div style="display: flex;width: 100%">
            <img
              :src="sysrUser.avatar ? sysrUser.avatar : require('@/assets/img/avatar.png')"
              style="width: 100px;height:100px;margin-left: 20px;cursor: pointer;"
            >
            <el-form label-width="120px" label-suffix=":" style="float:right;width:100%;">
              <el-row>
                <el-col :span="12">
                  <el-form-item :label="$t('ec.user.realName')">
                    <template v-if="realNameEdit">
                      <el-input v-model="sysrUser.realName" style="width: auto;" />
                      <el-button
                        type="primary"
                        size="mini"
                        style="margin-left:10px;"
                        @click="updatePartInfo({realName: sysrUser.realName})"
                      >
                        {{ $t('ec.message.confirm') }}
                      </el-button>
                      <el-button size="mini" @click="realNameEdit=false">{{ $t('ec.message.cancel') }}</el-button>
                    </template>
                    <span v-else>
                      {{ sysrUser.realName }}
                      <i class="fa fa-edit icon" @click="realNameEdit=true" />
                    </span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('ec.user.userName')">
                    {{ sysrUser.username }}
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item :label="$t('ec.user.sex')">
                    <ec-radio-group v-model="sysrUser.sex" dict-type="sex" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('ec.user.birthday')">
                    {{ sysrUser.birthday ? sysrUser.birthday.substring(0,10) : '' }}
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item :label="$t('ec.user.position')">
                    {{ sysrUser.position }}
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('ec.user.insider')">
                    {{ sysrUser.insider ? $t('ec.table.yes') : $t('ec.table.no') }}
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row v-if="showWechat">
                <el-col :span="12">
                  <el-form-item>
                    <span slot="label"><i class="fa fa-wechat" />:</span>
                    <template v-if="wechatEdit">
                      {{ wechatAccount }}
                      <el-button class="bind" size="mini" icon="fa fa-link" @click="unbindWechat">解绑</el-button>
                    </template>
                    <span v-else>
                      未绑定
                      <el-button class="bind" size="mini" icon="fa fa-link" @click="bindWechat">绑定</el-button>
                    </span>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
          <el-divider />
          <div style="margin-top: 20px">
            <el-form label-suffix=":" label-width="120px">
              <el-row v-if="enableTenant">
                <el-col :span="12">
                  <el-form-item :label="$t('ec.user.tenant')">
                    <ec-tenant :value="sysrUser.tenantId" readonly />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="$t('ec.user.org')">
                    {{ sysrUser.orgName }}
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item :label="$t('ec.user.ustatus')">
                    <ec-radio-group
                      v-model="sysrUser.ustatus"
                      :ec-data="[{ value: 0, label: $t('ec.user.ustatusInit') }, { value: 1, label: $t('ec.user.ustatusNormal') }, { value:2, label: $t('ec.user.ustatusFrozen') }]"
                      readonly
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12" v-if="showWechat">
                  <el-form-item :label="$t('ec.user.wxBind')">
                    {{ sysrUser.weixinBind ? $t('ec.table.yes') : $t('ec.table.no') }}
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item :label="$t('ec.user.accessibleApp')">
                <template v-for="item in accessibleAppList">
                  <el-tag v-if="sysrUser.accessibleAppIds.indexOf(item.appId) > -1" :key="item.appId" style="margin-right: 4px">
                    {{ item.appName }}
                  </el-tag>
                </template>
              </el-form-item>
              <el-form-item :label="$t('ec.user.role')">
                <template v-for="item in roleList">
                  <el-tag v-if="sysrUser.roleIds.indexOf(item.id) > -1" :key="item.id" style="margin-right: 4px" type="success">
                    {{ item.roleName }}
                  </el-tag>
                </template>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
        <el-tab-pane :label="$t('ec.user.contactDetails')" name="2">
          <el-form label-width="120px" label-suffix=":">
            <el-form-item :label="$t('ec.sms.phone')">
              {{ sysrUser.phone }}
              <i
                :class="sysrUser.phone && sysrUser.phoneValid ? validRes.valid.icon : validRes.invalid.icon "
                :style="sysrUser.phone && sysrUser.phoneValid ? validRes.valid.style : validRes.invalid.style"
              />
              <span>{{ sysrUser.phone && sysrUser.phoneValid ? $t('ec.user.verified') : $t('ec.user.unverified') }}</span>
              <i class="fa fa-edit icon" @click="phoneEdit=true" />
            </el-form-item>
            <el-form-item :label="$t('ec.email.address')">
              {{ sysrUser.email || '-' }}
              <i
                :class="sysrUser.email && sysrUser.mailValid ? validRes.valid.icon : validRes.invalid.icon "
                :style="sysrUser.email && sysrUser.mailValid ? validRes.valid.style : validRes.invalid.style"
              />
              <span>{{ sysrUser.email && sysrUser.mailValid ? $t('ec.user.verified') : $t('ec.user.unverified') }}</span>
              <i class="fa fa-edit icon" @click="emailEdit=true" />
            </el-form-item>
            <el-form-item :label="$t('ec.user.address')">
              <template v-if="addressEdit">
                <el-input v-model="sysrUser.address" style="width: auto;" />
                <el-button
                  type="primary"
                  size="mini"
                  style="margin-left:10px;"
                  @click="updatePartInfo({address: sysrUser.address})"
                >
                  {{ $t('ec.message.confirm') }}
                </el-button>
                <el-button size="mini" @click="addressEdit=false">{{ $t('ec.message.cancel') }}</el-button>
              </template>
              <span v-else>
                {{ sysrUser.address }}
                <i class="fa fa-edit icon" @click="addressEdit=true" />
              </span>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane
          v-if="showChangePwd"
          :label="$t('ec.navbar.changePwd')"
          name="3"
        >
          <el-form ref="pwdForm" :model="userForm" label-width="120px">
            <el-form-item
              :label="$t('ec.login.pwd.old')"
              prop="password"
              :rules="[{ required: true, message: $t('ec.login.pwd.oldEmpty'), trigger: 'blur' }]"
            >
              <el-input v-model="userForm.password" type="password" autocomplete="off" />
            </el-form-item>
            <el-form-item
              :label="$t('ec.login.pwd.new')"
              prop="loginPwd"
              :rules="[
                { required: true, message: $t('ec.login.pwd.newEmpty'), trigger: 'blur' },
                { validator: validateNewPassword, trigger: 'blur' }
              ]"
            >
              <el-input v-model="userForm.loginPwd" type="password" autocomplete="off" />
            </el-form-item>
            <el-form-item
              :label="$t('ec.login.pwd.confirm')"
              prop="confirmPassword"
              :rules="[
                { required: true, message: $t('ec.login.pwd.confirmEmpty'), trigger: 'blur' },
                { validator: validateConfirmPassword, trigger: 'blur' }
              ]"
            >
              <el-input v-model="userForm.confirmPassword" type="password" autocomplete="off" />
            </el-form-item>
          </el-form>
          <el-button type="primary" style="margin-left: 120px" @click="changePwd">{{ $t('ec.message.confirm') }}</el-button>
        </el-tab-pane>
        <el-tab-pane :label="$t('ec.user.myLog')" name="4">
          <el-tabs style="margin-left: 10px">
            <el-tab-pane v-loading="loginStatLoading" :label="$t('ec.user.loginTrend')">
              <aside style="margin: 10px 0">
                <div>
                  <span>{{ $t('ec.user.recentLoginDesc', {days: $moment(loginStatParams.searchDate[1]).diff($moment(loginStatParams.searchDate[0]), 'days') + 1, loginDays: loginStat.allCount, lastLoginDate: loginStat.yesterday}) }}</span>
                  <!--                  <span>近{{ $moment(loginStatParams.searchDate[1]).diff($moment(loginStatParams.searchDate[0]), 'days') + 1 }}天内有{{ loginStat.allCount }}天具有登录行为，最后一次登录时间为{{ loginStat.yesterday }}</span>-->
                </div>
              </aside>

              <div>
                <el-checkbox v-model="loginStatParams.filterWorkDay" style="margin-right: 20px" @change="loadLoginStat">
                  {{ $t('ec.dashboard.filterWeekend') }}
                </el-checkbox>
                <el-date-picker
                  v-model="loginStatParams.searchDate"
                  type="daterange"
                  align="left"
                  unlink-panels
                  :range-separator="$t('ec.date.rangeSeparator')"
                  :start-placeholder="$t('ec.date.startDate')"
                  :end-placeholder="$t('ec.date.endDate')"
                  :clearable="false"
                  :picker-options="pickerOptions"
                  @change="loadLoginStat"
                />
              </div>

              <login-line-chart v-if="activeTab==='4'" ref="loginLineChart" :total-name="$t('ec.user.loginPv')" style="width: 100%" height="400px" />

            </el-tab-pane>

            <el-tab-pane :label="$t('ec.user.visitHistory')">
              <div style="margin-top: 10px">
                <el-date-picker
                  v-model="visitStatSearchDate"
                  type="daterange"
                  align="left"
                  unlink-panels
                  :range-separator="$t('ec.date.rangeSeparator')"
                  :start-placeholder="$t('ec.date.startDate')"
                  :end-placeholder="$t('ec.date.endDate')"
                  :clearable="false"
                  :picker-options="pickerOptions"
                  @change="getVisitStat"
                />
              </div>
              <div v-infinite-scroll="loadVisitStat" class="infinite-scroll-div" style="height: 600px">
                <el-timeline style="padding-left: 0">
                  <el-timeline-item
                    v-for="(value, key) in visitStat"
                    :key="key"
                    :timestamp="key"
                    placement="top"
                    color="#0088fe"
                  >
                    <el-card>
                      <p v-for="(item, index) in value" :key="index" style="margin: 5px 0 5px">
                        <label style="margin-right: 30px;text-align: right;font-weight: normal;display: inline-block;">
                          {{ item.createDate.substring(11) }}
                        </label>
                        <span>{{ $t('ec.user.visitDetail', {appName: item.appName, module: item.name}) }}</span>
                        <!--                        <span>使用了【{{ item.appName }}】系统的【{{ item.name }}】功能</span>-->
                      </p>
                    </el-card>
                  </el-timeline-item>
                </el-timeline>
              </div>
            </el-tab-pane>

            <el-tab-pane :label="$t('ec.user.infoUpdateHistory')">
              <div style="margin-top: 10px">
                <el-date-picker
                  v-model="operationSearchDate"
                  type="daterange"
                  align="left"
                  unlink-panels
                  :range-separator="$t('ec.date.rangeSeparator')"
                  :start-placeholder="$t('ec.date.startDate')"
                  :end-placeholder="$t('ec.date.endDate')"
                  :clearable="false"
                  :picker-options="pickerOptions"
                  @change="getOperation"
                />
              </div>
              <div v-infinite-scroll="loadOperation" class="infinite-scroll-div">
                <el-timeline style="padding-left: 0">
                  <el-timeline-item
                    v-for="(value, key) in operation"
                    :key="key"
                    :timestamp="key"
                    placement="top"
                    color="#0088fe"
                  >
                    <el-card>
                      <p v-for="(item, index) in value" :key="index" style="margin: 5px 0 5px">
                        <label style="margin-right: 30px;text-align: right;font-weight: normal;display: inline-block;">
                          {{ item.optTime.substring(11) }}
                        </label>
                        <span>{{ item.realName }}</span>
                        <span style="margin-left: 20px;">{{ item.description }}</span>
                      </p>
                    </el-card>
                  </el-timeline-item>
                </el-timeline>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-tab-pane>
      </el-tabs>

      <el-dialog :title="$t('ec.user.verifyPhone')" :visible.sync="phoneEdit">
        <el-form ref="phoneForm" :model="userForm" label-width="130px">
          <el-form-item
            :label="$t('ec.sms.phone')"
            prop="phone"
            :rules="[
              { required: true, message: $t('ec.login.phoneEmpty'), trigger: 'blur'},
              { validator: validator.mobilePhoneNumber, trigger: 'blur' }
            ]"
          >
            <el-input v-model="userForm.phone" autocomplete="off">
              <el-button slot="append" type="primary" :disabled="disabled=!phone.show" @click="sendPhoneCode()">
                <span v-show="phone.show">{{ $t('ec.login.sendCode') }}</span>
                <span v-show="!phone.show" class="count">{{ phone.count }} s</span>
              </el-button>
            </el-input>
          </el-form-item>
          <el-form-item :label="$t('ec.login.code')">
            <el-input v-model="userForm.phoneCode" autocomplete="off" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="phoneEdit = false">{{ $t('ec.table.cancel') }}</el-button>
          <el-button type="primary" @click="verifyPhone()">{{ $t('ec.table.confirm') }}</el-button>
        </div>
      </el-dialog>

      <el-dialog :title="$t('ec.user.verifyEmail')" :visible.sync="emailEdit">
        <el-form ref="emailForm" :model="userForm" label-width="120px">
          <el-form-item
            :label="$t('ec.email.address')"
            prop="email"
            :rules="[
              { required: true, message: $t('ec.email.empty'), trigger: 'blur'},
              { validator: validator.email, trigger: 'blur' }
            ]"
          >
            <el-input v-model="userForm.email" autocomplete="off" type="text">
              <el-button slot="append" type="primary" :disabled="disabled=!email.show" @click="sendEmailCode()">
                <span v-show="email.show">{{ $t('ec.login.sendCode') }}</span>
                <span v-show="!email.show" class="count">{{ email.count }} s</span>
              </el-button>
            </el-input>
          </el-form-item>
          <el-form-item :label="$t('ec.login.code')">
            <el-input v-model="userForm.emailCode" autocomplete="off" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="emailEdit = false">{{ $t('ec.table.cancel') }}</el-button>
          <el-button type="primary" @click="validateEmail()">{{ $t('ec.table.confirm') }}</el-button>
        </div>
      </el-dialog>

    </el-card>
    <wechat-code ref="wechatCode" @close="getData" />
  </div>
</template>

<script>
import validators from 'ecip-web/utils/validators'
import config from '@/settings'
import { getById, checkAccount, updatePartInfo, changePwd,
  sendSmsCode, sendEmailCode, validatePhone, validateEmail, unbindWechat } from 'ecip-web/api/vue/user/sysrUserApi'
import { findTenantAccessApps } from 'ecip-web/api/vue/app/sysrRegisterAppApi'
import { findRolesByAppIds } from 'ecip-web/api/vue/role/sysrRoleApi'
import { userLoginStat } from 'ecip-web/api/dashboard'
import LoginLineChart from 'ecip-web/views/dashboard/admin/components/LoginLineChart'
import { getUserData as getVisitStat } from 'ecip-web/api/web/stat/visit/ecipVisitStatApi'
import { getData as getOperation } from 'ecip-web/api/vue/log/oprationLogApi'
import WechatCode from './components/wechatCode'

const showChangePwd = window._CONFIG['changePwd']
const showWechat = window._CONFIG['showWechat']
const enableTenant = window._CONFIG['enableTenant']

export default {
  name: 'ModulesPersonalView',
  components: { LoginLineChart, WechatCode },
  mixins: [validators],
  data() {
    return {
      enableTenant: typeof enableTenant === undefined ? true : window._CONFIG['enableTenant'],
      showChangePwd: typeof showChangePwd !== 'undefined' ? showChangePwd : true,
      showWechat: typeof showWechat !== 'undefined' ? showWechat : true,
      activeTab: '1',
      loading: true,
      realNameEdit: false,
      wechatEdit: false,
      phoneEdit: false,
      emailEdit: false,
      addressEdit: false,
      sysrUser: {
        id: this.$store.getters.userInfo.id
      },
      accessibleAppList: [],
      roleList: [],
      userForm: {
        phone: '',
        phoneCode: '',
        email: '',
        emailCode: '',
        password: '',
        loginPwd: '',
        confirmPassword: ''
      },
      phone: {
        show: true,
        count: '',
        timer: null
      },
      email: {
        show: true,
        count: '',
        timer: null
      },
      validRes: {
        valid: {
          icon: 'el-icon-circle-check',
          style: {
            marginLeft: '8px',
            color: '#6cff50'
          }
        },
        invalid: {
          icon: 'el-icon-warning-outline',
          style: {
            marginLeft: '8px',
            color: '#ff621a'
          }
        }
      },
      pickerOptions: {
        shortcuts: [{
          text: this.$t('ec.date.today'),
          onClick(picker) {
            const start = new Date(new Date(new Date().toLocaleDateString()).getTime()) // 00:00:00
            const end = new Date(start.getTime() + 24 * 60 * 60 * 1000 - 1) // 23:59:59
            picker.$emit('pick', [start, end])
          }
        }, {
          text: this.$t('ec.date.past7Days'),
          onClick(picker) {
            const end = new Date()
            const start = new Date(end.getTime() - 3600 * 1000 * 24 * 6)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: this.$t('ec.date.past30Days'),
          onClick(picker) {
            const end = new Date()
            const start = new Date(end.getTime() - 3600 * 1000 * 24 * 29)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: this.$t('ec.date.past90Days'),
          onClick(picker) {
            const end = new Date()
            const start = new Date(end.getTime() - 3600 * 1000 * 24 * 89)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      loginStatLoading: true,
      loginStatParams: {
        filterWorkDay: false,
        searchDate: []
      },
      loginStat: {
        date: [],
        pc: [],
        app: [],
        total: [],
        yesterday: '',
        allCount: 0
      },
      visitStatCurPage: 1,
      visitStatSearchDate: [],
      visitStatEnd: false,
      visitStat: {},
      operationCurPage: 1,
      operationSearchDate: [],
      operationEnd: false,
      operation: {}
    }
  },
  watch: {
    activeTab(val) {
      if (val === '4') {
        this.loadLoginStat()
        this.getVisitStat()
        this.getOperation()
      }
    }
  },
  async created() {
    await this.getData()
    this.initDate()
  },
  methods: {
    initDate() {
      const end = new Date()
      const start = this.$moment().subtract(29, 'days').toDate()
      this.loginStatParams.searchDate = [start, end]
      this.visitStatSearchDate = [start, end]
      this.operationSearchDate = [start, end]
    },
    async getData() {
      const { data } = await getById(this.$store.getters.userInfo.id)
      this.sysrUser = data.sysrUser
      this.wechatAccount = data.wechatAccount
      this.wechatEdit = this.sysrUser.weixinBind === true
      this.loading = false
      await this.findTenantAccessApps(this.sysrUser.tenantId)
      await this.findRolesByAppIds(this.sysrUser.tenantId, this.sysrUser.accessibleAppIds)
    },
    async validateCode(rule, value, callback) { //  新增子节点不校验、编辑子节点不校验
      const { data } = await checkAccount(this.sysrUser.id, value)
      if (data.valid) {
        callback()
      } else {
        callback(new Error(this.$t('ec.table.exist')))
      }
    },
    unbindWechat() {
      this.$confirm('解绑后没法接收到微信公众号消息，也没法扫码登录，是否继续解绑微信？', this.$t('ec.message.prompt'), {
        confirmButtonText: this.$t('ec.message.confirm'),
        cancelButtonText: this.$t('ec.message.cancel'),
        type: 'warning'
      }).then(async() => {
        try {
          this.loading = true
          await unbindWechat()
          await this.getData()
          this.$notify.success('解绑成功')
        } finally {
          this.loading = false
        }
      })
    },
    async bindWechat() {
      try {
        this.loading = true
        this.$refs.wechatCode.init()
      } finally {
        this.loading = false
      }
    },
    async findTenantAccessApps(tenantId) {
      const { data } = await findTenantAccessApps(tenantId)
      this.accessibleAppList = data
    },
    async findRolesByAppIds(tenantId, appIds) {
      const { data } = await findRolesByAppIds(tenantId, appIds)
      this.roleList = data
    },
    async updatePartInfo(propObj) {
      try {
        this.loading = true
        await updatePartInfo(this.sysrUser.id, propObj)
        if (propObj.realName) {
          this.$notify.success(this.$t('ec.message.saveSuccess'))
          setTimeout(() => {
            location.reload()
          }, 1000)
        } else {
          this.$notify.success(this.$t('ec.message.saveSuccess'))
        }
      } finally {
        this.loading = false
      }
    },
    sendPhoneCode() {
      this.$refs.phoneForm.validate((valid) => {
        if (valid) {
          sendSmsCode(this.userForm.phone).then(res => {
            if (res.code === 200) {
              this.$notify.success({ title: this.$t('ec.message.success'), message: this.$t('ec.login.sendSuccess') })
              this.setPhoneCount()
            }
          }).catch(error => {
            console.log('error', error)
          })
        }
      })
    },
    sendEmailCode() {
      this.$refs.emailForm.validate((valid) => {
        if (valid) {
          sendEmailCode(this.userForm.email).then(res => {
            if (res.code === 200) {
              this.$notify.success({ title: this.$t('ec.message.success'), message: this.$t('ec.login.sendSuccess') })
              this.setEmailCount()
            }
          }).catch(error => {
            console.log('error', error)
          })
        }
      })
    },
    verifyPhone() {
      validatePhone(this.userForm.phone, this.userForm.phoneCode).then(res => {
        if (res.code === 200) {
          this.$notify.success({ title: this.$t('ec.message.success'), message: this.$t('ec.user.verifyPhoneSuccess') })
          clearInterval(this.phone.timer)
          this.phone = { count: '', show: true, timer: null }
          this.userForm.phone = ''
          this.userForm.phoneCode = ''
          this.getData()
          this.phoneEdit = false
        } else {
          this.$notify.error({ title: this.$t('ec.message.error'), message: this.$t('ec.user.verifyPhoneFail') })
        }
      }).catch(error => {
        console.log('error', error)
      })
    },
    validateEmail() {
      validateEmail(this.userForm.email, this.userForm.emailCode).then(res => {
        if (res.code === 200) {
          this.$notify.success({ title: this.$t('ec.message.success'), message: this.$t('ec.user.verifyEmailSuccess') })
          clearInterval(this.email.timer)
          this.email = { count: '', show: true, timer: null }
          this.userForm.email = ''
          this.userForm.emailCode = ''
          this.getData()
          this.emailEdit = false
        } else {
          this.$notify.error({ title: this.$t('ec.message.error'), message: this.$t('ec.user.verifyEmailFail') })
        }
      }).catch(error => {
        console.log('error', error)
      })
    },
    setPhoneCount() {
      const TIME_COUNT = 60
      if (!this.phone.timer) {
        this.phone.count = TIME_COUNT
        this.phone.show = false
        this.phone.timer = setInterval(() => {
          if (this.phone.count > 0 && this.phone.count <= TIME_COUNT) {
            this.phone.count--
          } else {
            this.phone.show = true
            clearInterval(this.phone.timer)
            this.phone.timer = null
          }
        }, 1000)
      }
    },
    setEmailCount() {
      const TIME_COUNT = 60
      if (!this.email.timer) {
        this.email.count = TIME_COUNT
        this.email.show = false
        this.email.timer = setInterval(() => {
          if (this.email.count > 0 && this.email.count <= TIME_COUNT) {
            this.email.count--
          } else {
            this.email.show = true
            clearInterval(this.email.timer)
            this.email.timer = null
          }
        }, 1000)
      }
    },
    validateNewPassword(rule, value, callback) {
      if (config.password && config.password.reg) {
        if (config.password.same === false && this.sysrUser.username === value) {
          callback(new Error(this.$t('ec.login.pwd.sameError')))
          return
        }
        if (!config.password.reg.test(value)) {
          callback(new Error(this.$t(config.password.msg) || this.$t('ec.login.pwd.regError') + config.password.reg))
          return
        }
      } else {
        if (value && value.length > 0 && value.length < 6) {
          callback(new Error(this.$t('ec.login.pwd.lengthError')))
          return
        }
      }
      callback()
    },
    validateConfirmPassword(rule, value, callback) {
      if (this.userForm.loginPwd !== value) {
        callback(new Error(this.$t('ec.login.pwd.confirmError')))
      } else {
        callback()
      }
    },
    changePwd() {
      this.$refs.pwdForm.validate((valid) => {
        if (valid) {
          this.loading = true
          changePwd({ oldPassword: this.userForm.password, loginPwd: this.userForm.loginPwd }).then(res => {
            if (res.code === 200) {
              this.$notify.success(this.$t('ec.login.pwd.changeSuccess'))
              this.loading = false
              this.$store.dispatch('user/logout')
              this.$router.push(`/login?redirect=${this.$route.fullPath}`)
            }
          }).catch(error => {
            console.log('error', error)
          }).finally(() => {
            this.loading = false
          })
        }
      })
    },
    loadLoginStat() {
      const start = this.$moment(this.loginStatParams.searchDate[0]).format('YYYY-MM-DD')
      const end = this.$moment(this.loginStatParams.searchDate[1]).format('YYYY-MM-DD')
      this.loginStatLoading = true
      userLoginStat({
        start: start,
        end: end,
        filterWorkDay: this.loginStatParams.filterWorkDay,
        userId: this.sysrUser.id
      }).then(res => {
        this.loginStatLoading = false
        this.loginStat = res.data
        this.$refs.loginLineChart.setData(res.data)
      })
    },
    loadVisitStat() {
      if (this.visitStatEnd) {
        return
      }
      this.visitStatCurPage += 1
      this.getVisitStat()
    },
    getVisitStat() {
      const start = this.$moment(this.visitStatSearchDate[0]).format('YYYY-MM-DD')
      const end = this.$moment(this.visitStatSearchDate[1]).format('YYYY-MM-DD')
      getVisitStat({ size: 20, current: this.visitStatCurPage, userId: this.sysrUser.id, start, end }).then(res => {
        this.visitStatEnd = !res.data.hasNext
        res.data.records.forEach(item => {
          const date = item.createDate.substring(0, 10)
          if (!(date in this.visitStat)) {
            this.$set(this.visitStat, date, [])
          }
          this.visitStat[date].push(item)
        })
      })
    },
    loadOperation() {
      if (this.operationEnd) {
        return
      }
      this.operationCurPage += 1
      this.getOperation()
    },
    getOperation() {
      const params = {
        size: 20,
        current: this.operationCurPage,
        field: 'createDate',
        order: 'desc'
      }
      const requestBody = {
        beginOptTime: this.$moment(this.operationSearchDate[0]).format('YYYY-MM-DD HH:mm:ss'),
        endOptTime: this.$moment(this.operationSearchDate[1]).endOf('day').format('YYYY-MM-DD HH:mm:ss'),
        recordId: this.sysrUser.id
      }
      getOperation(params, requestBody).then(res => {
        this.operationEnd = !res.data.hasNext
        res.data.records.forEach(item => {
          const date = item.optTime.substring(0, 10)
          if (!(date in this.operation)) {
            this.$set(this.operation, date, [])
          }
          this.operation[date].push(item)
        })
      })
    }
  }
}
</script>

<style scoped>
.icon {
  margin-left:10px;
  cursor:pointer;
}
.bind {
  margin-left:10px;
}
.infinite-scroll-div {
  overflow: auto;
  height: 65vh;
  margin-top: 10px;
  padding: 20px
}
::v-deep .el-timeline-item__timestamp.is-top{
  color: #303133;
  font-size: 18px;
}
</style>
