<template>
  <div class="basic__layout__panel">
    <div>
      <div class="layout-header-panel container normal-panel">
        <div class="flex-align-center flex-between">
          <div class="normal-margin flex-align-center">
            <div v-if="activeApp" style="font-size:26px;font-weight:300;flex-shrink:0">{{$t(customTitle ? customTitle : activeApp.meta.title)}}&nbsp;
              <!-- <i v-if="!customTitle" @click="addToAsideBar" style="color:#999" :class="showAppCollection()?'el-icon-star-on collection':'el-icon-star-off'"></i> -->
              <div v-if="!customTitle" style="display:inline">
                <img width="20" v-if="showAppCollection()" src="@/assets/icons/incoll.svg" alt="">
                <img width="20" v-else src="@/assets/icons/uncoll.svg" @click="addToAsideBar" alt="">
              </div>
            </div>
            <div style="margin:0 8px"></div>

            <div class="flex-align-center flex-wrap" style="line-height: 40px;">
              <div v-if="oldFormPath || formPath">
                <cpAdd v-if="tool.checkAuth($route.name,'insert')" :formPath="formPath" :oldFormPath="oldFormPath" @onAddSuccess="listData(param.content.pageNumber = 1)"></cpAdd>
              </div>
              <slot name="titleLight"></slot>
              <!-- <el-button-group v-if="tool.checkAuth($route.name,'delete')" class="inline-16">
                <el-button :type="selection.length === 0?'':'primary'" :disabled="selection.length === 0" size="small" @click="deleteData">{{$t('删 除')}}</el-button>
              </el-button-group> -->
              <!-- <el-button class="inline-16" size="small" type="primary" plain>{{$t('导 入')}}</el-button> -->
              <reportCenter :btnName="$t('报 表')" class="inline-16" position="detail" size="small" :data="reportCenterLsit.filter(item => item.type == 'datainfo')" v-if="reportCenterLsit.filter(item => item.type == 'datainfo').length > 0 && systemappid != 163">
                <template v-slot:print="scope2">
                  <el-button @click="printBtn({},scope2.data)" type="text" size="mini">{{$t('打 印')}}</el-button>
                </template>
              </reportCenter>
              <slot name="titleRight"></slot>
            </div>
          </div>
          <div class="normal-margin" style="flex-shrink:0">
            <setColumn :layout="layout" @changeColumn="changeColumn"></setColumn>
            <setFixed :data="tableLayout" @onFixedClick="onFixedClick"></setFixed>
            <i class="el-icon-refresh" @click="listData(param.content.pageNumber = 1,param.content.where.condition = '')"></i>
          </div>
        </div>
        <div class="flex-align-stretch" style="min-width:800px">
          <slot name="custom"></slot>
          <el-input v-if="!hideSearch" style="width:200px;" :placeholder="$t('搜索')" :suffix-icon="param.content.where.condition?param.content.where.condition.length > 0?'':'':'el-icon-search'" v-model="param.content.where.condition" @keyup.native.enter="listData(param.content.pageNumber = 1)" @clear="clearSearchValue" size="small" class="input-with-select inline-16 layout_search__panel" clearable>
          </el-input>
          <slot name="custom-right"></slot>
        </div>
      </div>
      <div class="normal-panel " style="padding-right:16px;">
        <div style="display: flex;">
          <slot name="tableLeft"></slot>
          <div style="flex: 1;width: 70%" v-if="listType === 'table' && refreshTable">
            <tableTemp height="calc(100vh - 315px)" ref="table" :layout="tableLayout" :tableName="tableName" :custom="true" :data="list" :fixRightData="fixRightData" :fixLeftData="fixLeftData" @headerSearch="onHeaderSearch" @checkboxCallBack="checkboxCallBack">
              <template v-slot:temp="scope">
                <slot name="tempChild" :data="scope.data"></slot>
              </template>

              <template v-slot:customcol="scope">
                <slot :data="scope" name="tbList"></slot>
              </template>

              <template v-slot:opreation="scope">

                <drawerTemp class="inline-16" v-if="detailPath && checkRowStatus(scope.data.status)" :data="scope.data" :detailPath="detailPath" :idName="idName" @onSuccess="listData" @delSuccess="delSuccess"></drawerTemp>
                <slot :data="scope" name="tbOpreation"></slot>
                <!--systemappid != 163 排除报表应用-->
                <reportCenter class="inline-16"  size="mini" :data="reportCenterLsit.filter(item => item.type == 'printinfo')" v-if="reportCenterLsit.filter(item => item.type == 'printinfo').length > 0 && systemappid != 163">
                  <template v-slot:print="scope2">
                    <el-button @click="printBtn(scope.data,scope2.data)" type="text" size="mini">{{$t('打 印')}}</el-button>
                  </template>
                </reportCenter>

              </template>
            </tableTemp>
            <div style="display:flex;align-items:center;flex-direction:row-reverse;justify-content:space-between">
              <div v-if="!hidePagination" class="normal-panel" style="text-align:right;padding-top: 16px">
                <el-pagination
                    background
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[20, 50, 100, 200]"
                    :page-size="100"
                    layout="total,sizes, prev, pager, next, jumper"
                    :total="total">
                </el-pagination>
              </div>
              <slot name="footerLeft"></slot>
            </div>

          </div>
        </div>


      </div>
    </div>
    <drawer :drawerWidth="drawerWidth" @onSuccess="onSuccess"></drawer>
  </div>
