<template>
  <div class="my-native region-card" :data-language="language">
    <div class="card">
      <div class="title">{{ $t('pages.dashboard.userNavigation.title') }}</div>
      <div class="subtitle">{{ $t('pages.dashboard.userNavigation.recentVisits') }}</div>
      <div class="content">
        <el-row :gutter="10">
          <el-col v-for="(item, index) in dashboard.recentPreviews" :key="index" :md="4" :sm="8" :xs="12">
            <div
              @click="clickRecentPreviews(item)"
              @mouseleave="mouseoutRecentPreviews(item)"
              @mouseenter="mouseoverRecentPreviews(item)"
            >
              <div class="tag region-tag-color flex-c">
                <a
                  :href="item.type === 'CUSTOM' ? item.link : 'javascript:void(0);'"
                  :target="item.type === 'CUSTOM' ? '_blank' : ''"
                  style="width: 100%"
                  @click="clickCustomNavigations(item)"
                >
                  <div class="nowrap-ellipsis" style="width: 100%">
                    {{ item.name }}
                  </div>
                </a>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <div class="native-content">
        <div class="native-item">
          <div class="subtitle">{{ $t('pages.dashboard.userNavigation.customShortcuts') }}</div>
          <div class="content">
            <el-row :gutter="10">
              <el-col v-for="(item, index) in dashboard.customNavigations" :key="index" :md="4" :sm="8" :xs="12">
                <div
                  @mouseleave="mouseoutCustomNavigations(item)"
                  @mouseenter="mouseoverCustomNavigations(item)"
                >
                  <div class="tag region-tag-color flex-c">
                    <a :href="item.link" target="_blank" style="width: 100%" @click="clickCustomNavigations(item)">
                      <div class="nowrap-ellipsis" style="width: 100%">
                        {{ item.name }}
                      </div>
                    </a>
                    <i
                      v-if="mouseoveCustomNavigationId === item.id"
                      class="el-icon-error"
                      style="font-size: 18px;"
                      @click.stop="removeCustomNavigations(item)"
                    />
                  </div>
                </div>
              </el-col>
              <el-col :md="4" :sm="8" :xs="12">
                <el-popover v-model="customNavigationFormVisible" width="400" trigger="click">
                  <div class="add-native">
                    <div class="blockquote">{{ $t('pages.dashboard.userNavigation.protocolTip') }}</div>
                    <el-form ref="customNavigationForm" :model="customNavigationForm" :rules="customNavigationFormRules">
                      <el-form-item :label="$t('pages.dashboard.userNavigation.entryName')" prop="name">
                        <el-input
                          v-model="customNavigationForm.name"
                          :placeholder="$t('pages.dashboard.userNavigation.entryNamePlaceholder')"
                          minlength="1"
                          maxlength="30"
                          show-word-limit
                        />
                      </el-form-item>
                      <el-form-item :label="$t('pages.dashboard.userNavigation.entryLink')" prop="link">
                        <el-input
                          v-model="customNavigationForm.link"
                          :placeholder="$t('pages.dashboard.userNavigation.entryLinkPlaceholder')"
                          minlength="1"
                          maxlength="300"
                          show-word-limit
                        />
                      </el-form-item>
                      <el-form-item>
                        <el-button
                          type="primary"
                          :loading="customNavigationFormLoading"
                          :disabled="customNavigationFormLoading"
                          @click="onSubmitCustomNavigationForm"
                        >
                          {{ $t('pages.dashboard.userNavigation.add') }}
                        </el-button>
                      </el-form-item>
                    </el-form>
                  </div>
                  <div slot="reference">
                    <div class="tag region-tag-color flex-c">
                      <div class="nowrap-ellipsis">
                        <i class="el-icon-circle-plus-outline" style="margin: 0 3px; font-weight: bold;" />
                        <strong>{{ $t('pages.dashboard.userNavigation.addShortcut') }}</strong>
                      </div>
                    </div>
                  </div>
                </el-popover>
              </el-col>
            </el-row>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { addDashboardCustom, removeDashboardPreviews, removeDashboardCustom, addDashboardPreviews } from '@/api/ops-system'

