<template>
  <div class="white-box">
    <div class="filter-box">
      <!-- 功能搜索 -->
      <div class="filter-box">
        <filter-user :filter-types="filterTypes" @select-value="handleFilterUser"></filter-user>
      </div>
      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        @selection-change="handleSelectionChange"
      >
<!--        <el-table-column type="selection" width="55" />-->
        <el-table-column :label="$t('ad.country')" prop="id" align="center" :class-name="getSortClass('id')">
          <template slot-scope="{row}">
            <span>{{ row.COUNTRY_NAME }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('ad.adTitle')" prop="id" align="center" :class-name="getSortClass('id')">
          <template slot-scope="{row}">
            <span>{{ row.TITLE.value }}</span>
          </template>
        </el-table-column>
<!--        <el-table-column :label="$t('ad.adLocation')" prop="id" align="center" :class-name="getSortClass('id')">-->
<!--          <template :value="{allLocation}">-->
<!--            <span>{{ allLocation.LOCATION_NAME }}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column :label="$t('ad.type')" align="center"> <!-- 类型 -->
          <template slot-scope="{row}">
            <template>
              <div v-if="row.TYPE === '1'">
               {{ $t('ad.externalLinks') }}
              </div><!-- 链接 -->
              <div v-else-if="row.TYPE === '2'">
                {{ $t('ad.article') }}
              </div><!-- 文章 -->
            </template>
          </template>
        </el-table-column>
        <el-table-column :label="$t('ad.content')" prop="id" align="center" :class-name="getSortClass('id')">
          <template slot-scope="{row}">
            <div v-if="row.TYPE === '1'">
              <el-link type="primary" target="_blank" :href="getHref(row.CONTENT)">{{ row.CONTENT }}</el-link>
            </div><!-- 链接 -->
            <div v-else-if="row.TYPE === '2'">
              <router-link :to="`/article/detail/${row.CONTENT}`" target="_blank" style="cursor: pointer;">{{ getContent(row.CONTENT) }}</router-link>
            </div><!-- 文章 -->
          </template>
        </el-table-column>
        <el-table-column :label="$t('ad.sort')" prop="id" align="center" :class-name="getSortClass('id')">
          <template slot-scope="{row}">
            <el-input
              v-model="row.SORT"
              min="0"
              max="99"
              @change="handleChangeSort(row.ID, row.SORT)"
              @click.native.stop=""
            />
          </template>
        </el-table-column>
<!--        <el-table-column :label="$t('ad.creator')" prop="id" align="center" :class-name="getSortClass('id')">-->
<!--          <template slot-scope="{row}">-->
<!--            <span>{{ row.CREATE_ADMIN_NAME }}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column :label="$t('ad.createTime')" align="center">-->
<!--          <template slot-scope="{row}">-->
<!--            <span>{{ row.CREATED_AT | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column :label="$t('ad.modifiedBy')" prop="id" align="center" width="80" :class-name="getSortClass('id')">-->
<!--          <template slot-scope="{row}">-->
<!--            <span>{{ row.UPDATE_ADMIN_NAME }}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column :label="$t('ad.modifiedTime')" align="center">-->
<!--          <template slot-scope="{row}">-->
<!--            <span>{{ tool.formatDate(row.UPDATED_AT) }}</span>-->

<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column :label="$t('article.status')" align="center">
          <template slot-scope="{row}">
            <div v-if="row.STATUS.value === '1'">{{$t('article.show')}}</div>
            <div v-else>{{$t('article.hide')}}</div>
          </template>
        </el-table-column>

        <el-table-column :label="$t('ad.action')" align="center">
          <template slot-scope="{row}">
            <el-dropdown v-if="permission.hasPermission(`ad/ad-delete`) || permission.hasPermission(`ad/edit`)" size="small" trigger="click">
              <el-button type="primary" size="small" @click.stop="">
                {{ $t('ad.action') }}<i class="el-icon-arrow-down el-icon--right" />
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-if="permission.hasPermission(`ad/edit`)" command="edit" @click.native="handleEdit(row)">{{ $t('common.edit') }}</el-dropdown-item>
                <el-dropdown-item v-if="permission.hasPermission(`ad/ad-delete`)" command="delete" @click.native="handleDeleteOne(row)">{{ $t('common.delete') }}</el-dropdown-item>
                <el-dropdown-item v-if="permission.hasPermission(`ad/ad-hide`)" command="hide" @click.native="handleHideOne(row)">{{ $t('ad.hide') }}</el-dropdown-item>
                <el-dropdown-item v-if="permission.hasPermission(`ad/ad-un-hide`)" command="un-hide" @click.native="handleUnHideOne(row)">{{ $t('ad.unhide') }}</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <div class="white-box-footer">
<!--        <el-dropdown v-if="permission.hasPermission(`ad/ad-delete`)" size="small">-->
<!--          <el-button type="primary" size="small">-->
<!--            {{ $t('ad.selectData') }}<i class="el-icon-arrow-down el-icon&#45;&#45;right" />-->
<!--          </el-button>-->
<!--          <el-dropdown-menu slot="dropdown">-->
<!--            <el-dropdown-item command="delete" @click.native="handleMuliDel()">{{ $t('table.delete') }}</el-dropdown-item>-->
<!--            <el-dropdown-item command="hide" @click.native="handleMultiHide()">{{ $t('ad.hide') }}</el-dropdown-item>-->
<!--            <el-dropdown-item command="un-hide" @click.native="handleMultiUnHide()">{{ $t('ad.unhide') }}</el-dropdown-item>-->
<!--          </el-dropdown-menu>-->
<!--        </el-dropdown>-->
        <el-button v-if="permission.hasPermission(`ad/ad-delete`)" type="primary" size="small" icon="el-icon-plus" @click="handleAdd">{{ $t('ad.add') }}</el-button>
        <pagination v-show="total>0" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" :page.sync="listQuery.page" :limit.sync="listQuery.pageSize" @pagination="getList" />
      </div>
      </div>
  </div>
</template>

<script>
import { fetchAdList, fetchChangeSort, fetchDelete, fetchHide, fetchUnhide } from '@/api/ad'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import tool from '@/utils/tool'
import permission from '@/utils/permission'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import ElementUI from 'element-ui'
import FilterUser from "@/components/FilterUser.vue";

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'ComplexTable',
  components: {FilterUser, Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      loading: true,
      listLoading: true,
      tool: tool,
      permission: permission,
      multipleSelection: null,
      pageSize: 20,
      listQuery: {
        page: 1,
        pageSize: 20,
        adId: null
      },
      changeSort: {
        id: null,
        sort: null
      },
      sort: null,
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        type: '',
        status: 'published'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false,
      allArticle: [],
      allLocation: {
        LOCATION_NAME: null
      },
      filterTypes: null
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleSizeChange (pageSize) {
      this.getList(this.currentPage, pageSize)
    },
    handleCurrentChange (page) {
      this.getList(page, this.pageSize)
    },
    getList(page, pageSize) {
      this.listLoading = true
      this.listQuery.adId = this.$route.params
      this.listQuery.page = (page === null || page == undefined) ? 1 : page
      this.listQuery.pageSize = (pageSize === null || pageSize == undefined) ? this.pageSize : pageSize
      fetchAdList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.totalCount
        this.allArticle = response.data.allArticle
        const ad_id = this.listQuery.adId.ID
        this.allLocation = response.data.allLocation[ad_id]
        this.pageSize = pageSize
        this.filterTypes = response.data.filterTypes

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: 'published',
        type: ''
      }
    },
    handleView(row) {
      this.$router.push(`/ad/list/${row.ID}`)
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    handleChangeSort(id, sort) {
      this.changeSort.id = id
      this.changeSort.sort = sort
      fetchChangeSort(this.changeSort).then(response => {
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    getContent(aid) {
      const titles = this.allArticle.filter(article => article.ID === aid).map(article => article.TITLE)
      return titles.length > 0 ? titles[0] : aid
    },
    getHref(link) {
      return link.indexOf('http') > -1 ? link : 'http://' + link
    },
    handleEdit(row) {
      this.$router.push({ path: `/ad/edit/${row.ID}` })
    },
    handleAdd() {
      this.$router.push({ path: `/ad/add` })
    },
    handleMuliDel() {
      this.handleDelete()
    },
    handleMultiHide() {
      this.handleHide()
    },
    handleHideOne(row) {
      this.handleHide(row.ID)
    },
    handleMultiUnHide() {
      this.handleUnhide()
    },
    handleDeleteOne(row) {
      this.handleDelete(row.ID)
    },
    handleDelete(id = null) {
      const obj = this
      obj.$confirm(this.$t('common.deleteSelectedData'), this.$t('common.notice'), { // 确定删除选定的数据？
       confirmButtonText: this.$t('common.confirm'), // 确定
       cancelButtonText: this.$t('common.cancel'), // 取消
        type: 'warning'
      }).then(() => {
        const selectedIds = []
        if (id === null) {
          for (const val of obj.multipleSelection) {
            selectedIds.push(val.ID)
          }
        } else {
          selectedIds.push(id)
        }
        fetchDelete({ selected: selectedIds }).then(response => {
          this.$message({
            message: response.data,
            type: 'success'
          })
          obj.getList(obj.currentPage, obj.pageSize)
        }).catch((error) => {
            ElementUI.Message({type: 'error', message: error.message, showClose: true, duration: 0})
        })
      })
    },
    handleHide(id = null) {
      const obj = this
     obj.$confirm(this.$t('common.hideSelectedData'), this.$t('common.notice'), {  // 确定删除选定的数据？
        confirmButtonText: 'confirm', // 确定
        cancelButtonText: 'cancel', // 取消
        type: 'warning'
      }).then(() => {
        const selectedIds = []
        if (id === null) {
          for (const val of obj.multipleSelection) {
            selectedIds.push(val.ID)
          }
        } else {
          selectedIds.push(id)
        }
        fetchHide({ selected: selectedIds }).then(response => {
          this.$message({
            message: response.data,
            type: 'success'
          })
          obj.getList(obj.currentPage, obj.pageSize)
        }).catch((error) => {
            ElementUI.Message({type: 'error', message: error.message, showClose: true, duration: 0})
        })
      })
    },
    handleUnHideOne(row) {
      this.handleUnhide(row.ID)
    },
    handleUnhide(id = null) {
      const obj = this
     obj.$confirm(this.$t('common.unHideSelectedData'), this.$t('common.notice'), { // 确定删除选定的数据？
        confirmButtonText: 'confirm', // 确定
        cancelButtonText: 'cancel', // 取消
        type: 'warning'
      }).then(() => {
        const selectedIds = []
        if (id === null) {
          for (const val of obj.multipleSelection) {
            selectedIds.push(val.ID)
          }
        } else {
          selectedIds.push(id)
        }
        fetchUnhide({ selected: selectedIds }).then(response => {
          this.$message({
            message: response.data,
            type: 'success'
          })
          obj.getList(obj.currentPage, obj.pageSize)
       }).catch((error) => {
           ElementUI.Message({type: 'error', message: error.message, showClose: true, duration: 0})
       })
      })
    }
  }
}
</script>