</template>

<script>

import {mapGetters} from 'vuex'
export default {
  componentName:'normalTable',
  props:['tableName','idName','tableData','apiId','formPath','oldFormPath','options','autoQuery','detailPath','customTitle','hidePagination','hideSearch','statusHideDetailBtn','specialKey','drawerWidth','isExport'],
  components:{
    tableTemp: () => import('./modules/table.vue'),
    setColumn: () => import('./modules/setColumn.vue'),
    cpAdd: () => import('./modules/cpAdd'),
    cpEdit: () => import('./modules/cpEdit'),
    setFixed: () => import('./modules/setFixed'),
    drawerTemp:() =>  import('./drawerDetail/index1'),
    excel:() =>  import('@/components/export_excel/index.vue'),
    cardTemp:() => import('./modules/cardList.vue'),
    drawer:() =>  import('./drawerDetail/drawer'),
    reportCenter:() =>  import('./reportCenter/index'),

  },
  computed:{
    ...mapGetters({
      activeApp:'activeApp',
      searchValue:'searchValue',
      menuApp:'menuApp',
    })
  },
  data () {
    return {
      listType:'table',
      routerName:'',
      exports:true,
      select:'',
      param:{
        content:{
          "isExport":0,
          "pageNumber": 1,
          "pageSize": 100,
          "where": {
            "condition": "",
            "tablefilter":{}
          }
        }
      },
      layout:[],
      fixRightData:['operation'],
      fixLeftData:[],
      tableLayout:[],
      selection:[],
      list:[],
      total:0,
      currentPage:0,
      refreshTable:true,
      title:'',
      name:'',
      systemappid: (() => { try { return JSON.parse(sessionStorage.getItem('activeApp')).systemappid } catch(e) { return '' } })(),
      reportCenterLsit:[]
    }
  },
  methods:{
    clearSearch () {
      this.$store.state.searchValue = ''
      this.listData(this.param.content.pageNumber = 1)
    },
    onSuccess(){
      this.$emit('onSuccess')
    },
    async listData () {
      this.searchValue?this.param.content.where.condition = this.searchValue:''
      this.param.id = this.apiId.query
      const res = await this.$api.requested(this.param)
      this.list = res.data
      this.total = res.total
      this.currentPage = res.pageNumber
      /* 请求的数据暴露出去 二次处理 */
      this.$emit('listData',this.list)

      // 保存一下列表数据用于翻页
      this.$store.dispatch('saveListData',{listData:this.list,param:this.param,pageTotal:res.pageTotal})
    },
    delSuccess(){
      console.log("删除成功")
    },
    selectChange () {
      this.param.content.pageNumber = 1
      this.param.content.where.status = this.select
      this.listData()
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.param.content.pageSize = val
      this.listData()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.param.content.pageNumber = val
      this.listData()
    },
    checkboxCallBack (val) {
      this.selection = val
      this.$emit('checkboxCallBack',val)
    },
    deleteData () {
      this.$confirm(this.$t('确定删除这些数据吗') + '?', this.$t('提示'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(async () => {
        let param = {
          "id": this.apiId.del,
          "content":{}
        }
        if (this.idName instanceof Array) { //判断传入的类型是多个还是单个idname
          let obj = {}
          this.idName.forEach(e=>{
            obj[e] = ''
          })
          param.content[`${this.idName[0]}s`] = this.selection.map(e=>{
            Object.keys(obj).map((key,item)=>{
              obj[key] = e[key]
            })
            return obj
          })
        } else {
          param.content[`${this.idName}s`] = this.selection.map(e=>{
            return e[this.idName]
          })
        }
        const res = await this.$api.requested(param)
        this.tool.showMessage(res,()=>{
          this.listData()
        })
      }).catch((err) => {

        console.log(err)
        this.$message({
          type: 'info',
          message: this.$t('已取消删除')
        });
      });
    },
    onFixedClick (right,left) {
      this.fixRightData = right
      this.fixLeftData = left
      this.$refs['table'].checkFixed()
    },
    // 筛选列
    changeColumn (arr) {
      this.tableLayout = arr
      this.refreshTable= false
      setTimeout(() => {
        this.refreshTable= true
      }, 0);
    },
    // 创建快捷应用
    async addToAsideBar () {
      const res = await this.$api.requested({
        "classname": "sysmanage.develop.userauthforweb.userauth",
        "method": "create_usershortcuts",
        "content": {
          "systemappid":this.activeApp.systemappid
        }
      })
      this.$store.dispatch('setAppMenu')
    },
    showAppCollection () {
			let _isSame = this.menuApp.some(m=>this.activeApp.name === m.systemapp)
			return _isSame
		},
    checkRowStatus (status) {
      if (this.statusHideDetailBtn) {
        let _isSame = this.statusHideDetailBtn.some(m=>status === m)
			  return !_isSame
      } else {
        return true
      }

		},
    onHeaderSearch (key,val) {
      this.param.content.pageNumber = 1
      this.param.content.where.tablefilter[key] = val
      this.listData()
    },
    /* 获取是否有报表数据 */
    async getSystemAppid () {
      let res = await this.$api.requested({
        "id":20221213094401,
        "content": {
          "systemappid":this.systemappid,
        }
      })
      this.reportCenterLsit = res.data
      console.log(res,'报表数据');
    },
    async printBtn (data,data2) {
      /* 报表类型 type = datainfo */
      if (!Object.keys(data).length) data[this.idName] = 0

      let res = await this.$api.requested({
        "id":20221213094501,
        "content": {
          sys_reportid:data2.sys_reportid,
          dataid:data[this.idName]
        }
      })
      this.tool.showMessage(res,() => {
        window.open(this.tool.getBaseUrl() + res.data + `&${this.idName}=${data[this.idName]}`)
      })
    },
    clearSearchValue () {
      this.$store.dispatch('clearSearchValue')
      this.listData(this.param.content.pageNumber = 1)
    }
  },
  watch:{
  },
  mounted () {
    this.autoQuery === false?'':this.listData()
    this.isExport !== false ? this.exports = true : this.exports = false
    console.log(process.env)
  },
  created () {
    this.$emit('listCreate',this.param)
    try {
      this.routerName = this.$route.meta.title
      this.layout = this.tool.tabelCol(this.$route.name)[this.tableName].tablecols
      this.tableLayout = this.layout
      this.getSystemAppid()
    } catch (error) {
      console.log(error)
    }

  }
}

</script>
<style>
.layout_search__panel{
  align-items: center;
}
.layout-header-panel .el-input-group__append, .el-input-group__prepend{
  background-color: #fff !important;
  color: #999 !important;
  border: 1px solid #dcdfe6 !important;
  cursor: pointer;
}
.layout-header-panel .el-input--small .el-input__icon{
  height: 32px !important;
}
</style>
<style scoped>

/* .basic__layout__panel{
  padding: 16px 0;
} */
.card__list{
  display: flex;
}
.collection{
  color: orange !important;
  flex-direction: row-reverse;
}
.flex-wrap {
  flex-wrap: wrap;
}
</style>
