<template>
  <div>
    <div class="queryKeyWord">
        <p style="margin-left: 30px;">ID：</p>
        <Input class="" clearable v-model="userId" style="width: 60px" />

      <p style="margin-left: 30px;">{{$t('account')}}：</p>
      <!-- <Input :value.sync="keyWord" placeholder="请输入要搜索的账号" style="width: 300px"></Input> -->
      <Input class="" clearable v-model="keyWord" :placeholder="$t('search_account')" style="width: 200px" />
      <p class="queryKeyWord__level__p">{{$t('level')}}：</p>
      <Select v-model="memberLevel" clearable style="width:200px" class="queryKeyWord__input" @on-change="selectChange">
        <Option v-for="item in memberLevelNameMap" :value="item.level" :key="item.level">{{ item.name }}</Option>
      </Select>
      <i-button type="primary" @click="search">{{$t('search')}}</i-button>
    </div>
    <Table class="ListTab" border :loading="disabledTab" :columns="columnsList" :data="dataList">
      <template slot-scope="{ row }" slot="username">
          <router-link :to="{name:'lookOverUser',query:{id:row.id}}"><p>{{ row.username }}</p></router-link>
      </template>
      <template slot-scope="{ row }" slot="member_level">
          <span v-if="row.member_level === 255" style="color:red"><strong>{{$t('super_admin')}}</strong></span>
        <span v-else-if="row.member_level === 200" style="color:red">{{$t('admin')}}</span>
        <span v-else-if="row.member_level === 101">{{$t('company_dev')}}</span>
        <span v-else-if="row.member_level === 100">{{$t('personal_dev')}}</span>
        <span v-else-if="row.member_level === 0">{{$t('common_member')}}</span>
      </template>
      <template slot-scope="{ row,index }" slot="operation" class="operation">
        <router-link :to="{name:'compileUser',query:{id:row.id}}">
          <Button type="primary" size="small" class="operation__btn" style="">{{$t('edit')}}</Button>
        </router-link>
        <Button type="success" size="small" class="operation__btn" style="" v-if="row.member_status === 0" @click="changeMemberStatus(index)">{{$t('enable')}}</Button>
        <Button type="warning" size="small" class="operation__btn" style="" v-else @click="changeMemberStatus(index)" :disabled="row.member_level === 2 ? true : false">{{$t('disable')}}</Button>
        <Button class="ivu-btn ivu-btn-error ivu-btn-small operation__btn" type="text" size="small" :disabled="row.member_level === 2 ? true : false" @click="remove(index)">{{$t('delete')}}</Button>
        <Button type="info" class="operation__btn" size="small" @click="userLoginSimulate(row)">{{$t('userLoginSimulate')}}</Button>
        <Button type="info" class="operation__btn" size="small" @click="showUserVisitPath(row)">{{$t('userVisitPath')}}</Button>
      </template>
    </Table>
    <div class="pagination">
      <Page :total="total" show-elevator show-sizer @on-page-size-change='changeSize' @on-change='changePage'/>
    </div>
    <!-- 用户轨迹弹窗 -->
    <Modal v-model="userVisitPathModal" width="800" footer-hide @on-visible-change="closeVisitListModal"	>
    <div slot="header">{{$t('userVisitPath')}}：{{userVisitPathName}}</div>
      <div>
        {{$t('date')}}：<DatePicker type="date" style="width: 200px" @on-change="selectVisitDate"></DatePicker>
        <Button style="margin-left:10px" @click="getVisitPathList">{{$t('refresh')}}</Button>
      </div>
      <Table style="margin-top:10px" border :columns="columnsList_visitPath" :height="500" :data="dataList_visitPath">
        <template></template>
      </Table>
    </Modal>
  </div>
</template>

