<template>
  <div class="table-bg">
    <el-table
      v-loading="loading"
      header-row-class-name="table-head"
      :data="tableData.data"
      @sort-change = "sortChange"
      :border="table.border"
      :empty-text="'暂无数据'"
      @select="handleSelectionChange"
      @select-all="handleSelectionChange"
      :default-sort = "table.defaultSort"
      style="width: 100%">
      <el-table-column v-if="table.select"
                       type="selection"
                       align="center"
                       width="50">
      </el-table-column>
      <el-table-column  v-if="table.index"
                        :label="'序号'"
                        type="index"
                        align="center"
                        width="80"
                        :index="indexMethod">
      </el-table-column>
      <el-table-column
        :resizable="table.resizable"
        v-for="col in table.tableLabel"
        :align="(col.hasOwnProperty('align')&& col.align) ? col.align : 'center'"
        :key="col.prop"
        :type="col.type"
        :fixed="col.fixed"
        :prop="col.prop"
        :label="col.title"
        :min-width="col.width"
        :sortable="col.sort&&'custom'"
        :show-overflow-tooltip="(col.ellipsis===false)?false:true">
        <template slot-scope="scope">

          <template v-if="col.hasOwnProperty('type') && col.type==='img'">
            <el-image
              :style="{ width: (col.imgWidth||100)+'px',  height: (col.imgWidth||100)+'px'}"
              :src="scope.row[col.prop]"
              :fit="'fit'">
            </el-image>
          </template>
          <template v-else-if="col.hasOwnProperty('type') && col.type==='imgs'">
            <el-carousel :interval="5000"  arrow="never"  type="card" indicator-position="none" :autoplay="false">
              <el-carousel-item v-for="item in scope.row[col.prop]" :key="item">
                <el-image
                  :style="{ width: (col.imgWidth||100)+'px',  height: (col.imgWidth||100)+'px'}"
                  :src="item"
                  :fit="'fit'">
                </el-image>
              </el-carousel-item>
            </el-carousel>
          </template>
          <template v-else-if="col.hasOwnProperty('trigger')">
            <el-switch
              v-model="scope.row[col.prop]"
              :active-value="col.trigger.activeValue||1"
              :inactive-value="col.trigger.inActiveValue||0"
              @change="switchTrigger(scope.row,$event,col.trigger.methods)"
            >
            </el-switch>
          </template>
          <span class="table-link-text" :class="(col.hasOwnProperty('className')?col.className:'') + ' ' + (col.hasOwnProperty('color')?col.color:'') + ' ' + (col.colorOption ? (col.colorOption.option[scope.row[col.colorOption.depend]]) : '')"  @click="handleButton(scope.row,col.methods)" v-else-if="col.methods">
            {{formatter(scope.row, col)||col.prop}}</span>
          <span v-else   class="table-color-text" :class="(col.hasOwnProperty('className')?col.className:'') + ' ' + (col.hasOwnProperty('color')?col.color:'') + ' ' +( col.colorOption ? (col.colorOption.option[scope.row[col.colorOption.depend]]) : '')"  >
            {{formatter(scope.row, col)}}
          </span>
        </template>

      </el-table-column>
      <el-table-column
        v-if="table.tableOperate"
        fixed="right"
        align="center"
        header-align="center"
        :label="'操作'"
        :width="table.tableOperate.width">
        <template slot-scope="scope">
          <span  class="table-link-text" :class="btn.color||''" v-for="btn in table.tableOperate.buttons" :key="btn.methods" v-if="btnIsShow(scope.row,btn)"
                 @click="handleButton(scope.row,btn.methods)" >
            {{ btn.label }}</span>
        </template>
      </el-table-column>
    </el-table>

    <Page
      @sizeChange="handleSizeChange"
      @currentChange="handleCurrentChange"
      :current-page="tableData.page"
      :page-sizes="pageParam.pageSizes"
      :page-size="pageParam.pageSize"
      :total="tableData.total"
      :style="table.pageStyle">
    </Page>

  </div>
</template>

