<template>
  <div class="importAndExport">
    <div class="project-name">
      <p>{{$route.matched[1].meta.parentTitle}} - {{ $route.matched[1].meta.title }}</p>
    </div>
    <!-- 目前已废弃 2021.02.05 -->
    <!-- <div class="list-img">
                <ul>
                    <li v-for="(item,index) in imgArr" :key="index">
                        <img :src="item.path" alt="" >
                        <a @click="todel(index)"></a>
                    </li>
                    <li>
                        <div class="addImg" >
                            <input  type="file"  @change="fileChange($event)"  accept=".zip">
                        </div>
                    </li>
                </ul>
            </div>
            <el-button @click="importData" type="primary" class="export-project" icon="el-icon-search">导入配置</el-button> -->

    <el-upload
      class="upload-demo"
      ref="upload"
      action="test"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :file-list="fileList"
      :before-remove="beforeRemove"
      :on-change="handleProgress"
      :limit='1'
      :before-upload="beforeUpload"
      :http-request="importDatas"
      :auto-upload="false">
      <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
      <!-- <el-button style="margin-left: 10px;" size="small" type="success" @click="importData">导入配置</el-button> -->
      <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">导入配置</el-button>
      <div slot="tip" class="el-upload__tip">请选择从OSB导出的jar文件</div>
      <!-- <div>
        批量发布： <el-radio-group v-model="isPulic">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
      </div> -->
    </el-upload>
    <div class="table-wrapper">
      <el-table
        :data="tableDataS"
        style="width: 80%;margin-bottom: 20px;"
        row-key="id"
        border
        default-expand-all
        :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="action" label="操作" width="100"></el-table-column> -->
          <el-table-column prop="types" align="center" label="类型" width="180"></el-table-column>
          <el-table-column prop="refs" align="center" label="依赖" width="180">
            <template slot-scope="scope" >
              <el-button v-if="scope.row.refs > 0" type="text">{{scope.row.refs}}Refs</el-button>
            </template>
          </el-table-column>
      </el-table>
    </div>
    <SelectArea v-model="domainDialog" :connectorId="domainid" @confirm="getArea" />
  </div>
