<script>
import {mapMutations, mapState} from "vuex";
import qs from 'query-string'

export default {
  name: "AppDutyInfo",
  appName: "值班信息",
  data() {
    return {
      list: [],
      show: false,
      columns: [
        {label: '值班人员', prop: 'dutyUserName'},
        {label: '开始时间', prop: 'dutyStartTime'},
        {label: '结束时间', prop: 'dutyEndTime'},
      ]
    }
  },
  computed: {
    ...mapState(['user']),
  },
  onShow() {
    document.title = '值班信息'
    if (this.user.token) {
      this.getList()
    } else if (this.$route.query.code) {
      this.getToken().then(this.getList)
    } else this.getCode().then(this.getToken).then(this.getList)
  },
  methods: {
    ...mapMutations(['setToken']),
    getCode() {
      /**
       * 构建oauth2链接获取code
       */
      const oauth2Weixin = params => {
        const redirect = qs.parseUrl(location.href)
        delete redirect.query.code
        delete redirect.query.state
        return qs.stringifyUrl({
          url: "https://open.weixin.qq.com/connect/oauth2/authorize",
          query: {
            response_type: 'code',
            redirect_uri: qs.stringifyUrl(redirect),
            ...params
          },
          fragmentIdentifier: "wechat_redirect"
        })
      }
      const oauthURL = oauth2Weixin({
        appid: "ww596787bb70f08288",
        agentid: "1000211",
        scope: "snsapi_privateinfo"
      })
      location.replace(oauthURL)
    },
    getToken() {
      const {code} = this.$route.query
      return this.$http.post("/node/wxtest/token", null, {withoutToken: 1, params: {code}}).then(res => {
        if (res?.data) {
          return this.setToken(res.data.data)
        } else if (res?.err?.errcode == 40029) {
          this.getCode().then(this.getToken).then(this.getList)
        }
      })
    },
    getList() {
      this.$http.post('/node/duty/list').then((res) => {
        if (res?.data) {
          this.list = res.data.records
        }
      })
    },
  },
}

</script>

<template>
  <section class="AppDutyInfo">
    <div v-text="user.token"/>
    <div class="select" @click="show=true">艾贤凌
      <u-icon name="arrow-down" color="#999" size="24"/>
    </div>
    <u-table>
      <u-tr>
        <u-th width="33%" v-for="column in columns" :key="column.prop">{{ column.label }}</u-th>
      </u-tr>
      <u-tr v-for="(row, i) in list" :key="i">
        <u-th width="33%" v-for="column in columns" :key="column.prop">{{ row[column.prop] }}</u-th>
      </u-tr>
    </u-table>
  </section>
</template>

<style scoped lang="scss">
.AppDutyInfo {
  padding: 0 16px;

  .select {
    text-align: right;
    padding: 32px 0;
  }
}
</style>
