<template>
  <div v-if="refreshPage" style="min-width:1200px">
    <div style="margin:10px 10px 0 10px;border-radius:5px;position:relative" class="container normal-panel sticky" @click="closeTags">
      <div class="flex-align-start flex-between normal-margin" style="flex-wrap:nowrap">
        <div>
          <p class="main_title mt-10">{{titleText?titleText:'##'}}</p>
          <tagTemp v-if="activeApp.isdatatag" ref="tag" :ownertable="ownertable?ownertable:idname.slice(0, this.idname.length - 2)" @onSuccess="onSuccess" @sysTag="sysTag"></tagTemp>
        </div>
        <div class="flex-align-center" style="flex: 1 0 auto;  justify-content: flex-end;">
          <cpEdit v-if="tool.checkAuth($route.name,'update')" :formPath="formPath" :oldFormPath="oldFormPath" :data="editData" btnType="default" @onAddSuccess="onSuccess"></cpEdit>
          <!-- 打印 -->
          <reportCenter size="mini" position="detail" class="inline-16" :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($route.query.id,scope2.data)" type="text" size="mini">打 印</el-button>
            </template>
          </reportCenter>

          <div>
            <slot name="customOperation"></slot>
          </div>
          <el-button v-if="tool.checkAuth($route.name,'delete') && delApiId" :type="checkDisabled()?'':'primary'" class="inline-16" size="mini" :disabled="checkDisabled()" @click="deleteData">删 除</el-button>
         <div v-if="!pageChange">
            <el-button size="mini" icon="el-icon-arrow-left" @click="previous()"></el-button>
            <el-button size="mini" @click="next()"><i class="el-icon-arrow-right"></i></el-button>
          </div>
        </div>
      </div>
      <div>
        <slot name="d_head"></slot>
      </div>
      <div v-show="isTop">
        <el-descriptions :column="5" size="mini">
          <el-descriptions-item label-class-name="my-label-layout" content-class-name="my-content" v-for="item in mainAData" :key="item.index" :label="item.label">
            <span v-if="item.label === '关联应用数据'" @click="onGoto(item,item.index)" :style="item.style?item.style():''">{{item.value !== ''?item.value:'--'}}</span>
            <span v-else :style="item.style?item.style():''">{{item.value !== ''?item.value:'--'}}</span>
          </el-descriptions-item>
        </el-descriptions>
        <el-descriptions :column="1" size="mini">
          <el-descriptions-item label-class-name="my-label-layout" content-class-name="my-content" v-for="item in mainAData2" :key="item.index" :label="item.label">
            <span :style="item.style?item.style():''">{{item.value !== ''?item.value:'--'}}</span>
          </el-descriptions-item>
        </el-descriptions>
        <slot name="headerBottom"></slot>
      </div>

      <span @click="isTop=!isTop" style="color:#3874f6;position:absolute;right:10px;bottom:10px;cursor: pointer;">
        <i :class="isTop ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
        {{ isTop ? '收起' : '展开' }}
      </span>
    </div>
    <div style="box-sizing: border-box;padding:10px">
      <el-row class="flex-align-stretch no-wrap" :gutter="activeApp.isdatateam?10:activeApp.isdatafollowup?10:0">
        <el-col style="flex:1 0 auto;" :span="activeApp.isdatateam?18:activeApp.isdatafollowup?18:24">
          <slot name="customBefore"></slot>
          <tabTemp :status="status" :tabs="tabs" :editData="editData" :idname="idname" :ownertable="ownertable?ownertable:idname.slice(0, this.idname.length - 2)" @onTabClick="onTabClick">
            <div :slot="'slot' + index" v-for="(tab,index) in tabs" :key="tab.index">
              <slot :name="'slot' + index"></slot>
            </div>
          </tabTemp>
          <slot name="custom"></slot>
        </el-col>
        <el-col v-if="collapse" style="width:400px;" :span="6">
          <taskTemp v-if="activeApp.istask" :status="status" :ownertable="ownertable?ownertable:idname.slice(0, this.idname.length - 2)">
            <el-button slot="collapse" type="text" icon="el-icon-s-unfold" class="inline-16" @click="onCollapse"></el-button>
          </taskTemp>
          <group v-if="activeApp.isdatateam" :status="status" ref="group" style="margin-bottom:10px" :justsaler="justsaler" :ownertable="ownertable?ownertable:idname.slice(0, this.idname.length - 2)" @onSuccess="onSuccess" @teamList="teamList">
            <el-button slot="collapse" type="text" icon="el-icon-s-unfold" class="inline-16" @click="onCollapse"></el-button>
          </group>
          <follow-up v-if="activeApp.isdatafollowup" :status="status" ref="follow" :ownertable="ownertable?ownertable:idname.slice(0, this.idname.length - 2)">
            <el-button slot="collapse" type="text" icon="el-icon-s-unfold" class="inline-16" @click="onCollapse"></el-button>
          </follow-up>
        </el-col>
        <div v-else style="text-align-center" class="container normal-panel">
          <el-button slot="collapse" type="text" icon="el-icon-s-fold" @click="onCollapse"></el-button>
        </div>

      </el-row>
    </div>

  </div>
