<template>
  <div class="importAndExport">
    <div class="project-name">
      <p>{{$route.matched[1].meta.parentTitle}} - {{ $route.matched[1].meta.title }}</p>
    </div>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="项目" name="project">
        <el-form :model="searchForm" @keyup.enter.native="getData" ref="searchForm" label-width="120px" size="mini">
          <el-row>
            <el-col :span="8">
              <el-form-item label="项目名称">
                <el-input type="text" v-model="searchForm.name">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-button class="export-project" type="primary" @click="getData">查询</el-button>
              <el-button @click="exportTO" type="primary" class="export-project">导出</el-button>
            </el-col>
          </el-row>
        </el-form>
        <el-table ref="multipleTable" :data="tableList" tooltip-effect="dark" style="width: 100%"
          @selection-change="handleSelectionChangeP">
          <el-table-column type="selection" width="55"> </el-table-column>

          <el-table-column label="名称" width="120">
            <template slot-scope="scope">
              <el-link class="table-link" @click.native.prevent="nodeHandle('edit', scope.row)"
                :type="currentRow && currentRow.id && scope.row.id && currentRow.id === scope.row.id ? 'primary' : ''">
                {{ scope.row.name }}
              </el-link>

            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" width="120" show-overflow-tooltip span="1">
          </el-table-column>
          <el-table-column prop="proxyServiceNum" label="代理服务数量" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="businessServiceNum" label="业务服务数量" show-overflow-tooltip>
          </el-table-column>
          <!-- <el-table-column
            prop="connectorNum"
            label="适配器数量"
            show-overflow-tooltip
          >
          </el-table-column> -->
          <el-table-column prop="flowNum" label="消息流数量" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="resourceFileNum" label="资源文件数量" show-overflow-tooltip>
          </el-table-column>
        </el-table>

        <el-pagination :page-size="page.pageSize" :current-page.sync="page.pageNum" background
          @current-change="getDataNext" :total="page.total" />
      </el-tab-pane>
      <el-tab-pane label="资源" name="souce">
        <div style="height:40px">
          <el-checkbox v-model="isXg">相关性</el-checkbox>
          <el-button @click="exportTOSouce" type="primary" class="export-project2">导出</el-button>
          <!-- <el-button @click="toggleSelection" type="primary" class="export-project" >导出</el-button> -->
        </div>
        <div class="table-wrapper">
          <el-table :data="tableData" style="width: 90%;margin-bottom: 20px;" border :key="loadingT"
            v-loading="loadingS" row-key="id" ref="relyTableListR" header-row-class-name="text-align:center"
            @row-click="handleClicksT" @selection-change="handleSelectionChange"
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
            <el-table-column type="selection" align="center" width="55">
              <template slot-scope="scope">
                <el-checkbox @change="value => handleSelectionChanges(value,scope.$index,scope.row)"
                  v-model="scope.row.isY"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="资源">
            </el-table-column>
            <el-table-column prop="ftype" align="center" label="类型" width="180">
              <template slot-scope="scope">
                <span v-if="scope.row.stype">{{scope.row.stype}}</span>
                <span v-else>{{scope.row.ftype}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="updateon" align="center" label="修改时间" width="180">
            </el-table-column>
            <el-table-column prop="refs" align="center" label="依赖" width="180">
              <template slot-scope="scope">
                <span v-if="scope.row.refs > 0" @click="toFlow(scope.row)"
                  style="color:blue">{{scope.row.refs}}Refs</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- <el-tree
          :data="tableData"
          :props="props"
          ref="tree"
          show-checkbox>
        </el-tree> -->
      </el-tab-pane>
    </el-tabs>
    <el-dialog :title="'引用'+connectorType" :close-on-click-modal="false" :visible.sync="dialogVisible" width="800px"
      top="5vh" append-to-body @close="closeDialog">
      <div class="">
        <el-table :data="relyTableList" border highlight-current-row height="400"
          style="width: 100%; margin-bottom: 10px" size="mini">
          <el-table-column prop="name" label="名称" align="center" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="projectName" label="项目" align="center" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="type" label="类型" align="center" show-overflow-tooltip>
            <!-- <template slot-scope="scope">
              <span v-if="scope.row.type">{{scope.row.type}}</span>
              <span v-else>{{types}}</span>
            </template> -->
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closeDialog">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { exportData, exportData2 } from '@/api/import_and_export' // 导出接口
import { getFormateDate } from '@/utils/common'
// import {
//   queryProjectList,
//   getProjectListDetail,
//   deleteProjectList
// } from '@/api/project_list'
import { queryProjectList, exportDatas } from '@/api/project_list'
import { proxyservicedepent, businessservicedependent, listflowdependenet } from '@/api/esb_service'
import EsbServiceListMixins from '@/mixins/esb_service_list_mixins'

export default {
  mixins: [EsbServiceListMixins],
  components: {},
  data() {
    return {
      // types: '',
      connectorType: '',
      relyTableList: [],
      loadingT: false,
      loadingS: false,
      dialogVisible: false,
      props: {
        children: 'children',
        label: 'name'
      },
      activeName: 'project',
      tableList: [],
      checkedList: [],
      projectList: [],
      isXg: false,
      exprtList: [],
      page: {
        pageNum: 0,
        pageSize: 10,
        total: 0
      },
      isProject: null,
      iop: null,
      treeData: [],
      tableData: []
    }
  },
  computed: {},
  created() { },
  mounted() {
    this.exportDatas()
  },
  watch: {
  },
  methods: {
    toFlow(row) {
      this.types = row.ftype
      switch (row.ftype) {
        case '业务服务':
          businessservicedependent(row.id).then(res => {
            this.dialogVisible = true
            let datas = []
            Object.keys(res.data).forEach(item => {
              res.data[item].forEach(items => {
                switch (item) {
                  case 'BUSINESS':
                    items.type = '业务服务'
                    break
                  case 'FLOW':
                    items.type = '消息流'
                    break
                  case 'PROXY':
                    items.type = '代理服务'
                    break
                  case 'CONNECTOR':
                    items.type = '适配器'
                    break
                }
              })
              datas = datas.concat(res.data[item])
            })
            this.relyTableList = datas
          })
          break
        case '代理服务':
          proxyservicedepent(row.id).then(res => {
            this.dialogVisible = true
            let datas = []
            Object.keys(res.data).forEach(item => {
              console.log(item)
              res.data[item].forEach(items => {
                switch (item) {
                  case 'BUSINESS':
                    items.type = '业务服务'
                    break
                  case 'FLOW':
                    items.type = '消息流'
                    break
                  case 'PROXY':
                    items.type = '代理服务'
                    break
                  case 'CONNECTOR':
                    items.type = '适配器'
                    break
                }
              })
              datas = datas.concat(res.data[item])
            })
            this.relyTableList = datas
          })
          break
        case '消息流':
          listflowdependenet(row.id).then(res => {
            this.dialogVisible = true
            let datas = []
            Object.keys(res.data).forEach(item => {
              res.data[item].forEach(items => {
                switch (item) {
                  case 'BUSINESS':
                    items.type = '业务服务'
                    break
                  case 'FLOW':
                    items.type = '消息流'
                    break
                  case 'PROXY':
                    items.type = '代理服务'
                    break
                  case 'CONNECTOR':
                    items.type = '适配器'
                    break
                }
              })
              datas = datas.concat(res.data[item])
            })
            this.relyTableList = datas
          })
          break
      }
    },
    closeDialog() {
      this.dialogVisible = false
    },
    handleClick(tab, event) {
      // console.log(tab, event);
    },
    handleClicks(row, column) {
      console.log(column)
      if ((row.ftype && row.ftype !== '') || row.children) {
        return
      }
      this.loadingS = true
      const vm = this
      const index = row.id.indexOf('=')
      const filters = [
        {
          key: 'level',
          opt: 'LIKE',
          type: 'S',
          value: 2
        },
        {
          key: 'project_id',
          opt: 'LIKE',
          type: 'S',
          value: row.id.substring(0, index)
        },
        {
          key: 'ftype',
          opt: 'LIKE',
          type: 'S',
          value: ''
        }
      ]
      switch (row.name) {
        case '业务服务':
          filters[2].value = '业务服务'
          vm.exportDatas(filters, row, column)
          break
        case '代理服务':
          filters[2].value = '代理服务'
          vm.exportDatas(filters, row, column)
          break
        case '资源文件':
          filters[2].value = '资源文件'
          vm.exportDatas(filters, row, column)
          break
      }
    },
    handleClicksT(row, column, isF) {
      if (row.children || row.ftype !== '项目') {
        return
      }
      this.loadingS = true
      const vm = this
      this.isProject = row.id
      const filters = [
        {
          key: 'level',
          opt: 'LIKE',
          type: 'S',
          value: 2
        },
        {
          key: 'project_id',
          opt: 'LIKE',
          type: 'S',
          value: row.id
        }
      ]
      vm.exportDatas(filters, row, column)
    },
    exportDatas(Efilters, row, column) {
      const vm = this
      if (!Efilters) {
        Efilters = [{
          key: 'level',
          opt: 'LIKE',
          type: 'S',
          value: 1
        }]
      }
      this.loadingS = true
      exportDatas({
        filters: Efilters,
        orderby: 'updateon',
        sort: 'desc',
        pageNum: 1,
        pageSize: 1000
      }).then(res => {
        this.loadingS = false
        if (Efilters.length > 1) {
          res.data.list.forEach(item => {
            item.isY = row.isY
            if (row.isY && vm.checkedList.findIndex(items => items.id === item.id) === -1) {
              vm.checkedList.push(item)
            }
            item.updateon = getFormateDate(item.updateon, 'yyyy-MM-dd hh:mm:ss')
          })
          row.children = res.data.list.filter(item => item.ftype !== '适配器')
          this.loadingT = !this.loadingT
        } else {
          res.data.list.forEach(item => {
            item.isY = false
            item.updateon = getFormateDate(item.updateon, 'yyyy-MM-dd hh:mm:ss')
          })
          this.treeData = res.data.list.filter(item => item.ftype !== '适配器')
          this.tableData = this.treeData
        }
      }).catch((e) => {
        this.loadingS = false
      })
    },
    async exportTO() {
      var that = this
      if (that.projectList.length === 0) {
        this.$message({
          message: '请选择要导出的数据！',
          type: 'info'
        })
        return
      }
      let str = `确认导出选择${that.projectList.length}个项目吗？`
      var ids = that.projectList.map((item) => item.id).join(',')
      var rt = await exportData([
        {
          id: 'bas.esb.console.migrate.service.impl.ESBMigrateService',
          name: 'ESB资源迁移',
          migrates: [
            {
              id: 'project',
              name: '项目',
              query: {
                filters: [
                  {
                    key: 'id',
                    value: ids,
                    opt: 'IN'
                  }
                ]
              }
              // subModule: [
              //   {
              //     id: 'businessService',
              //     name: '业务服务'
              //   }
              // ]
            }
          ]
        }
      ]).then(rt => {
        console.log(rt)
        this.tableLoading = false
        that.downloadFile(
          rt,
          '',
          'bas.esb.console.migrate.service.impl.ESBMigrateService.zip'
        )
      }).catch((e) => {
        console.log(rt)
        this.tableLoading = false
        that.downloadFile(
          e,
          '',
          'bas.esb.console.migrate.service.impl.ESBMigrateService.zip'
        )
        // return Promise.reject(e)
      })
    },
    async exportTOSouce() {
      var that = this
      if (that.checkedList.length === 0) {
        this.$message({
          message: '请选择要导出的数据！',
          type: 'info'
        })
        return
      }
      that.exprtList = []
      this.checkedList.forEach(item => {
        if (item.id.indexOf('=') === -1 && item.hasOwnProperty('ftype') && item.ftype !== '项目') {
          const ins = {
            projectId: item.projectId,
            souceId: item.id,
            type: item.ftype,
            stype: item.stype
          }
          that.exprtList.push(ins)
        }
      })
      const souceList = []
      that.exprtList.forEach(item => {
        const listChildren = {
          id: 'resource',
          name: that.isXg,
          query: {
            filters: [
              {
                key: 'project_id',
                value: item.projectId,
                opt: 'IN'
              }
            ]
          }
        }
        const subModules = []
        that.exprtList.forEach(itemP => {
          if (itemP.projectId === item.projectId) {
            const subModule = {
              id: 'proxyService',
              name: '业务服务',
              query: {
                filters: [
                  {
                    key: 'id',
                    value: itemP.souceId,
                    opt: 'IN'
                  }
                ]
              }
            }
            switch (itemP.type) {
              case '业务服务':
                subModule.id = 'businessService'
                break
              case 'sql构建器':
                subModule.id = 'sqlBuilderDtos'
                break
              case '代理服务':
                break
              case '消息流':
                subModule.id = 'flow'
                break
              case '资源文件':
                subModule.id = 'resource'
                subModule.query = {}
                subModule.query.fullFilters = [
                  {
                    logic: 'and',
                    filters: [
                      {
                        key: 'project_id',
                        value: itemP.projectId
                      }, {
                        key: 'type',
                        value: itemP.stype
                      }, {
                        key: 'id',
                        value: itemP.souceId
                      }
                    ]
                  }
                ]
                break
            }
            subModules.push(subModule)
          }
        })
        listChildren.subModule = subModules
        if (souceList.length > 0 && souceList.findIndex(souceItem => souceItem.query.filters[0].value === item.projectId) === -1) {
          souceList.push(listChildren)
        } else {
          if (souceList.length === 0) {
            souceList.push(listChildren)
          }
        }
        console.log(souceList.findIndex(souceItem => souceItem.query.filters[0].value === item.projectId))
      })
      // let str = `确认导出选择${that.exprtList.length}个资源吗？`
      var rt = await exportData([
        {
          id: 'bas.esb.console.migrate.service.impl.ESBMigrateService',
          name: 'ESB资源迁移',
          migrates: souceList
        }
      ]).then(res => {
        console.log(res, 'haishini')
        this.tableLoading = false
        that.downloadFile(
          res,
          '',
          'bas.esb.console.migrate.service.impl.ESBMigrateService.zip'
        )
      }).catch((e) => {
        console.log(e, '出来了')
        this.tableLoading = false
        that.downloadFile(
          e,
          '',
          'bas.esb.console.migrate.service.impl.ESBMigrateService.zip'
        )
        // return Promise.reject(e)
      })
    },
    async exportTOSouces() {
      var that = this
      if (that.checkedList.length === 0) {
        this.$message({
          message: '请选择要导出的数据！',
          type: 'info'
        })
        return
      }
      that.exprtList = []
      this.checkedList.forEach(item => {
        console.log(item)
        if (item.id.indexOf('=') === -1 && item.hasOwnProperty('ftype') && item.ftype !== '项目') {
          const ins = {
            souceId: item.id,
            type: item.ftype
          }
          that.exprtList.push(ins)
        }
      })
      const listChildren = [
      {
          name: 'proxyService',
          id: ''
        },
              {
          name: 'flow',
          id: ''
        },
        {
          name: 'businessService',
          id: ''
        },
        {
          name: 'resource',
          id: ''
        }
      ]
      that.exprtList.forEach(itemP => {
        console.log(itemP)
        switch (itemP.type) {
          case '业务服务':
            if (itemP.souceId) {
              if (listChildren[2].id) {
                listChildren[2].id += ','
              }
              listChildren[2].id += itemP.souceId
            }
            break
          case '代理服务':
            if (itemP.souceId) {
              if (listChildren[0].id) {
                listChildren[0].id += ','
              }
              listChildren[0].id += itemP.souceId
            }
            break
          case '消息流':
            if (itemP.souceId) {
              if (listChildren[1].id) {
                listChildren[1].id += ','
              }
              listChildren[1].id += itemP.souceId
            }
            break
          case '资源文件':
            if (itemP.souceId) {
              if (listChildren[3].id) {
                listChildren[3].id += ','
              }
              listChildren[3].id += itemP.souceId
            }
            break
          case 'sql构建器':
            if (itemP.souceId) {
              if (listChildren[4].id) {
                listChildren[4].id += ','
              }
              listChildren[4].id += itemP.souceId
            }
            break
        }
      })
      // let str = `确认导出选择${that.exprtList.length}个资源吗？`
      var rt = await exportData(listChildren).catch((e) => {
        this.tableLoading = false
        that.downloadFile(
          e,
          '',
          'bas.esb.console.migrate.service.impl.ESBMigrateService.zip'
        )
      })
    },
    async exportNew() {
      const rt = await exportData2().catch((e) => {
        return Promise.reject(e)
      })
      console.log(rt)
    },
    // 下载文件流
    downloadFile(data, type, fileName) {
      const blob = new Blob([data], { type: `${data.type};charset=utf-8` })
      // 获取heads中的filename文件名
      const downloadElement = document.createElement('a')
      // 创建下载的链接
      const href = window.URL.createObjectURL(blob)
      downloadElement.href = href
      // 下载后文件名
      downloadElement.download = fileName
      document.body.appendChild(downloadElement)
      // 点击下载
      downloadElement.click()
      // 下载完成移除元素
      document.body.removeChild(downloadElement)
      // 释放掉blob对象
      window.URL.revokeObjectURL(href)
    },
    // 获取列表
    async getData() {
      this.tableLoading = true
      // const rt = await queryProxyService({
      const rt = await queryProjectList({
        filters: [
          {
            key: 'name',
            opt: 'LIKE',
            type: 'S',
            value: this.searchForm.name
          }
        ],
        orderby: 'updateon',
        sort: 'desc',
        pageNum: this.page.pageNum,
        pageSize: this.page.pageSize
      }).catch((e) => {
        this.tableLoading = false
        return Promise.reject(e)
      })
      console.log(rt)
      if (rt.status === '200') {
        this.tableLoading = false
        this.tableList = rt.data.list.filter(item => item.ftype !== '适配器') || []
        this.treeList = this.tableList
        this.page.total = rt.data.total
        return Promise.resolve(rt)
      } else {
        this.tableLoading = false
      }
    },
    handleSelectionChanges(val, index, list) {
      if (val) {
        this.checkedList.push(list)
      } else {
        this.checkedList.splice(this.checkedList.indexOf(list), 1)
      }
      if (list.ftype === '项目') {
        if (list.children) {
          list.children.forEach(item => {
            item.isY = val
            if (val && item.isY) {
              this.checkedList.push(item)
            }
          })
        }
        if (!val) {
          JSON.parse(JSON.stringify(this.checkedList)).forEach((cItem, cindex) => {
            if (cItem.projectId && cItem.projectId === list.id) {
              console.log(cindex)
              this.checkedList.splice(this.checkedList.indexOf(cItem), 1)
            }
          })
        }
      } else {
        list.isY = val
        let ind
        this.tableData.forEach((item, tindex) => {
          if (item.id === list.projectId) {
            if (!item.isY) {
              item.isY = val
            } else {
              const test = this.checkedList.filter(item => {
                if (item.projectId && item.projectId === list.projectId) {
                  return item
                }
              })
              if (test.length === 0) {
                item.isY = val
              }
            }
            ind = tindex
          }
        })
        this.$set(this.tableData, ind, this.tableData[ind])
      }
      console.log(this.checkedList)
    },
    handleSelectionChange(list) {
      if (list.length === this.page.total) {
        return
      }
      let iop, ind
      const lists = JSON.parse(JSON.stringify(this.checkedList))
      console.log(list, lists)
      this.checkedList = list
      var that = this
      if (this.checkedList.length > 0 && (lists.length && list.length && lists.length > list.length)) {
        lists.map(function (item, index) {
          const inds = list.findIndex(items => item.id === items.id)
          if (inds === -1 && item.ftype === '项目') {
            ind = index
          }
        })
      }
      console.log(ind)
      if (ind && !list[list.length - 1].hasOwnProperty('children')) {
        console.log(123)
        lists[ind].children.map(item => {
          that.$refs.relyTableListR.toggleRowSelection(item, false)
        })
        // that.$nextTick(() => {
        //   that.loadingT = !that.loadingT
        // })
      } else {
        list.map(function (item, index) {
          if (item) {
            if (item.ftype === '项目' && item.hasOwnProperty('children')) {
              if (ind || list[list.length - 1].hasOwnProperty('children')) {
                if (lists.length === 0 || lists.findIndex(items => items.id === item.id) === -1) {
                  that.isProject = item.id
                }
                that.toggleSelection(item, 'Project')
              }
            } else if (item.ftype === '项目') {
              console.log(2)
              that.isProject = item.id
              that.handleClicksT(item, 'select', '12')
            } else if (!list[0].hasOwnProperty('children') && list[0].ftype !== '项目') {
              console.log(3)
              if (item.hasOwnProperty('children')) {
                iop = 1
              }
              if (iop !== 1) {
                console.log(45)
                that.deltoggleSelection(item, 'Project?')
              }
            } if (item.ftype !== '项目') {
              // that.toggleSelection(item)
            }
          }
        })
      }
    },
    handleSelectionChangeP(list) {
      this.projectList = list
    },
    getDataNext(val) {
      // 分页
      this.page.pageNum = val
      this.getData()
    }
  }
}
</script>
<style type="text/scss" lang="scss" scoped>
.importAndExport {
  background: #ffffff;
  margin: 10px 10px;
  position: relative;
  padding: 20px;

  .centers {
    text-align: center;
  }

  .export-project {
    float: left;
    margin: 2.75px 20px;
  }

  .export-project2 {
    float: right;
    margin: 0 20px;
    position: fixed;
    right: 40px;
  }

  .el-pagination {
    padding-top: 20px;
  }
  .el-table{
    overflow-y: auto;
    height: 500px;
  }
}
</style>>
