<template>
  <div  style="min-height:calc(100vh - 200px);">
    <el-toolbar>
      <el-col :offset="14" :span="10">
        <div class="list-or-grid" style="float: right;line-height:normal">
                <el-radio-group v-model="listLayout" @change="changeType">
                  <el-radio-button label="list">
                    <i class="fa fa-list-ul"></i>
                  </el-radio-button>
                  <el-radio-button label="grid">
                    <i class="fa fa-th"></i>
                  </el-radio-button>
                  <el-radio-button label="table">
                    <i class="fa fa-table"></i>
                  </el-radio-button>
                </el-radio-group>
            </div>
      </el-col>
    </el-toolbar>
    <el-row type="flex" class="row-bg" justify="space-around" align="middle">
      <el-col :span="7">
        <el-select class="layout-select" placeholder="" clearable v-model="orderType" @change="reflushlist">
          <el-option v-for="item in orderTypeList" :key="'key_'+item.value" :value="item.value" :label="item.label"></el-option>
        </el-select>
        </el-col>

      <el-col :span="9">
        <el-input v-model="search" placeholder="请输入标题" size="medium" @keyup.enter.native="reflushlist">
        </el-input>
      </el-col>

      <el-col :span="7">
        <el-select class="layout-select" placeholder="文章状态" clearable v-model="status" @change="reflushlist">
          <el-option v-for="item in statusList" :key="'key_'+item.value" :value="item.value" :label="item.label"></el-option>
        </el-select>
        </el-col>
    </el-row>
    <div style="padding:3px"></div>
    <el-row type="flex" class="row-bg" justify="space-around" align="middle">
      <el-col :span="7">
        <el-select class="layout-select" placeholder="选择文章类型" clearable v-model="contentType" @change="reflushlist">
          <el-option  :label="value" :key="value" :value="key" v-for="(value,key) in contentTypeList"></el-option>
        </el-select>
      </el-col>
      <el-col :span="9">
        <el-date-picker
            id="dept-date-picker"
            class="layout-date-picker"
            @change="reflushlist"
            v-model="dateInterval"
            type="datetimerange"
            start-placeholder="发布时间"
            end-placeholder="发布时间"
            style="width:100%"
            :picker-options="selectDates"></el-date-picker>
      </el-col>
      <el-col :span="7">
        <el-button  type="primary" @click="reflushlist">
          <i class="fa fa-search"></i>搜索
        </el-button>
      </el-col>
    </el-row>
    <div class="content-list">
      <el-table  ref="list" :data-read-url="getData" :pageSize="20" v-if="listLayout=='table'" :multi-operates="multiOperates">
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column type="index" width="60" label="序号" align="center"></el-table-column>
        <el-table-column label="标题" >
          <template slot-scope="scope" >
            <span v-if="hasPrivs('Draft.Dept.Draft.Edit')"><a  @click.stop="edit(scope.row)">{{scope.row.title}}</a></span>
            <span v-else>{{scope.row.title}}</span>
          </template>
        </el-table-column>
        <el-table-column label="所属栏目" width="100">
          <template slot-scope="scope">
            <em v-if="scope.row.dimensionName">{{scope.row.dimensionName}}></em><em>{{scope.row.catalogName}}</em>
          </template>
        </el-table-column>
        <el-table-column label="所属部门" width="100" >
          <template slot-scope="scope">
            <span>{{scope.row.branchName}}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80">
          <template slot-scope="scope">
            <span>{{scope.row.statusName}}</span>
          </template>
        </el-table-column>
        <el-table-column label="发布时间" width="160" >
          <template slot-scope="scope">
            <span>{{scope.row.publishDate | fixDateTime}}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="right">
          <template slot-scope="scope">
              <!-- 发布按钮 -->
            <draft-publish-button
              v-if="hasPrivs('Draft.Dept.Draft.Publish')"
              :contentId="scope.row.ID"
              :catalogId="scope.row.catalogID"
              :contentType="scope.row.contentTypeID"
              @refresh-content="reflushlist()"
              :rootCatalogId="catalogId"
              ></draft-publish-button>
              <el-dropdown>
              <el-button type='text'>
                <i class="fa fa-ellipsis-h" aria-hidden="true"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown" class="button-dropdown">
                <el-dropdown-item>
                  <el-button v-if="hasPrivs('Draft.Dept.Draft.Edit')" @click.stop="edit(scope.row)" type="text" title="编辑"  :priv="'com.zving.cms.Catalog.Content.Edit.'+scope.row.catalogID">
                    <i class="fa fa-edit"></i>编辑
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item >
                  <el-button @click.stop="preview(scope.row)" v-if="!!scope.row.catalogID"  type="text" title="预览">
                    <i class="fa fa-eye"></i>预览
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <content-delete-button v-if="hasPrivs('Draft.Dept.Draft.Del')" :selected-rows="[scope.row]" @refresh-content="reflushlist()" :catalog-id="scope.row.catalogID" button-type="text"></content-delete-button>
                </el-dropdown-item>
              </el-dropdown-menu>
              </el-dropdown>
            <!-- <el-button v-if="hasPrivs('Draft.Dept.Edit')" @click.stop="edit(scope.row)" type="text" title="编辑"  :priv="'com.zving.cms.Catalog.Content.Edit.'+scope.row.catalogID">
              <i class="fa fa-edit"></i>编辑</el-button>
            <el-button @click.stop="preview(scope.row)" type="text" title="预览">
              <i class="fa fa-eye"></i>预览</el-button>
            <content-delete-button v-if="hasPrivs('Draft.Dept.Del')" :selected-rows="[scope.row]" @refresh-content="reflushlist()" :catalog-id="scope.row.catalogID" button-type="text"></content-delete-button> -->
          </template>
        </el-table-column>
      </el-table>
      <el-list-view ref="list" class="list-view-dept" :data-read-url="getData" :page-size="20"  :layout="listLayout" v-else selectable :multi-operates="multiOperates">
        <template slot-scope="row">
          <div class="panel-card">
            <el-row :gutter="20">
              <el-col :span="4" class="item-logo-ct">
                <div :class="listLayout=='list'?'logoFile':'logoFile_table'" :style="{backgroundImage:'url('+row.listLogo+'),url(assets/images/picture404-'+((row.ID||row.$index) % 4)+'.png)'}"></div>
              </el-col>
              <el-col :span="20" class="item-info-ct">
                <i :class="row.contentTypeID | fixIcon" style="font-size:17px"></i>
                <em v-if="row.dimensionName">[{{row.dimensionName}}] </em><em>[{{row.catalogName}}] </em>
                <a class="list-card-title" href="javascript:void(0)" @click.stop="edit(row)" :style="row.titleStyle">&nbsp;{{row.title|getchars(60)}}</a>
                <p class="summary" v-if="!row.bodyText">{{row.summary|getchars(110)}}</p>
                <p class="summary" v-else>{{row.bodyText|getchars(110)}}</p>

                <el-row v-if="listLayout=='list'">
                  <el-col :span="24" style="text-align:right">
                    <span class="datetime" >{{row.publishDate | fixDateTime}}</span>
                  </el-col>
                </el-row>
                <el-row v-else>
                  <p><em v-if="row.dimensionName">{{row.dimensionName}}></em><em>{{row.catalogName}}</em></p>
                  <p><span class="datetime" >{{row.publishDate | fixDateTime}}</span></p>
                </el-row>

              </el-col>
            </el-row>
            <el-row>
              <el-col :span="10" class="item-status">
                <el-tag size="small">{{row.statusName}}</el-tag>
                <span style="color: #28b06e;" v-for="(value,key) in row.checkedAttrs" :key="key" :title="value"><i :class="key | contentPrefix"></i></span>
                <span v-if="!!row.imagesTotal" title="图片"><i class="fa fa-file-image-o"></i><span class="num-circle">{{row.imagesTotal}}</span></span>
                <span v-if="!!row.videosTotal" title="视频"><i class="fa fa-file-video-o"></i><span class="num-circle">{{row.videosTotal}}</span></span>
                <span v-if="!!row.audiosTotal" title="音频"><i class="fa fa-file-audio-o"></i><span class="num-circle">{{row.audiosTotal}}</span></span>
                <span v-if="!!row.filesTotal" title="文件"><i class="fa fa-file-archive-o"></i><span class="num-circle">{{row.filesTotal}}</span></span>
              </el-col>
              <el-col :span="14" class="item-buttons" style="text-align:right">
                  <!-- 发布按钮 -->
                <draft-publish-button
                  v-if="hasPrivs('Draft.Dept.Draft.Publish')"
                  :contentId="row.ID"
                  :catalogId="row.catalogID"
                  :contentType="row.contentTypeID"
                  @refresh-content="reflushlist()"
                  :rootCatalogId="catalogId"
                  ></draft-publish-button>
                <el-button v-if="hasPrivs('Draft.Dept.Draft.Edit')" @click.stop="edit(row)" type="text" title="编辑"  :priv="'com.zving.cms.Catalog.Content.Edit.'+row.catalogID">
                  <i class="fa fa-edit"></i>编辑</el-button>
                <el-button @click.stop="preview(row)" type="text" title="预览" v-if="!!row.catalogID">
                  <i class="fa fa-eye"></i>预览</el-button>
                <content-delete-button v-if="hasPrivs('Draft.Dept.Draft.Del')" @refresh-content="reflushlist()" :selected-rows="[row]" :catalog-id="row.catalogID" button-type="text"></content-delete-button>
              </el-col>
            </el-row>
          </div>
        </template>
      </el-list-view>
    </div>
  </div>