<script>
import { GetAllMembers, DelMember, AlterMemberStatus, GetAllMemberLevelList, SimulationLogin, GetUserVisitPath } from '@/api/user'
import { getToken } from '@/libs/util'
import Cookies from 'js-cookie'
export default {
  name: 'directive_page',
  data () {
    return {
      disabledTab: false, // 表格disable
      userId: '',
      keyWord: '', // 搜索的关键词
      total: 0,
      page: 1, // 分页
      perpage: 10,
      token: getToken(),
      columnsList: [
        {
          width: 100,
          title: this.$t('account_id'),
          key: 'id',
          align: 'center'
        },
        {
          title: this.$t('account'),
          key: 'username',
          align: 'center',
          slot: 'username'
        },
        {
          title: this.$t('name'),
          key: 'nickname',
          align: 'center'
        },
        {
          title: this.$t('tel'),
          key: 'mobile',
          align: 'center'
        },
        {
          title: this.$t('email'),
          key: 'email',
          align: 'center'
        },
        {
          title: this.$t('member_type'),
          key: 'member_level',
          align: 'center',
          slot: 'member_level'
        },
        {
          title: this.$t('sign_up_time'),
          key: 'register_time',
          align: 'center',
          width: 200
        },
        {
          title: this.$t('operation'),
          slot: 'operation',
          width: 200,
          align: 'center'
        }
      ], // 表头
      dataList: [], // 接受的数据
      memberLevel: '', // 等级
      memberLevelNameMap: [],
      userVisitPathModal: false, // 用户轨迹弹窗
      userVisitPathName: '',
      userVisitPathUid: '',
      request_day: '', // 用户轨迹最后日期
      columnsList_visitPath: [
        {
          width: 100,
          title: 'ID',
          key: 'id',
          align: 'center'
        },
        {
          title: this.$t('request_time'),
          key: 'request_time',
          align: 'center'
        },
        {
          title: 'API',
          key: 'service',
          align: 'center'
        }
      ],
      dataList_visitPath: []
    }
  },
  // 获取应用管理数据
  created () {
    this.getBerLevel()
    this.queryList()
  },
  methods: {
    search () {
      this.page = 1
      this.queryList()
    },
    // 获取用户类型
    getBerLevel () {
      const data = new FormData()
      data.append('access_token', this.token)
      GetAllMemberLevelList(data).then(res => {
        if (res.ret === 200) {
          this.memberLevelNameMap = res.data.list
        }
      })
    },
    // 查询列表
    queryList () {
      this.disabledTab = true
      // this.page = 1
      const formdata = new FormData()
      if (this.keyWord) {
        formdata.append('username', this.keyWord)
      }
      if (this.memberLevel || this.memberLevel === 0) {
        formdata.append('member_type', this.memberLevel)
      }
      if (this.userId) {
        formdata.append('user_id', this.userId)
      }
      formdata.append('page', this.page)
      formdata.append('perpage', this.perpage)
      formdata.append('access_token', this.token)
      GetAllMembers(formdata).then(res => {
        if (res.data.list.length) {
          this.dataList = res.data.list
        } else {
          this.dataList = []
        }
        this.total = res.data.total
        this.disabledTab = false
      })
    },
    changeSize (size) {
      this.perpage = size
      this.queryList()
    },
    changePage (page) {
      this.page = page
      this.queryList()
    },
    // 开启/禁用操作
    changeMemberStatus (index) {
      this.$Modal.confirm({
        title: this.$t('operation_confirm'),
        content: this.dataList[index].member_status === 0 ? this.$t('enable_this_account') : this.$t('disable_this_account'),
        onOk: () => {
          const formdata = new FormData()
          formdata.append('access_token', this.token)
          formdata.append('id', this.dataList[index].id)
          if (this.dataList[index].member_status) {
            formdata.append('type', 0)
          } else {
            formdata.append('type', 1)
          }
          AlterMemberStatus(formdata).then(res => {
            if (res.ret === 200 && res.data.is_success) {
              this.$Message.success(this.$t('successfully_altered'))
              this.queryList()
            } else {
              this.$Message.success(this.$t('alter_fail'))
            }
          })
        },
        onCancel: () => {
          this.$Message.info(this.$t('cancel'))
        }
      })
    },
    userLoginSimulate (row) {
      this.$Modal.confirm({
        title: `模拟登录${row.username}`,
        content:
        `<p style="color:red">注意1：模拟登录后，不要擅自修改客户的数据</p>
         <p style="color:red">注意2：使用完毕后，退出登录</p>`,
        onOk: () => {
          console.log('ok', row)
          const data = new FormData()
          data.append('access_token', this.token)
          data.append('uid', row.id)
          SimulationLogin(data).then(res => {
            // localStorage.setItem('p_token', 'maxLogo', res.data.logo)
            // let storeValue = {
            //   name: 'p_token',
            //   value: res.data.access_token,
            //   expires: (res.data.expire_at * 1000) - (new Date().getTime()),
            //   startTime: new Date().getTime()
            // }
            // localStorage.setItem('p_token', JSON.stringify(storeValue))
            Cookies.set('p_token', res.data.access_token, { expires: (res.data.expire_at * 1000) - (new Date().getTime()) })

            setTimeout(() => {
              window.open('/platform/')
            }, 1500)
          })
        },
        onCancel: () => {
          console.log('oh no')
        }
      })
    },
    showUserVisitPath (row) {
      this.userVisitPathName = row.username
      this.userVisitPathModal = true
      this.userVisitPathUid = row.id
      this.getVisitPathList()
    },
    getVisitPathList () {
      const data = new FormData()
      data.append('access_token', this.token)
      data.append('request_uid', this.userVisitPathUid)
      if (this.request_day) {
        data.append('request_day', this.request_day)
      }
      GetUserVisitPath(data).then(res => {
        this.dataList_visitPath = res.data.logs
      })
    },
    selectVisitDate (e) {
      this.request_day = e
    },
    closeVisitListModal () {
      if (!this.userVisitPathModal) {
        this.userVisitPathName = ''
        this.dataList_visitPath = []
      }
    },
    remove (index) {
      this.$Modal.confirm({
        title: this.$t('operation_confirm'),
        content: `<p>${this.$t('are_u_sure_delete_the_')}<span style="color:red">${this.dataList[index].username}</span>&nbsp;${this.$t('account')}</p>`,
        onOk: () => {
          const formdata = new FormData()
          formdata.append('access_token', this.token)
          formdata.append('id', this.dataList[index].id)
          DelMember(formdata).then(res => {
            if (res.ret === 200) {
              this.$Message.success(this.$t('update_successfully'))
              this.queryList()
            }
          })
        },
        onCancel: () => {
          this.$Message.info(this.$t('cancel'))
        }
      })
    },
    selectChange (val) {
      this.memberLevel = val
    }
  }
}
</script>

<style lang="scss" scoped>
.queryKeyWord{
  display: flex;
  align-items: center;
  height:72px;
  background:rgba(255,255,255,1);
  box-shadow:0px 0px 30px 0px rgba(0,0,0,0.05);
  border-radius:10px;
  margin-bottom: 20px;
  &__level{
    &__p{
      margin-left: 40px;
    }
  }
  &__input{
    margin-right: 40px;
  }
}
.ListTab{
  background: #fff;
  border-radius: 10px;
}
.pagination {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
}

.operation{
  &__btn{
    margin: 0 5px;
  }
}
</style>
