<template>
  <el-card shadow="never"
           class="aui-card--fill">
    <div class="mod-news__news}">
      <el-form :inline="true"
               :model="dataForm"
               @keyup.enter.native="getDataList()">
        <el-form-item label="所属机构">
          <el-cascader v-model="deptIdList"
                       :options="options"
                       :props="{ checkStrictly: true }"
                       clearable></el-cascader>
        </el-form-item>
        <!--<el-form-item label="所属街道"
                      prop="deptId">
          <el-select v-model="dataForm.streetId"
                     @change="changeStreet"
                     clearable
                     placeholder="所属街道">
            <el-option v-for="item in streetList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属社区">
          <el-select v-model="dataForm.communityId"
                     @change="changeCommunity"
                     clearable
                     placeholder="所属社区">
            <el-option v-for="item in communityList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属网格">
          <el-select v-model="dataForm.gridId"
                     @change="changeGrid"
                     clearable
                     placeholder="所属网格">
            <el-option v-for="item in gridList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>-->
        <br>
        <span class="demonstration">提交时间</span>&nbsp;&nbsp;
        <el-date-picker @change='setRegistTime'
                        v-model="time"
                        value-format="yyyy-MM-dd"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期">
        </el-date-picker> &nbsp; &nbsp;
        <el-form-item label="类别">
          <el-select v-model="dataForm.category"
                     clearable
                     placeholder="所属类别">
            <el-option v-for="item in categorys"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关键字">
          <el-form-item>
            <el-input v-model="dataForm.keyword"
                      placeholder="请输入标题"
                      clearable></el-input>
          </el-form-item>
        </el-form-item>
        <el-form-item>
          <el-button @click="getDataList()">{{ $t('query') }}</el-button>
        </el-form-item>
        <el-form-item>
          <el-button v-if="$hasPermission('news:news:save')"
                     type="primary"
                     @click="addOrUpdateHandle()">{{ $t('add') }}</el-button>
        </el-form-item>
        <el-form-item>
          <el-button v-if="$hasPermission('news:news:delete')"
                     type="danger"
                     @click="deleteHandle()">{{ $t('deleteBatch') }}</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="dataListLoading"
                :data="dataList"
                border
                @selection-change="dataListSelectionChangeHandle"
                style="width: 100%;">
        <el-table-column label="序号"
                         width="50px">
          <template slot-scope="scope">
            {{scope.$index+1}}
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip
                         prop="newsTitle"
                         label="标题名称"
                         header-align="center"
                         align="center"
                         min-width="400"></el-table-column>
        <el-table-column prop="readingAmount"
                         label="阅读量"
                         header-align="center"
                         align="center"
                         width="70"></el-table-column>
        <el-table-column prop="likeNumber"
                         label="支持数"
                         header-align="center"
                         align="center"
                         width="70"></el-table-column>
        <el-table-column prop="unLikeNumber"
                         label="不支持数"
                         header-align="center"
                         align="center"
                         width="100"></el-table-column>
        <el-table-column show-overflow-tooltip
                         prop="allDeptNames"
                         label="所属网格"
                         header-align="center"
                         align="center"
                         min-width="200"></el-table-column>
        <el-table-column prop="createdTime"
                         label="提交时间"
                         header-align="center"
                         align="center"
                         width="180"></el-table-column>
        <el-table-column prop="creatorName"
                         label="提交人"
                         header-align="center"
                         align="center"
                         show-overflow-tooltip
                         width="100"></el-table-column>
        <el-table-column label="有效时间" width="360" header-align="center" align="center">
          <template slot-scope="scope">
            {{scope.row.newsReleaseStartTime}} 到 {{scope.row.newsReleaseEndTime}}
          </template>
        </el-table-column>
        <el-table-column label="发布状态"
                         :formatter="publishState"
                         header-align="center"
                         align="center"
                         width="100">
        </el-table-column>
        <!-- <el-table-column prop="newsUpDownState" label="新闻上下线状态" :formatter="newsUpDownState" header-align="center" align="center"></el-table-column> -->
        <el-table-column :label="$t('handle')"
                         fixed="right"
                         header-align="center"
                         align="center"
                         width="200">
          <template slot-scope="scope">
            <el-button type="text"
                       size="small"
                       @click="addOrUpdateHandle(scope.row.id)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination :current-page="page"
                     :page-sizes="[10, 20, 50, 100]"
                     :page-size="limit"
                     :total="total"
                     layout="total, sizes, prev, pager, next, jumper"
                     @size-change="pageSizeChangeHandle"
                     @current-change="pageCurrentChangeHandle">
      </el-pagination>
      <!-- 弹窗, 新增 / 修改 -->
      <add-or-update v-if="addOrUpdateVisible"
                     ref="addOrUpdate"
                     @refreshDataList="getDataList"></add-or-update>
    </div>
  </el-card>