</template>
<script>
import SelectArea from '@/views/esb_service/global_variable/SelectArea'
import { importDatas } from '@/api/import_and_export'// 导出接口
import { publishByList } from '@/api/esb_service'// 导出接口
import jsZip from 'jszip'
export default {
  components: {
    SelectArea
  },
  data() {
    return {
      domainDialog: false,
      isPulic: false,
      domainid: '',
      msg: '',
      domainAddRow: {
        domainInfos: [],
        connectorInfos: []
      },
      domainRow: {
        businessData: [],
        connerctorData: []
      },
      fileList: [],
      checkedList: [],
      blobData: null,
      imgArr: [],
      isEx: 0,
      tableDataS: [],
      tableData: []
    }
  },
  computed: {},
  created() {},
  watch: {
    fileList(val) {
      // console.log(val)
    }
  },
  methods: {
    getArea(data) {
      this.domainid = data.id
      this.$refs.upload.submit()
    },
    // 选择文件
    handleSelectionChanges(val, index, list) {
      console.log(val, index, list)
      if (val) {
        this.checkedList.push(list)
      } else {
        this.checkedList.splice(this.checkedList.indexOf(list), 1)
      }
      if (list.typex === '项目') {
        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)
            }
            if (!cItem.isY) {
              console.log(this.checkedList)
              this.checkedList.splice(this.checkedList.indexOf(cItem), 1)
            }
          })
        }
      } else {
        list.isY = val
        let ind
        this.tableDataS.forEach((item, index) => {
          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 = index
          }
          if (list.url && item.name === list.url.split('/')[0]) {
            console.log(index)
            console.log(JSON.parse(JSON.stringify(this.tableDataS)))
            ind = index
          }
        })
        this.$set(this.tableDataS, ind, this.tableDataS[ind])
      }
      console.log(this.checkedList, this.tableDataS)
    },
    getFile(event) {
      var file = event.target.files
      for (var i = 0; i < file.length; i++) {
        // 上传类型判断
        var imgName = file[i].name
        var idx = imgName.lastIndexOf('.')
        if (idx !== -1) {
          var ext = imgName.substr(idx + 1).toUpperCase()
          ext = ext.toLowerCase()
          if (ext !== 'jpg' && ext !== 'png' && ext !== 'bmp' && ext !== 'gif') {

          } else {
            this.imgArr.push(file[i])
          }
        } else {

        }
      }
    },
    // 转换blob
    fileChange(e) {
      const evt = e || window.event
      const file = evt.target.files[0]
      const reader = new FileReader()
      const rs = reader.readAsArrayBuffer(file)
      let blob = null
      reader.onload = (e) => {
        if (typeof e.target.result === 'object') {
          blob = new Blob([e.target.result])
        } else {
          blob = e.target.result
        }
        this.blobData = blob
      }
      console.log(rs)
    },
    // 上传
    async importDatas() {
      const that = this
      // var file = new File([this.blobData], "bas.esb.console.migrate.service.impl.ESBMigrateService.zip", {
      //   type: "application/x-zip-compressed",
      // })
      // console.log(file)
      const listChildren = [
        {
          name: 'proxyService',
          id: ''
        },
        {
          name: 'flow',
          id: ''
        },
        {
          name: 'businessService',
          id: ''
        },
        {
          name: 'resource',
          id: ''
        },
        {
          name: 'connector',
          id: ''
        },
        {
          name: 'domainInfo',
          domainInfos: []
        },
        {
          name: 'connectorInfo',
          connectorInfos: []
        }
      ]
      const jarList = []
      const ids = []
      var fm = new FormData()
      fm.append('file', this.blobData)
      fm.append('domainId', this.domainid)
      if (this.blobData.name.indexOf('.jar') !== -1) {
        that.checkedList.forEach(itemP => {
          if (itemP.url) {
            jarList.push(itemP.url)
          }
        })
        console.log(jarList)
        fm.append('selectedJson', jarList)
      } else {
        that.checkedList.forEach(itemP => {
          if (itemP.status === '未发布' && itemP.typex === '代理服务') {
            ids.push(itemP.id)
          }
          if (itemP.typex !== '项目') {
            switch (itemP.typex) {
              case '业务服务':
                if (itemP.id) {
                  if (listChildren[2].id) {
                    listChildren[2].id += ','
                  }
                  listChildren[2].id += itemP.id
                }
                break
              case '代理服务':
                if (itemP.id) {
                  if (listChildren[0].id) {
                    listChildren[0].id += ','
                  }
                  listChildren[0].id += itemP.id
                }
                break
              case '消息流':
                if (itemP.id) {
                  if (listChildren[1].id) {
                    listChildren[1].id += ','
                  }
                  listChildren[1].id += itemP.id
                }
                break
              case '资源文件':
                if (itemP.id) {
                  if (listChildren[3].id) {
                    listChildren[3].id += ','
                  }
                  listChildren[3].id += itemP.id
                }
                break
              case '适配器':
                if (itemP.id) {
                  if (listChildren[4].id) {
                    listChildren[4].id += ','
                  }
                  listChildren[4].id += itemP.id
                }
                break
            }
          }
        })
        listChildren[listChildren.length - 2].domainInfos = this.domainAddRow.domainInfos
        listChildren[listChildren.length - 1].connectorInfos = this.domainAddRow.connectorInfos
        console.log(listChildren)
        fm.append('selectedJson', JSON.stringify(listChildren))
      }
      await importDatas(fm).then(res => {
        this.tableDataS = []
        if (res.status === '200') {
          that.$message({
            message: `上传成功`,
            type: 'success'
          })
        } else {
          this.msg = ''
          res.data.forEach(item => {
            this.msg += item.message
          })
          that.$message({
            message: `${this.msg}`,
            type: 'error'
          })
        }
      }).catch(e => {
        console.log(e)
        if (e.status === '200') {
          that.$message({
            message: `上传成功`,
            type: 'success'
          })
          that.$confirm('是否将导入成功的自动发布', '提示', {
            confirmButtonText: '是',
            cancelButtonText: '否',
            type: 'warning'
          }).then(() => {
            publishByList(ids).then(res => {
              // let sucT = 0
              // let sucF = 0
              // res.data.forEach(item => {
              //   if (item.success) {
              //     sucT++
              //   } else {
              //     sucF++
              //   }
              // })
              // this.$message.warning(`发布成功${sucT},发布成功${sucF}`)
              let ind = true
              let inds = ''
              res.data.forEach(item => {
                if (!item.success) {
                  ind = false
                  inds += item.message
                }
              })
              if (ind) {
                this.$message({
                  message: '发布成功',
                  type: 'success'
                })
                this.$emit('confirm')
              } else {
                this.$message({
                  message: inds,
                  type: 'warning'
                })
              }
            })
          })
        } else {
          this.msg = ''
          e.data.forEach(item => {
            this.msg += item.message
          })
          that.$message({
            message: `${this.msg}`,
            type: 'error'
          })
        }
        return Promise.reject(e)
      })
      // return
      // console.log(fm.get('file'))
      // var _this = this
      // const rt = await importData(fm).catch(e => {
      //   // console.log(e)
      //   _this.$message({
      //     message: `上传成功`,
      //     type: 'success'
      //   })
      //   return Promise.reject(e)
      // })
      // console.log(rt)
    },
    beforeUpload(file) {
      console.log(file)
      this.blobData = file
    },
    beforeRemove() {
      this.tableDataS = []
    },
    handleProgress(file, fileList) {
      console.log(file, fileList)
      if (this.msg) {
        file = this.blobData
      }
      console.log(file, fileList)
      const vm = this
      const jarTree = []
      jsZip.loadAsync(file.raw).then(res => {
        let treeId = 0
        let project = ''
        res.forEach(function(relativePath, zioEntry) {
          if (file.name.indexOf('.jar') !== -1) {
            treeId++
            let trees = {}
            if (relativePath.indexOf('SMTP') === -1 && relativePath.indexOf('/') !== -1 && project.indexOf(relativePath.split('/')[0]) === -1) {
              if (project.split(',').length >= 1 && project !== '') {
                project = project + ','
              }
              project = project + relativePath.split('/')[0]
              jarTree.push({
                id: 'xx' + project.split(',').length,
                types: '项目',
                typex: '项目',
                name: relativePath.split('/')[0],
                children: []
              })
            }
            if (relativePath.indexOf('/') !== -1) {
              trees = {
                id: treeId,
                url: relativePath,
                name: relativePath.split('/')[relativePath.split('/').length - 1],
                types: '业务服务'
              }
            }
            if (relativePath.split('/')[relativePath.split('/').length - 1].indexOf('WSDL') !== -1 || relativePath.split('/')[relativePath.split('/').length - 1].indexOf('XSLT') !== -1 || relativePath.split('/')[relativePath.split('/').length - 1].indexOf('XMLSchema') !== -1) {
              trees.types = '资源文件'
            }
            if (relativePath.split('/')[relativePath.split('/').length - 1].indexOf('Archive') !== -1 || relativePath.split('/')[relativePath.split('/').length - 1].indexOf('XSLT') !== -1 || relativePath.split('/')[relativePath.split('/').length - 1].indexOf('XMLSchema') !== -1) {
              trees.types = '资源文件'
            }
            if (relativePath.split('/')[relativePath.split('/').length - 1].indexOf('ProxyService') !== -1) {
              trees.types = '代理服务'
            }
            if (relativePath.split('/')[relativePath.split('/').length - 1].indexOf('ServiceAccount') !== -1) {
              trees.types = '账户信息'
            }
            if (relativePath.split('/')[relativePath.split('/').length - 1].indexOf('Pipeline') !== -1) {
              trees.types = '消息流'
            }
            if (trees.types && ((trees.types === '业务服务' && trees.name.indexOf('BusinessService') !== -1) || trees.types !== '业务服务')) {
              const inds = project.split(',').indexOf(trees.url.split('/')[0])
              jarTree[inds].children.push(trees)
              jarTree[inds].children.sort((a, b) => a.types.localeCompare(b.types))
            }
            if (trees.types && ((trees.types === '业务服务' && trees.name.indexOf('BusinessService') !== -1) || trees.types !== '业务服务')) {
              vm.checkedList.push(trees)
            }
          }
          if (file.name.indexOf('.jar') === -1 && zioEntry.name.slice(zioEntry.name.length - 1) !== '/') {
            res.file(zioEntry.name).async('blob').then(function success(text) {
              text.text().then(function(e) {
                const list = JSON.parse(e)
                list.data.forEach(item => {
                  const childrens = {
                    name: item.projectDTO.name,
                    id: item.projectDTO.id,
                    types: '项目',
                    typex: '项目',
                    isY: false,
                    children: []
                  }
                  Object.keys(item).forEach(item1 => {
                    switch (item1) {
                      case 'businessService':
                        item[item1].forEach(item => {
                          item.isY = false
                          item.types = '业务服务'
                          item.typex = '业务服务'
                          if (item.serverResourceDetail) {
                            item.refs = item.serverResourceDetail.length
                          }
                          childrens.children.push(item)
                        })
                        break
                      case 'proxyService':
                        item[item1].forEach(item => {
                          item.isY = false
                          item.types = '代理服务'
                          item.typex = '代理服务'
                          if (item.serverResourceDetail) {
                            item.refs = item.serverResourceDetail.length
                          }
                          childrens.children.push(item)
                        })
                        break
                      case 'flows':
                        item[item1].forEach(item => {
                          item.isY = false
                          item.types = '消息流'
                          item.typex = '消息流'
                          if (item.serverResourceDetail) {
                            item.refs = item.serverResourceDetail.length
                          }
                          childrens.children.push(item)
                        })
                        break
                      case 'resource':
                        item[item1].forEach(item => {
                          item.isY = false
                          item.typex = '资源文件'
                          item.types = item.type
                          if (item.serverResourceDetail) {
                            item.refs = item.serverResourceDetail.length
                          }
                          childrens.children.push(item)
                        })
                        break
                      case 'connector':
                        item[item1].forEach(item => {
                          item.isY = false
                          item.typex = '适配器'
                          item.types = item.type
                          if (item.serverResourceDetail) {
                            item.refs = item.serverResourceDetail.length
                          }
                          childrens.children.push(item)
                        })
                        break
                      case 'sqlBuilderDtos':
                        item[item1].forEach(item => {
                          item.isY = false
                          item.typex = 'sql构建器'
                          item.types = item.type
                          if (item.serverResourceDetail) {
                            item.refs = item.serverResourceDetail.length
                          }
                          childrens.children.push(item)
                        })
                        break
                    }
                  })
                  if (vm.tableDataS.length < 1) {
                    vm.tableDataS.push(childrens)
                  }
                })
              }, function error(e) {})
            })
          }
        })
        this.$nextTick(() => {
          if (jarTree.length > 0 && jarTree[0].children && jarTree[0].children.length > 0) {
            vm.tableDataS = jarTree
          }
        })
      })
      // console.log(jarTree.children)
      // vm.tableDataS = jarTree
    },
    submitUpload(val) {
      // console.log(this.fileList)
      // this.importData()
      // this.$refs.upload.submit()
      // console.log(this.domainAddRow, this.blobData)
      if (this.domainid && this.domainid !== '') {
        this.$refs.upload.submit()
      } else {
        this.domainDialog = true
      }
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(1)
      // console.log(file);
    }
  }
}
</script>

<style lang="scss" scoped>
  .importAndExport{
    margin: 10px 10px;
  }
</style>
<style type="text/scss" lang="scss" scoped>
  .importAndExport {
    background: #ffffff;
    padding: 20px;
    // .export-project{
    //     float: right;
    //     margin: 20px;
    // }
    // .el-pagination{
    //     padding-top: 20px;
    // }
  }
  .table-wrapper {
    margin-top: 20px;
  }
</style>>