<script>
  /*
  * 2019-05-13
  * 徐飞
  * 增加了单图展示和文字对齐字段
  * */
  import Page from '../components/page'
  /*
  * tableData.page需要传过来
  * */

  export default {
    name: 'mainTable',
    components:{
      Page
    },
    props: {
      loading:{ // 必须要使用value
        default: false,
      },
      tableOption:{ // 必须要使用value
        default: ()=>({}),
      },
      tableData:{ // 必须要使用value
        default: ()=>({}),
      },
      formatterOptions:{ // 必须要使用value
        default: ()=>({}),
      },
      pageParam:{ // 必须要使用value
        default: ()=>({
          pageSize: 10, // 可选
          pageSizes: [10,15,20,50], // 可选
          page: 1
        }),
      },
    },
    data:function(){
      return{

      }
    },
    computed: {
      table: function() {
        let tableOptionDefault = {
          resizable: false,
          // 配置是否显示网格
          border: false,
          // 默认排序 {prop:字段名,order:desc}
          defaultSort: {prop: 'updateTime' ,order: 'descending' },
          // 是否显示行勾选
          select: false,
          /*
          存放列信息
          tableLabel:[
             {prop:'name',title:'名称',width:'200',methods:'productView'},
             {prop:'isDelete',title:'状态',width:'100',formatter:'statusOptions'}
           ]
           prop放字段名
           title放中文显示名
           methods放触发的方法
           formatter放需要对应转换的参考数组数组内对象{id:xxx,name:xxx}
           */
          tableLabel: [],
          /*
          存放最后一列的操作按钮
          tableOperate:{
            width:'250',
            buttons:[
              {label:'修改',methods:'updateProductView',color:''},
              {label:'修改模板',methods:'updateTemplate',hide:{templateId:null}},
              {label:'创建模板',methods:'setTemplate',show:{templateId:null}}
            ]
          }
          methods为按钮触发的方法，只能调用当前页面的方法
          hide控制该按钮显隐，根据内部对象字段条件是否满足来判断
          color属性控制按钮颜色
            &.link{
              //蓝色
              color:#0879FE
            }
            &.safe{
              //绿色
              color:#5BC146
            }
            &.warn{
              //红色
              color:#FD4C62
            }
            &.info{
              //橘色
              color:#FD4C62
            }
          */
          tableOperate: {},
          // 分页配置，一般不动
          pageStyle: {
            layout: 'default',
            background: false
          }
        }

        Object.assign(tableOptionDefault, this.tableOption)

        // console.log(this.tableData)
        return tableOptionDefault
      }
    },
    mounted(){
      // console.log(this.table)
    },
    methods: {
      switchTrigger(row,status,methods) {
        this.$emit('action',{'row': row,'methods': methods, 'status': status});
      },
      formatter(row,col){
        let colName=col.prop
        let value=row[colName]
        if(col.formatter == undefined){
          value = (value === null || value === 'null') ? '' : value
          value = (col.prefix || '') + value + (col.suffix || '')
        }else if(typeof (col.formatter) === 'string'){
          if(this.formatterOptions && this.formatterOptions[col.formatter]){
            let options = this.formatterOptions[col.formatter]
            for(let o of options){
              if(o.id === value){
                return o.name
              }
            }
            return options[value]
          }
        }else if(typeof (col.formatter) === 'function'){
          value=col.formatter(row,col)
        }
        return value
      },
      btnIsShow(item,obj){
        let btnShow=obj.show
        let btnHide=obj.hide
        let show=true;
        if(btnShow){
          for(let attr in btnShow){
            if(btnShow.hasOwnProperty(attr) ){
              if(Object.prototype.toString.call(btnShow[attr]) === '[object Array]'){
                // 如果条件是个数组
                if(btnShow[attr].indexOf(item[attr])<0){
                  show=false
                  break
                }
              }else if( btnShow[attr]!==item[attr]){
                // 如果条件是个字符串
                show=false
                break
              }
            }

          }
        }
        if(btnHide){
          for(let attr in btnHide){
            if(btnHide.hasOwnProperty(attr)){

              if(Object.prototype.toString.call(btnHide[attr])==='[object Array]'){
                // 如果条件是个数组
                if(btnShow[attr].indexOf(item[attr])>=0){
                  show=false
                  break
                }
              }else if( btnHide[attr]===item[attr]){
                // 如果条件是个字符串
                show=false
                break
              }

            }
          }
        }
        return show
      },
      indexMethod(index) {
        return index+1 +(this.tableData.page-1)*this.pageParam.pageSize;
      },
      sortChange(obj){
        let order='';
        let sort='';
        if(obj.order && obj.prop) {
          sort=obj.prop
          if (obj.order.substr(0, 1) === 'a') {
            order='asc'
          }
          if (obj.order.substr(0, 1) === 'd') {
            order='desc'
          }
        }
        this.$emit('search',{order,sort});
      },
      handleButton(row,methods) {
        this.$emit('action',{'row':row,'methods':methods});
      },
      handleSizeChange(val) {
        // console.log(val)
        this.pageParam.pageSize=val
        this.pageParam.page=1
        this.$emit('search',{pageSize: val  ,page: 1});
      },
      handleCurrentChange(val) {
        // console.log(val)
        this.pageParam.page=val
        this.$emit('search',{page:val});
      },
      handleSelectionChange(val,ele) {
        this.$emit('selectChange',val,ele);
      }
    },
  }
</script>