</template>

<script>
import cpEdit from '../modules/cpEdit.vue'
import followUp from './modules/followUp/followUp.vue'
import tagTemp from './modules/tags/tag.vue'
import tabTemp from './modules/tabs/tab.vue'
import group from './modules/group/group.vue'
import taskTemp from './modules/task/index.vue'
import reportCenter from '../reportCenter/index'
import {mapGetters} from 'vuex'
export default {
  props:['titleText','mainAreaData','turnPageId','delApiId','idname','ownertable','formPath','oldFormPath','editData','tags','tabs','statusCheck','pageChange','justsaler','mainData','status'],
  data () {
    return {
      isTop:true,
      routerName:'',
      rowindex:0,
      total:0,
      param:{
        "id": '',
        "content": {
          "isExport":false,
          "pageNumber": 1,
          "pageSize": 1,
          "nocache": true,
          "where": {
            "condition": ""
          }
        }
      },
      collapse:true,
      refreshPage:true,
      reportCenterLsit:[],
      systemappid:JSON.parse(sessionStorage.getItem('activeApp')).systemappid,
    }
  },
  computed:{
    mainAData () {
      try {
        let data = this.mainAreaData.filter(e=>{
          if(e.label !== '备注') {
            return e
          }
        })
        return data
      } catch (error) {

      }

    },
    mainAData2 () {
      try {
        let data = this.mainAreaData.filter(e=>{
          if(e.label == '备注') {
            return e
          }
        })
        return data
      } catch (error) {

      }

    },
    ...mapGetters({
      activeApp:"activeApp",
      svlistData:'svlistData'
    })
  },
  components:{
    cpEdit,
    followUp,
    group,
    tagTemp,
    tabTemp,
    taskTemp,
    reportCenter
  },
  methods:{
    // async queryData (pageNumber) {
    //   this.$emit('updateParam',this.param)
    //   this.param.id = this.turnPageId
    //   this.param.content.pageNumber = pageNumber
    //   const res = await this.$api.requested(this.param)
    //   this.total = res.total
    //   this.$refs['tag']?this.$refs['tag'].queryTag():''
    //   this.refresh()
    // },
    async nextData(param,fn) {
      console.log('执行')
      this.rowStatus = null
      const res = await this.$api.requested(param)
      this.$store.dispatch('saveListData',{listData:res.data,param:param,pageTotal:res.pageTotal})
      fn?fn():''
    },
    /* 获取是否有报表数据 */
    async getSystemAppid () {
      let res = await this.$api.requested({
        "id":20221213094401,
        "content": {
          "systemappid":this.systemappid,
        }
      })

      this.reportCenterLsit = res.data || []
      console.log('报表',this.reportCenterLsit);
    },
    async printBtn (data,data2) {
      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}`)
      })
    },
    async next () {
      const rs = await this.checkPaginationData()
      if (rs == 0 && this.svlistData.listData.length == 1) return false
      if (rs == 1 && this.svlistData.param.content.pageNumber == this.svlistData.pageTotal) return false
      let fun = (rs) =>{
        let nowId = this.$route.query.id
        let changeId = ''
        if (rs == 1) {
          changeId = this.svlistData.listData[0][this.idname]
        } else {
          this.svlistData.listData.forEach((e,index)=>{
            if (e[this.idname] == nowId) {
              changeId = this.svlistData.listData[index + 1][this.idname]
            }
          })
        }
        this.$emit('pageChange',changeId,this.idx)
        this.refresh()
      }
      if (rs == 1) {
        this.svlistData.param.content.pageNumber ++
        this.nextData(this.svlistData.param,(rs)=>{
          fun(1)
        })
      } else {
        fun()
      }
    },
    async previous () {
      const res = await this.checkPaginationData()
      if (res == 0 && this.svlistData.param.content.pageNumber == 1) return false
      const fun = (rs)=>{
        let nowId = this.$route.query.id
        let changeId = ''

        if (rs == 0) {
          changeId = this.svlistData.listData[this.svlistData.listData.length - 1][this.idname]
        } else {
          this.svlistData.listData.forEach((e,index)=>{
            if (e[this.idname] == nowId) {
              changeId = this.svlistData.listData[index - 1][this.idname]
            }
          })
        }
        this.$emit('pageChange',changeId,this.idx)
        this.refresh()
      }
      if (res == 0) {
        this.svlistData.param.content.pageNumber --
        this.nextData(this.svlistData.param,()=>{
          fun(0)
        })
      } else {
        fun()
      }
    },
    onSuccess () {
      this.$emit('onEditSuccess')

    },
    deleteData () {
      this.$confirm('确定删除当前数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let param = {
          "id": this.delApiId,
          "content":{}
        }
        if (this.idname instanceof Array) { //判断传入的类型是多个还是单个idname
          let obj = {}
          this.idname.forEach(e=>{
            obj[e] = ''
          })
          param.content[`${this.idname[0]}s`] =  [Object.keys(obj).map((key,item)=>{
            obj[key] = this.editData[key]
          })]
        } else {
          param.content[`${this.idname}s`] = [this.editData[this.idname]]
        }
        const res = await this.$api.requested(param)
        this.tool.showMessage(res,()=>{
          this.$store.dispatch('changeDetailDrawer',false)
        })
      }).catch((err) => {

        console.log(err)
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    checkDisabled () {
      if (this.statusCheck) {
        let _isSame = this.statusCheck.some(item=>item.value === this.editData[item.key])
        return _isSame
      } else {
        return false
      }
    },
    onTabClick () {
      this.$emit('onTabClick')
    },
    onCollapse () {
      this.collapse?this.collapse = false:this.collapse = true
    },
    refresh () {
      this.refreshPage = false
      setTimeout(() => {
        this.refreshPage = true
      }, 10);
    },
    refreshTag () {
      this.$refs.tag.queryTag()
    },
    closeTags() {
      this.$refs.tag?this.$refs.tag.closeTag():''
    },

    checkPaginationData () {
      return new Promise((reslove,reject)=>{
        let id = this.$route.query.id
        let n = 0
        this.svlistData.listData.filter((e,index)=>{
          if (e[this.idname] == id){

            n = index
          }
        })
        if (n == 0) {
          reslove(0)
        } else if (n == this.svlistData.listData.length - 1) {
          reslove(1)
        } else {
          reslove(-1)
        }
      })
    },

    sysTag(val){
      this.$emit('sysTag',val)
    },


    /*任务页面跳转*/
    onGoto(row,index){
      let path = this.mainData.systemapp[0].apppath_index
      let route = this.$route
      if (route.path !== path.slice(1)){
        this.oldRoute = {path:route.path,query:route.query}
        this.$store.dispatch('setHistoryRouter',this.oldRoute)
      }
      this.$router.push({
        path:path,
        query:{
          id:this.mainData.ownerid,
          rowindex:this.mainData.rowindex
        }
      })
    },
    /*任务协助人*/
    teamList(val){
      this.$emit('teamList',val)
    }
  },
  mounted () {
    // this.checkPaginationData()
    this.idx = this.$route.query.rowindex

  },
  created () {
    this.$emit('detailCreate',this.param)
    this.routerName = this.$route.meta.title
    this.rowindex = Number(this.$route.query.rowindex)
    this.getSystemAppid()
  },
  watch:{
    mainAreaData () {
      // console.log(this.mainAData,'mainAData')
      // this.checkPaginationData()
    }
  }
}

</script>
<style>
.detail__head__label{
  display: inline-block;
  width: 70px;
}
.my-label-layout{
  font-size: 14px;
  color: #999;
}
</style>
<style scoped>
.appname{
  display: inline;
  background: #FA8C19;
  color:#fff;
  border-radius: 4px;
  padding: 2px 10px;
  font-size: 12px;
}
.my-tabs{
  background:#eeeeee
}
.sticky{
  position: sticky;
  top:0;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
}
.no-wrap{
  flex-wrap:nowrap !important;
}
.main_title{
  font-size:30px;
  font-weight:300;
  margin-right:16px;
  line-height: 32px;
}
</style>