export default {
  name: 'MyNavigation',
  data() {
    const checkLink = (rule, value, callback) => {
      if (!value) {
        return callback(new Error(this.$t('pages.dashboard.userNavigation.protocolValidation')))
      }

      if (value.startsWith('http://') || value.startsWith('https://')) {
        return callback()
      }
      return callback(new Error(this.$t('pages.dashboard.userNavigation.protocolValidation')))
    }

    return {
      addNativeTables: [
        { titleKey: 'pages.dashboard.userNavigation.searchAdd', component: 'DailyPurchase' },
        { titleKey: 'pages.dashboard.userNavigation.customAdd', component: 'MonthlyPurchase' }
      ],
      customNavigationFormVisible: false,
      customNavigationFormLoading: false,
      customNavigationForm: {
        id: '',
        type: 'CUSTOM',
        name: '',
        link: ''
      },
      customNavigationFormRules: {
        name: [{ required: true, message: this.$t('pages.dashboard.userNavigation.requiredField'), trigger: 'blur' }],
        link: [{ required: true, trigger: 'blur', validator: checkLink }]
      },
      mouseoveRecentSeletedId: '',
      mouseoveCustomNavigationId: ''
    }
  },
  computed: {
    ...mapGetters(['buttonPermissions', 'name', 'dashboard', 'language'])
  },
  watch: {
    language() {
      this.customNavigationFormRules = {
        name: [{ required: true, message: this.$t('pages.dashboard.userNavigation.requiredField'), trigger: 'blur' }],
        link: [{
          required: true,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (!value) {
              return callback(new Error(this.$t('pages.dashboard.userNavigation.protocolValidation')))
            }

            if (value.startsWith('http://') || value.startsWith('https://')) {
              return callback()
            }

            return callback(new Error(this.$t('pages.dashboard.userNavigation.protocolValidation')))
          }
        }]
      }
    }
  },
  methods: {
    loadDashboard() {
      this.$store.dispatch('user/getUserDashboard').catch(er => {
        console.error('loadDashboard', er)
      })
    },
    clickCustomNavigations(item) {
      if (item.type === 'CUSTOM') {
        addDashboardPreviews(item)
      }
    },
    clickRecentPreviews(item) {
      if (item.type === 'CUSTOM') {
        return
      }
      if (item.link) {
        this.$router.push(item.link)
      }
    },
    mouseoutCustomNavigations() {
      this.mouseoveCustomNavigationId = ''
    },
    mouseoverCustomNavigations(item) {
      this.mouseoveCustomNavigationId = item.id
    },
    removeCustomNavigations(item) {
      removeDashboardCustom(item.id).then(() => {
        this.$opsMessage.success()
        this.loadDashboard()
      }).catch(er => {
        console.error('removeCustomNavigations', er)
      })
    },
    mouseoutRecentPreviews() {
      this.mouseoveRecentSeletedId = ''
    },
    mouseoverRecentPreviews(item) {
      this.mouseoveRecentSeletedId = item.id
    },
    removeRecentPreviews(item) {
      removeDashboardPreviews(item.id).then(() => {
        this.$opsMessage.success()
        this.loadDashboard()
      }).catch(er => {
        console.error('removeRecentPreviews', er)
      })
    },
    onSubmitCustomNavigationForm() {
      this.$refs.customNavigationForm.validate((valid) => {
        if (!valid) {
          console.error('error submit!!')
          return false
        }
        this.customNavigationFormLoading = true
        addDashboardCustom(this.customNavigationForm).then(() => {
          this.$opsMessage.success()
          this.customNavigationFormLoading = false
          this.customNavigationFormVisible = false
          this.loadDashboard()
        }).catch(() => {
          this.customNavigationFormLoading = false
          this.customNavigationFormVisible = false
        })
      })
    }
  }
}
</script>

<style scoped lang="scss">
.my-native {
  .tag {
    width: 100%;
    height: 32px;
    line-height: 32px;
    padding: 0 12px;
    margin-bottom: 8px;
    overflow: hidden;
    border-radius: 2px;
    font-size: 12px;
    cursor: pointer;
    white-space: nowrap;
    text-decoration: none;
  }
}
</style>