</template>
<script>
import mixinViewModule from '@/mixins/view-module'
import AddOrUpdate from './allnews-add-or-update'
export default {
  mixins: [mixinViewModule],
  data () {
    return {
      mixinViewModuleOptions: {
        getDataListURL: '/news/news/allPage',
        getDataListIsPage: true,
        deleteURL: '/news/news',
        deleteIsBatch: true
      },
      dataForm: {
        id: '',
        streetId: '',
        communityId: '',
        gridId: '',
        startTime: '',
        endTime: '',
        keyword: '',
        category: ''
      },
      time: '',
      options: [],
      deptIdList: [],
      streetList: [],
      communityList: [],
      gridList: [],
      categorys: [],
      onLine: {
        id: '',
        onLineState: ''
      }
    }
  },
  created () {
    this.$http
      .get(`/sys/user/deptOptions/getByLoginUser`)
      .then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.options = res.data.options
      })
      .catch(() => { })
    this.getDeptInfoList('street', localStorage.getItem('street') === null ? '1169154711480528897' : localStorage.getItem('street'))
    this.getListCategory()
  },
  methods: {
    newsUpDownState: function (row) {
      return row.newsUpDownState === '1' ? '下线' : '上线'
    },
    publishState: function (row) {
      var stdt = new Date(row.newsReleaseStartTime.replace('-', '/'))
      var eddt = new Date(row.newsReleaseEndTime.replace('-', '/'))
      var nowdt = new Date()
      if (row.newsUpDownState === '1') {
        // 手动下线
        return '已下线'
      }
      if (nowdt > stdt && nowdt < eddt && row.newsUpDownState === '0') {
        return '已上线'
      }
      if (nowdt < stdt) {
        return '未上线'
      }
      if (nowdt > eddt) {
        return '已下线'
      }
    },
    // 获取部门列表
    getDeptInfoList (dataReceiver, faDeptId) {
      this.$http.get(`/sys/dept/sublist/` + faDeptId).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        if (dataReceiver === 'street') {
          this.streetList = res.data
        } else if (dataReceiver === 'community') {
          this.communityList = res.data
        } else if (dataReceiver === 'grid') {
          this.gridList = res.data
        }
      }).catch(() => { })
    },
    changeStreet (event) {
      if (this.dataForm.streetId === '') {
        this.communityList = []
        this.gridList = []
        this.dataForm.communityId = ''
        this.dataForm.gridId = ''
        return
      }
      this.dataForm.streetId = event
      let choosenItem = this.streetList.filter(item => item.id === this.dataForm.streetId)[0]
      this.initDeptIdAndName(choosenItem)
      this.dataForm.communityId = this.dataForm.gridId = null
      this.communityList = this.gridList = []
      this.getDeptInfoList('community', event)
    },
    changeCommunity (event) {
      if (this.dataForm.communityId === '') {
        this.gridList = []
        this.dataForm.gridId = ''
        return
      }
      this.communityId = event
      let choosenItem = this.communityList.filter(item => item.id === this.dataForm.communityId)[0]
      this.initDeptIdAndName(choosenItem)
      this.dataForm.gridId = null
      this.gridList = []
      this.getDeptInfoList('grid', event)
    },
    changeGrid (event) {
      this.dataForm.gridId = event
      let choosenItem = this.gridList.filter(item => item.id === this.gridId)[0]
      this.initDeptIdAndName(choosenItem)
    },
    initDeptIdAndName (choosenItem) {
      this.dataForm.dept = choosenItem.name
      this.dataForm.deptId = choosenItem.id
    },
    setRegistTime () {
      console.log(this.time[0])
      this.dataForm.startTime = this.time[0]
      this.dataForm.endTime = this.time[1]
    },
    getListCategory () {
      this.$http.get(`/news/newscategory/category/`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.categorys = res.data
      }).catch(() => { })
    },
    modifyOnLine (row) {
      this.$confirm(this.$t('prompt.info', { 'handle': '下线' }), this.$t('下线'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      }).then(() => {
        this.onLine.id = row.id
        this.onLine.onLineState = '0'
        console.log(this.onLine)
        this.$http.post(`/news/news/modifyOnLine/`, this.onLine).then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
            }
          })
          this.getDataList()
        }).catch(() => { })
      }).catch(() => { })
    },
    newsToBanner (row) {
      this.$confirm(this.$t('prompt.info', { 'handle': '上banner' }), this.$t('上banner'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      }).then(() => {
        this.$http.post(`/news/news/newsToBanner/` + row.id).then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
            }
          })
          this.getDataList()
        }).catch(() => { })
      }).catch(() => { })
    },
    // 获取数据列表
    getDataList () {
      if (this.time === null) {
        this.dataForm.startTime = ''
        this.dataForm.endTime = ''
      }
      this.dataListLoading = true
      this.$http.get(
        this.mixinViewModuleOptions.getDataListURL,
        {
          params: {
            order: this.order,
            orderField: this.orderField,
            page: this.mixinViewModuleOptions.getDataListIsPage ? this.page : null,
            limit: this.mixinViewModuleOptions.getDataListIsPage ? this.limit : null,
            ...this.dataForm
          }
        }
      ).then(({ data: res }) => {
        this.dataListLoading = false
        if (res.code !== 0) {
          this.dataList = []
          this.total = 0
          return this.$message.error(res.msg)
        }
        this.dataList = this.mixinViewModuleOptions.getDataListIsPage ? res.data.list : res.data
        this.total = this.mixinViewModuleOptions.getDataListIsPage ? res.data.total : 0
      }).catch(() => {
        this.dataListLoading = false
      })
    }
  },
  components: {
    AddOrUpdate
  },
  watch: {
    'deptIdList': function (val) {
      if (val.length !== 0) {
        this.dataForm.gridId = val[val.length - 1]
      } else {
        this.dataForm.gridId = ''
      }
    }
  }
}
</script>
