<template>
  <div>
    <div class="layout-no-cols right-list-toolbar">
      <el-row>
        <el-col :span="14">
          <!-- 工具条start -->
          <el-toolbar>
            <el-button @click="addClick" v-if="!!catalogId" :priv="`com.zving.cms.Catalog.Content.AddBlock.${catalogId}`">
              <i class="fa fa-plus" aria-hidden="true" ></i>新建
            </el-button>
            <el-button @click="addClick" v-else :priv="`com.zving.cms.Block.Site.Add.${siteId}||com.zving.cms.Site.AddBlock.${siteId}`">
              <i class="fa fa-plus" aria-hidden="true"></i>新建
            </el-button>
          </el-toolbar>
          <!-- 工具条end -->
        </el-col>
        <!--搜索栏-->
        <el-col :span="10"   class="dropdown-search-box-r search-bar-algin-toolbar search-bar-blocklist">
          <el-input v-model="searchFormModel.keyword" placeholder="请输入关键字" @keyup.enter.native="onSearchSubmit" size="medium">
            <el-select placeholder="" clearable slot="prepend" v-model="searchFormModel.type" @change="onTypeChange">
              <el-option label="所有区块" value="All"></el-option>
              <el-option label="我创建的区块" value="ADD"></el-option>
              <el-option label="初稿" value="Draft"></el-option>
              <el-option label="重新编辑" value="Editing"></el-option>
              <el-option label="待发布" value="ToPublish"></el-option>
              <el-option label="已发布" value="Published"></el-option>
            </el-select>
          </el-input>
          <span class="search-icon"><i class="fa fa-search" @click="onSearchSubmit" title="查询"></i></span>
        </el-col>

      </el-row>
      <!-- 列表start -->
      <el-list-view :data="blockListData" ref="blockListTable" :data-read-url="getData" :pageSize="10">
        <template slot-scope="row">
          <div class="panel-card">
            <el-row>
              <a class="list-card-title" href="javascript:void(0)" @click.stop="gotoDetailPage(row.ID)">{{row.name}}  <em>{{row.catalogName}}</em></a>
            </el-row>
            <el-row>
              <el-col :span="8"><span>类型：</span> <em v-if="item.ID === row.type" v-for="item in blockTypes" :key="item.name">{{ item.name }}</em> </el-col>
              <el-col :span="8"><span>代码：</span> <em>{{ row.code }}</em> </el-col>
              <el-col :span="8"><span>路径：</span> <em>{{ row.path }}</em> </el-col>
            </el-row>
            <el-row>
              <el-col :span="8" v-if="row.width"><span>宽度：</span> <em>{{ row.width }}</em> </el-col>
              <el-col :span="8" v-if="row.maxWeight"><span>权重：</span> <em>{{ row.minWeight }} ~ {{ row.maxWeight }}</em> </el-col>
            </el-row>
            <el-row class="list-card-buttons">
              <el-col :span="8">
                <el-tag size="small">{{ row.statusName }}</el-tag>
              </el-col>
              <el-col :span="16" class="tar">
                <el-button @click.stop="publish([row])" type="text" title="发布" :priv="`com.zving.cms.Block.Publish.${row.ID}`" >
                  <i class="fa fa-send-o"></i> 发布
                </el-button>
                <el-button @click.stop="unPublish([row])" type="text" title="待发布" :priv="`com.zving.cms.Block.Publish.${row.ID}`" >
                  <i class="fa fa-refresh"></i> 待发布
                </el-button>
                <el-button @click.stop="preview(row)" type="text" title="预览">
                  <i class="fa fa-eye"></i> 预览
                </el-button>
                <el-button @click.stop="gotoDetailPage(row.ID)" type="text" title="编辑" :priv="`com.zving.cms.Block.Edit.${row.ID}`">
                  <i class="fa fa-edit"></i> 编辑
                </el-button>
                <el-button v-if="!!catalogId" @click.stop="similarAddClick(row.ID)" type="text" title="类似创建"
                  :priv="`com.zving.cms.Catalog.Content.AddBlock.${catalogId}`">
                  <i class="fa fa-copy"></i> 类似创建
                </el-button>
                <el-button v-else @click.stop="similarAddClick(row.ID)" type="text" title="类似创建"
                  :priv="`com.zving.cms.Block.Site.Add.${siteId}||com.zving.cms.Site.AddBlock.${siteId}`">
                  <i class="fa fa-copy"></i> 类似创建
                </el-button>
                <el-button @click.stop="deleteClick([row])" type="text" title="删除" :priv="`com.zving.cms.Block.Delete.${row.ID}`">
                  <i class="fa fa-times"></i> 删除
                </el-button>
              </el-col>
            </el-row>
          </div>
        </template>
      </el-list-view>
      <!-- 列表end -->
    </div>
  </div>