</template>
<script>
import util from '@src/common/util.js'
import Privilege from '@src/common/privilege.js'
import ContentAddButton from '../contentcore/components/ContentAddButton.vue'
import ContentDeleteButton from '../contentcore/components/ContentDeleteButton.vue'
import DraftPublishButton from './components/DraftPublishButton.vue'

export default {
  components: {
    'content-add-button': ContentAddButton,
    'content-delete-button': ContentDeleteButton,
    'draft-publish-button': DraftPublishButton
  },
  filters: {
    fixIcon: function(val) {
      switch (val) {
        case 'Image':
          return 'fa fa-image'
        case 'Audio':
          return 'fa fa-music'
        case 'Video':
          return 'fa fa-video-camera'
        case 'File':
          return 'fa fa-file-archive-o'
        case 'VideoGroup':
          return 'fa fa-film'
        case 'Special':
          return 'fa fa-id-card-o'
        default:
          return 'fa fa-file-text-o'
      }
    },
    getchars: function(summary, len) {
      len = len > 60 ? 300 : 60
      return summary ? summary.slice(0, len) : ''
    },
    fixDateTime: function(val) {
      return val ? util.formatDate(val, 'yyyy-MM-dd HH:mm') : ' '
    },
    contentPrefix: function(val) {
      switch (val) {
        case 'attach':
          return 'fa fa-paperclip'
        case 'contribute':
          return 'fa fa-pencil-square-o'
        case 'copy':
          return 'fa fa-copy'
        case 'copyout':
          return 'fa fa-clipboard'
        case 'hot':
          return 'fa fa-fire'
        case 'image':
          return 'fa fa-image'
        case 'notation':
          return 'fa fa-file'
        case 'recommend':
          return 'fa fa-thumbs-up'
        case 'refer':
          return 'fa fa-external-link'
        case 'top':
          return 'fa fa-arrow-up'
        case 'video':
          return 'fa fa-film'
        default:
          return ''
      }
    }
  },
  props: {
    branchinnercode: String,
    catalogId: {
      type: [String, Number]
    }
  },
  data() {
    return {
      orderTypeList: [
        { label: '默认排序', value: '' },
        { label: '按添加日期', value: 'addtime' },
        { label: '按发布日期', value: 'publishdate' }
      ],
      statusList: [
        { label: '我创建的', value: 'add' },
        { label: '初稿', value: 'draft' },
        { label: '暂存', value: 'temporary' },
        { label: '重新编辑', value: 'editing' },
        { label: '流转中', value: 'workflow' },
        { label: '待发布', value: 'topublish' },
        { label: '已发布', value: 'published' },
        { label: '已下线', value: 'offline' },
        { label: '已归档', value: 'archive' },
        { label: '投稿', value: 'contribute' }
      ],
      contentTypeList: [],
      status: '',
      search: '',
      dateInterval: '',
      contentType: '',
      orderType: '',
      listLayout: 'list',
      selectDates: {
        shortcuts: [
          {
            text: '最近一天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 1)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      multiOperates: [
        {
          label: '删除',
          value: 'delete',
          fn: rows => {
            this.deleteContents(rows)
          }
        }
      ]
    }
  },
  watch: {
    branchinnercode() {
      this.reflushlist()
    }
  },
  computed: {
    startTime() {
      if (this.dateInterval) {
        return Date.parse(this.dateInterval[0])
      }
      return ''
    },
    endTime() {
      if (this.dateInterval) {
        return Date.parse(this.dateInterval[1])
      }
      return ''
    }
  },
  created() {
    this.getContentTypeList()
  },
  mounted() {
    window.refreshContentList = this.reflushlist
    if (!this.catalogId) {
      return
    }
    this.getContentTypeList()
  },
  methods: {
    // 批量删除内容
    async deleteContents(rows) {
      if (!Privilege.hasPriv('Draft.Dept.Draft.Del')) {
        util.showError('您没有操作权限！')
        return
      }

      this.$confirm(`确认删除选择的<span class='icon-danger'>${rows.length}条</span>内容吗？`, {
        title: '提示',
        dangerouslyUseHTMLString: true,
        type: 'warning'
      })
        .then(async r => {
          let data = {}
          rows.forEach(item => {
            let p = item.catalogID ? `com.zving.cms.Catalog.Content.Delete.${item.catalogID}` : 'Draft.Dept.Draft.Del'
            if (Privilege.hasPriv(p)) {
              if (data[item.catalogID] && Array.isArray(data[item.catalogID])) {
                data[item.catalogID].push(item.ID)
              } else {
                data[item.catalogID] = [item.ID]
              }
            }
          })

          let resp = await axios.delete(`/ui/contentcore/contents/delete`, {
            params: { data }
          })
          await util.showProgress(resp.data.taskID, resp.data.message)
          this.$refs.list.getData()
        })
        .catch(err => { console.error(err) })

      return null
    },

    hasPrivs(val) {
      return !!(val && Privilege.hasPriv(val))
    },
    getData() {
      return [
        '/ui/draftlib/dept/contentlist',
        {
          params: {
            branchInnerCode: this.branchinnercode,
            search: this.search,
            status: this.status,
            startTime: this.startTime,
            endTime: this.endTime,
            orderType: this.orderType,
            contentType: this.contentType
          }
        }
      ]
    },
    async getContentTypeList() {
      this.listLayout = localStorage['draft_show_type'] ? localStorage['draft_show_type'] : this.listLayout
      let catalogId = this.catalogId
      let resp = await axios.get(`/ui/catalogs/${catalogId || 0}/contenttypes`)
      // TODO: 上面一行的逻辑对吗？请检查测试
      if (resp.data.status === 1) {
        this.contentTypeList = resp.data.data
      }
    },
    reflushlist() {
      this.$refs.list.getData()
    },
    edit (row) {
      let id = row.ID ? row.ID : 'new'
      let format = row.extendJSON ? JSON.parse(row.extendJSON).format : ''
      let path = `/contentEditor/${id}?type=${row.contentTypeID}${row.catalogID ? `&cid=${row.catalogID}` : ''}`
      path = format ? path + `&format=${format}` : path
      window.open('contentEditor.html#' + path)
    },
    preview(row) {
      let currentLink = `preview.html?id=${row.ID}&type=content`
      if (row.contentTypeID === 'Special') {
        currentLink = `preview.html?id=${row.ID}&type=special&pageType=Special`
      }
      window.open(currentLink)
    },
    async publish(id, type) {
      let resp = await axios.put(`/ui/contentcore/contentpublish/${id}/${type}`)
      util.showResponseMessage(resp.data)
      resp.data.status === 1 && this.search()
    },
    changeType(val) {
      localStorage['draft_show_type'] = val
    }
  }
}
</script>
<style scoped>
.content-list >>> .el-loading-mask {
  background-color: rgba(0, 0, 0, 0)
}
.list-view-dept{
  min-height: 40px;
}
.el-list-view.list .item-buttons {
  text-align: right;
}
.el-list-view.grid .item-status,
.el-list-view.grid .item-buttons {
  float: none;
  width: 100%;
}
.el-list-view.grid .item-buttons {
  display: flex;
  justify-content: space-between;
}

.el-list-view.grid .item-buttons .el-button {
  padding-left: 0px;
  padding-right: 0px;
}
.el-list-view.grid .item-logo-ct,
.el-list-view.grid .item-info-ct {
  float: none;
  width: 100%;
}
.el-list-view.grid .item-info-ct {
  padding: 5px 15px !important;
}
.el-table {
  margin-top: 10px;
}
.summary{
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  font-size: 13px;
  color: #999;
  height: 38px;
  margin-bottom: 15px;
}
</style>
