<template>
  <div class="app-container">
    <div class="filter-container">
      <label style="font-size: 14px; color: #606266;">标题</label>
      <el-input v-model="listQuery.title" placeholder="请输入标题" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
      <!-- <label>跳转概述</label>
      <el-input v-model="listQuery.bannerDescription" placeholder="请输入跳转概述" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/> -->
      <label style="font-size: 14px; color: #606266;">适用社区</label>
      <el-select v-model="listQuery.communityId" placeholder="适用社区" clearable style="width: 200px" class="filter-item">
        <el-option v-for="item in communityList" :key="item.id" :value="item.id" :label="item.communityName"/>
      </el-select>
      <label style="font-size: 14px; color: #606266;">banner位置</label>
      <el-select v-model="listQuery.bannerPosition" placeholder="banner位置" clearable class="filter-item" style="width: 200px">
        <el-option v-for="item in bannerPositionArr" :key="item.id" :value="item.id" :label="item.value"/>
      </el-select>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
      <el-button v-waves class="filter-item" type="info" icon="el-icon-warning" @click="handleFilter">清空</el-button>
    </div>

    <el-row style="margin-top: 20px; margin-bottom: 20px;">
      <el-button type="primary" icon="el-icon-circle-plus" @click="dialogAddForm">添加</el-button>
      <el-button type="danger" icon="el-icon-delete" @click="deleteBanner">删除</el-button>
      <!-- <el-button type="primary" icon="el-icon-edit">设置轮播数</el-button> -->
    </el-row>

    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%; margin-top: 20px;"
      @selection-change="handleSelectionChange">
      <el-table-column label="选择" type="selection" sortable="custom" align="center" />
      <el-table-column label="标题" align="center" min-width="250px">
        <template slot-scope="scope">
          <!-- <span class="link-type" @click="handleUpdate(scope.row)">{{ scope.row.title }}</span> -->
          <!-- style="color: #409EFF;cursor: pointer" -->
          <span class="link-type" style="color: #409EFF;cursor: pointer" @click="infoBanner(scope.row.id)">{{ scope.row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="适用社区" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.communityName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="banner位置" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.bannerPositionName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="权重" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.sort }}</span>
        </template>
      </el-table-column>
      <el-table-column label="生效时间" align="center">
        <template slot-scope="scope">
          <span>{{ formatDate(scope.row.effTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="失效时间" class-name="status-col" align="center">
        <template slot-scope="scope">
          <span>{{ formatDate(scope.row.expTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" class-name="status-col" align="center">
        <template slot-scope="scope">
          <span>{{ formatDate(scope.row.updateDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改人" class-name="status-col" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.updateUserName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" class-name="status-col" align="center">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" @click="updateBanner(scope.row.id)">修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- <pagination v-show="total>0" :total="total" :current-page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" :page-sizes="[5, 10, 20, 30]" @pagination="getList" /> -->
    <el-pagination
      :total="total"
      :current-page="listQuery.pageNum"
      :page-sizes="[10, 20, 30]"
      :page-size="listQuery.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"/>
  </div>
</template>

<script>
// import { updateArticle, createBanner } from '@/api/banner' // getBanner
import { mapState, mapActions } from 'vuex'
import waves from '@/directive/waves' // Waves directive
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]
// 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: { 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,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        title: undefined,
        bannerPosition: undefined,
        bannerDescription: undefined,
        communityId: undefined
      },
      communityQuery: {
        pageNum: 1,
        pageSize: 200
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      addForm: {
        title: '',
        sort: '1',
        bannerCover: '',
        bannerPosition: '',
        communityId: '',
        effTime: '',
        expTime: '',
        bannerType: '1',
        externalLink: '',
        bannerTitle: '',
        bannerContent: ''
      },
      formLabelWidth: '120px',
      bannerPositionArr: [
        { id: 1, value: '首页banner' },
        { id: 2, value: '服务banner' },
        { id: 3, value: '广告banner' }
      ],
      deleteBannerId: []
    }
  },
  computed: {
    ...mapState('community', {
      communityList: s => s.list
    })
  },
  created() {
    const query = this.$route.query.listQuery
    if (query !== undefined) {
      this.listQuery = this.$route.query.listQuery
    }
    this.getList()
    this.getCommuniryList()
  },
  methods: {
    ...mapActions('community', [
      'FetchCommunityList',
      'CreateCommunity',
      'UpdateCommunity'
    ]),
    deleteBanner() {
      this.$confirm('您确定删除此banner吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(this.deleteBannerId)
        if (this.deleteBannerId.length === 0) {
          this.$message({
            message: '请选择需要删除的数据!',
            type: 'warning'
          })
        } else {
          this.$store.dispatch('DeleteBanner', this.deleteBannerId).then((res) => {
            if (res.code === '0') {
              this.$message({
                message: res.message,
                type: 'success'
              })
              this.deleteBannerId = []
              this.getList()
            } else {
              this.$message({
                message: res.message,
                type: 'warning'
              })
            }
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    dialogAddForm() {
      this.$router.push({ name: 'banner-add', query: { listQuery: this.listQuery }})
    },
    updateBanner(bannerId) {
      this.$router.push({ name: 'banner-edi', query: { id: bannerId, listQuery: this.listQuery }})
    },
    infoBanner(bannerId) {
      this.$router.push({ name: 'banner-info', query: { id: bannerId, listQuery: this.listQuery }})
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.listQuery.pageNum = val
      this.getList()
    },
    formatDate(val) {
      var value = new Date(val)
      var year = value.getFullYear()
      var month = value.getMonth() + 1
      var day = value.getDate()
      // var hour = value.getHours()
      // var minutes = value.getMinutes()
      // var seconds = value.getSeconds()
      // return year + '-' + month + '-' + day + ' ' + hour + ':' + minutes + ':' + seconds
      return year + '-' + month + '-' + day
    },
    getList() {
      this.listLoading = true
      this.$store.dispatch('GetBanner', this.listQuery).then(response => {
        this.list = response.item
        this.total = response.total
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    },
    getCommuniryList() {
      this.listLoading = true
      this.FetchCommunityList(this.communityQuery).then(() => {
        this.listLoading = false
      }).catch(() => {
        this.loading = false
        console.log('get list error')
      })
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.listQuery.pageSize = 5
      this.listQuery.title = undefined
      this.listQuery.bannerPosition = undefined
      this.listQuery.bannerDescription = undefined
      this.listQuery.communityId = undefined
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    handleSelectionChange(data) {
      this.deleteBannerId = []
      const bannerIdArr = this.deleteBannerId
      for (const i in data) {
        bannerIdArr.push(data[i].id)
      }
    },
    handleSearch() {
      this.getList()
    }
  }
}
</script>

<style scoped>
.title-span {
  background-color: rgba(64,158,255,.1);
  padding: 0 10px;
  height: 32px;
  line-height: 30px;
  font-size: 12px;
  color: #409EFF;
  border-radius: 4px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  border: 1px solid rgba(64,158,255,.2);
  white-space: nowrap;
}
</style>