</template>

<script>
import util from '@src/common/util.js'
export default {
  data() {
    return {
      blockListData: [],
      searchFormModel: {
        // 搜索
        type: 'All',
        keyword: ''
      },
      blockTypes: [],
      siteId: this.$root.siteID
    }
  },
  methods: {
    getData() {
      return [
        '/ui/blocklist', {
          params: {
            catalogID: this.catalogId,
            type: this.searchFormModel.type,
            keyword: encodeURI(this.searchFormModel.keyword)
          }
        }
      ]
    },
    // 点击名称进入详情页
    gotoDetailPage(ID, isEdit) {
      if (isEdit) {
        this.$router.push(`${this.$route.path}/edit?blockID=${ID}&catalogID=${this.catalogId}`)
      } else {
        this.$router.push(`${this.$route.path}/${ID}?catalogID=${this.catalogId}`)
      }
    },
    addClick() {
      this.$router.push(`${this.$route.path}/new?catalogID=${this.catalogId}`)
    },
    similarAddClick(ID) {
      this.$router.push(`${this.$route.path}/new?blockID=${ID}&catalogID=${this.catalogId}`)
    },
    async deleteClick(selectedRows) {
      // 区块删除
      try {
        await this.$confirm('确定删除吗，删除后无法恢复。是否继续删除？', '删除确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch (e) {
        return
      }
      let rowIDs = []
      selectedRows.forEach(function (row) {
        rowIDs.push(row.ID)
      })
      if (!rowIDs) {
        return
      }
      let data = await axios.delete(`/ui/blocklist/${rowIDs.join(',')}`)
      selectedRows = []
      if (data.data.status === 1) {
        this.blockListData = this.blockListData.filter(val => !rowIDs.includes(val.ID))
      }
      util.showResponseMessage(data.data)
    },

    refreshData(obj, type) {
      // 刷新列表数据
      if (type === 'save') {
        obj.statusName = obj.statusName === '已发布' ? '重新编辑' : obj.statusName
        let index = this.blockListData.findIndex(val => val.ID === obj.ID)
        this.blockListData.splice(index, 1, Object.assign({}, obj))
      } else if (type === 'publish') {
        obj.forEach(function (ID) {
          this.blockListData.forEach(function (data) {
            if (ID === data.ID) {
              data.statusName = '已发布'
            }
          }, this)
        }, this)
      } else if (type === 'unPublish') {
        obj.forEach(function (ID) {
          this.blockListData.forEach(function (data) {
            if (ID === data.ID) {
              data.statusName = '待发布'
            }
          }, this)
        }, this)
      }
    },

    async publish(selectedRows) {
      let IDs = []
      selectedRows.forEach(function (row) {
        IDs.push(row.ID)
      })
      if (!IDs) {
        return
      }
      let data
      try {
        data = await axios.put(`/ui/blocklist/publish/${IDs.join(',')}`)
      } catch (e) {
        util.showErrorMessageBox('请求失败，请稍后重试！')
      }
      if (data.data.status === 1) {
        this.refreshData(IDs, 'publish')
      }
      util.showResponseMessage(data.data)
    },

    async unPublish(selectedRows) {
      let IDs = []
      selectedRows.forEach(function (row) {
        IDs.push(row.ID)
      })
      if (!IDs) {
        return
      }
      let data
      try {
        data = await axios.put(`/ui/blocklist/unpublish/${IDs.join(',')}`)
      } catch (e) {
        util.showErrorMessageBox('请求失败，请稍后重试！')
      }
      if (data.data.status === 1) {
        this.refreshData(IDs, 'unPublish')
      }
      util.showResponseMessage(data.data)
    },

    async preview(selectedRow) {
      if (selectedRow.type === 'Widget') {
        if (!selectedRow.content) {
          this.$alert('请先为页面部件区块选取相应的页面部件！', '提示', {type: 'warning'})
          return
        }
        let content = JSON.parse(selectedRow.content)
        window.open(`preview.html?&ID=${content.ID}&type=${content.type}`)
      } else {
        window.open(`preview.html?id=${selectedRow.ID}&type=block_preview`)
      }
    },

    onTypeChange(command) {
      // 区块类型筛选
      this.$refs.blockListTable.getData()
    },
    onSearchSubmit() {
      this.$refs.blockListTable.getData()
    },
    async getBlocktypes() {
      let data = await axios.get(`/ui/blocklist/blocktypes`)
      this.blockTypes = data.data.data
    }
  },
  props: ['catalogId'],
  watch: {
    catalogId(value) {
      this.$refs.blockListTable.getData()
    }
  },
  created() {
    this.getBlocktypes()
  }
}
</script>
