<template>
  <el-card class="wrapper">
    <el-tabs v-model="listQuery.vendorType" @change="getList">
      <el-tab-pane v-for="(item, index) in typelist" :label="item | vendorName" :name="item" :key="index"> </el-tab-pane>
    </el-tabs>
    <AdvanceTable :key="listQuery.vendorType + 'type'" :card-border="false" :searchConfigs="searchConfigs" :data="list" :params="params" :columns="columns" :get-list="getList" :total="total" ref="multipleTable" @select="handleSelectItem" @select-all="handleSelectAll">
      <template v-slot:action>
        <router-link v-if="listQuery.vendorType && $store.state.app.userData.accountCategory === 'User'" :to="{ name: 'ServiceEcsCreate', params: { type: listQuery.vendorType } }" class="m-l-xs m-r-xs">
          <el-button type="primary">订购云主机</el-button>
        </router-link>
        <el-button type="ghost" @click="handle(1)" :disabled="selectList.length == 0">
          <i class="el-icon-switch-button"></i>
          开机
        </el-button>
        <el-button type="ghost" @click="handle(2)" :disabled="selectList.length == 0">
          <i class="el-icon-switch-button"></i>
          关机
        </el-button>
        <el-button type="ghost" @click="handle(3)" :disabled="selectList.length == 0">
          <i class="el-icon-switch-button"></i>
          重启
        </el-button>
        <el-button type="ghost" @click="handleImport" icon="el-icon-download"> 导出 </el-button>
        <el-button type="ghost" @click="handleAssignBefor">
          <i class="el-icon-position"></i>
          存量资源分配
        </el-button>
        <el-button type="ghost" @click="handleAssign" :disabled="selectList.length == 0" v-if="$store.state.app.userData.accountCategory !== 'User'">
          <i class="el-icon-position"></i>
          分配
        </el-button>
        <!-- <el-button type="ghost" @click="removeVms()" :disabled="selectList.length == 0">
          <i class="el-icon-delete"></i>
          移入回收站
        </el-button> -->
      </template>
      <template #account="val, record">
        <span class="detail-href" @click="getDetail(record)">{{ val }}</span>
      </template>
      <template #ip="val, record">
        <div v-if="record.vendorType == 'OPENSTACK' || record.vendorType == 'EASYSTACK' || record.vendorType == 'MANAGEONE' || record.vendorType == 'FUSIONCLOUD'">
          <span v-for="item in record.privateIpsList" :key="item.networkId">
            <div v-for="(items1, index) in item.addresses" :key="index">(内网){{ items1.address + (!item.networkName ? '' : '(' + item.networkName + ')') }}</div>
          </span>
        </div>
        <div v-else-if="record.vendorType == 'VMWARE' || record.vendorType == 'POWERVC'">
          <div v-for="item in record.privateIpsList" :key="item.address">(内网){{ !item.address ? '' : item.address + (!item.networkName ? '' : '(' + item.networkName + ')') }}</div>
        </div>
        <div v-else-if="record.vendorType == 'HUAWEI' || record.vendorType == 'HCSO'">
          <div v-for="item in record.privateIpsList" :key="item.address">{{ item.type == 'floating' ? '(公网)' : '(内网)' }}{{ !item.address ? '' : item.address + (!item.networkName ? '' : '(' + item.networkName + ')') }}</div>
        </div>
        <div v-else-if="record.vendorType == 'QCLOUD'">
          <div v-for="(item, index) in record.privateIpsList" :key="index">(内网){{ item.address }}</div>
        </div>
        <div v-else-if="record.vendorType == 'AZURE' || record.vendorType == 'AWS'">
          <div v-for="item in record.privateIpsList" :key="item">(内网){{ item }}</div>
        </div>
        <div v-else-if="record.vendorType == 'SMARTX' || record.vendorType == 'CLOUDTOWER'">
          <div>{{ record.managerIp ? '(内网)' + record.managerIp : '--' }}</div>
        </div>
        <div v-else-if="record.vendorType == 'JDCLOUD'">
          <div v-for="(item, index) in record.privateIpsList" :key="index">(内网){{ item }}</div>
        </div>
        <div v-else-if="record.vendorType == 'VOLCENGINE'">
          <!-- <div v-for="(item, index) in record.privateIpsList" :key="index">(内网){{ item.primaryIpAddress }}</div> -->
          <div v-if="JSON.parse(record.privateIps)[0].primaryIpAddress">{{ JSON.parse(record.privateIps)[0].primaryIpAddress }}(内网)</div>
          <div v-if="JSON.parse(record.privateIps)[0].eipAddress">{{ JSON.parse(record.privateIps)[0].eipAddress }}(公网)</div>
        </div>
        <div v-else-if="record.vendorType == 'SANGFOR'">
          <div>{{ record.privateIps }}</div>
        </div>
        <div v-else>
          <div v-for="item in record.privateIpsList" :key="item">(内网){{ item }}</div>
        </div>
        <div v-if="record.floatingIp">(公网){{ record.floatingIp }}</div>
        <div v-if="record.vendorType == 'TENCENT' || record.vendorType == 'ALIYUN' || record.vendorType == 'AZURE' || record.vendorType == 'AWS' || record.vendorType == 'QCLOUD'">
          <div v-for="(item, index) in JSON.parse(record.publicIps)" :key="index">(公网){{ item }}</div>
        </div>
      </template>
      <template #spec="val, record"> {{ (record.cpu ? record.cpu : 0) + 'C/' + (record.memory ? record.memory : 0) + 'GB/' }}{{ record.disk == null ? 0 : record.disk + 'GB' }} </template>
      <template #status="status">
        <status-icon :type="status | vmStatusColor">{{ status | openstackServer }}</status-icon>
      </template>
      <template #os="val, record">
        <div v-if="record.vendorType == 'SMARTX'">
          {{ record.osVersion ? record.osVersion : '' }}
        </div>
        <div v-else>
          {{ (record.osCategory ? record.osCategory : '') + ' ' + (record.osName ? record.osName : '') + ' ' + (record.osVersion ? record.osVersion : '') }}
        </div>
      </template>
      <template #memory="val"> {{ val }} GB </template>
      <template #operate="val, record">
        <operate :obj="record" @getList="getList" v-if="(record.vendorType == 'VMWARE' && !record.software) || record.vendorType != 'VMWARE'"></operate>
      </template>
    </AdvanceTable>
    <detail :data="installDetail" v-if="detailFlag" @goBack="goBack" ref="detail" @back="getDetail"></detail>
    <selection-service router="ServiceEcsCreate" code="compute" v-if="dialog.dialog" :dialog="dialog"></selection-service>
    <AssignBefor :addData="assignBeforDialog" v-if="assignBeforDialog.dialog" @back="getList" resourceCategory="Computer" :vendorType="listQuery.vendorType"></AssignBefor>
    <Assign :addData="assignDialog" v-if="assignDialog.dialog" @back="getList" :vendorType="listQuery.vendorType"></Assign>
  </el-card>
</template>

<script>
import operate from './operate/index.vue'
import detail from './detail/index.vue'
import AssignBefor from './assignBefor.vue'
import Assign from './assign/assign.vue'
import webSocket from '@/common/mixins/getGlobalSocket'
import selectionService from '@/components/selectionService.vue'
import { getVm, detailVm, conditionService, patchVms, recycleVms } from 'services/platform/index'
import { getClient } from 'services/platform/security'
import { getProject } from 'services/system/project'
import { getTags } from 'services/system/tag'
import { downloadFile } from 'utils/'

export default {
  mixins: [webSocket],
  data() {
    return {
      columns: [
        {
          type: 'selection',
          selectable: this.selectable
        },
        {
          label: '名称',
          prop: 'name',
          sortable: 'custom',
          scopedSlots: { customRender: 'account' }
        },
        {
          label: 'IP',
          prop: 'privateIps',
          sortable: 'custom',
          scopedSlots: { customRender: 'ip' }
        },
        {
          label: '状态',
          prop: 'status',
          scopedSlots: { customRender: 'status' }
        },
        {
          label: '规格',
          prop: 'spec',
          scopedSlots: { customRender: 'spec' }
        },
        {
          label: '操作系统',
          prop: 'os',
          scopedSlots: { customRender: 'os' }
        },
        {
          label: '过期时间',
          prop: 'expiredTime'
        },
        {
          label: '所属项目',
          prop: 'projectName'
        },
        {
          label: '操作',
          disabled: true,
          width: '240px',
          showOverflowTooltip: false,
          scopedSlots: { customRender: 'operate' }
        }
      ],
      searchConfigs: [
        { label: '名称', value: 'name', type: 'Input' },
        { label: 'IP', value: 'privateIps', type: 'Input' },
        { label: 'UUID', value: 'uuid', type: 'Input' },
        {
          label: '状态',
          value: 'status',
          type: 'Select',
          data: [
            { id: 'RUNNING', name: '运行中' },
            { id: 'BUILDING', name: '创建中' },
            { id: 'STOPPED', name: '关机' },
            { id: 'SUSPENDED', name: '挂起' },
            { id: 'EXCEPTION', name: '异常' },
            { id: 'UNKNOWN', name: '断开' }
          ]
        },
        { label: '标签', value: 'labelContent', type: 'Cascade', props: { value: 'id', label: 'name', children: 'children', checkStrictly: false }, data: [] },
        { label: '项目', value: 'projectId', type: 'Select', data: [] },
        { value: 'isRecycle', type: 'Const', initValue: 0 }
      ],
      list: null,
      total: null,
      listQuery: {
        name: '',
        vendorType: ''
      },
      params: {
        page: 1,
        rows: 10
      },
      detailFlag: false,
      //        详情数据
      installDetail: {
        id: '',
        title: '云主机详情',
        header: '基本信息'
      },
      dialog: {
        dialog: false
      },
      ClientUrl: '',
      typelist: [],
      idList: [],
      selectList: [],
      props: {
        label: 'name',
        value: 'id',
        children: 'children',
        emitPath: false
      },
      assignBeforDialog: {
        dialog: false,
        data: {
          type: 'tenant'
        }
      },
      assignDialog: {
        dialog: false,
        data: {}
      }
    }
  },
  components: {
    operate,
    detail,
    selectionService,
    Assign,
    AssignBefor
  },
  created() {
    conditionService('server').then(data => {
      if (data.success) {
        this.typelist = data.data
        this.listQuery.vendorType = this.$route.query.vendorType || this.typelist[0]
        this.searchConfigs = [
          { label: '名称', value: 'name', type: 'Input' },
          { label: 'IP', value: 'privateIps', type: 'Input' },
          { label: 'UUID', value: 'uuid', type: 'Input' },
          {
            label: '状态',
            value: 'status',
            type: 'Select',
            data: [
              { id: 'RUNNING', name: '运行中' },
              { id: 'BUILDING', name: '创建中' },
              { id: 'STOPPED', name: '关机' },
              { id: 'SUSPENDED', name: '挂起' },
              { id: 'EXCEPTION', name: '异常' },
              { id: 'UNKNOWN', name: '断开' }
            ]
          },
          { label: '标签', value: 'labelContent', type: 'Cascade', props: { value: 'id', label: 'name', children: 'children', checkStrictly: false }, data: [] },
          { label: '项目', value: 'projectId', type: 'Select', data: [] },
          { value: 'isRecycle', type: 'Const', initValue: 0 }
        ]
        this.getProject()
        this.getTag()
      }
    })
    // this.handleClientDownlod()
  },
  methods: {
    handleImport() {
      this.$refs.multipleTable.handleSearch()
      downloadFile('/ims/v1/vms/download', {
        action: 'createVspVmXls',
        params: this.params.params
      })
    },
    handleAssignBefor() {
      this.assignBeforDialog = {
        dialog: true
      }
    },
    handleAssign() {
      this.refreshId()
      this.assignDialog = {
        dialog: true,
        data: {
          type: 'tenant',
          tenantId: this.$store.state.app.userData.tenantId || this.$store.state.app.userData.id,
          ids: this.idList,
          resourceCategory: 'Computer',
          vendorType: this.listQuery.vendorType
        }
      }
    },
    async getProject() {
      const data = await getProject({
        page: 1,
        rows: 9999
      })
      if (data.success) {
        this.searchConfigs[5].data = data.data.rows
      }
    },
    getTag() {
      getTags({
        page: 1,
        rows: 9999
      }).then(data => {
        if (data.success) {
          data.data.rows.forEach(item => {
            this.recursion(item)
          })
          this.searchConfigs[4].data = data.data.rows
        }
      })
    },
    recursion(data) {
      if (!data.content) {
        this.$set(data, 'children', '')
      } else {
        const ary = JSON.parse(data.content)
        data.children = ary.map(item => {
          return {
            name: item,
            id: `${data.name}:${item}`
          }
        })
      }
    },
    removeVms() {
      const idList = []
      this.selectList.forEach(item => {
        idList.push(item.uuid)
      })
      this.$confirm('此操作将所选云主机移入回收站, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        recycleVms(idList).then(data => {
          if (data.success) {
            this.$message({
              type: 'success',
              message: data.message
            })
            this.getList()
          }
        })
      })
    },
    handle(index) {
      // 批量操作
      let str = ''
      let action = ''
      const idList = []
      this.selectList.forEach(item => {
        idList.push(item.id)
      })
      switch (index) {
        case 1:
          str = '开机'
          action = 'start'
          break
        case 2:
          str = '关机'
          action = 'stop'
          break
        case 3:
          str = '重启'
          action = 'reboot'
          break
      }
      this.$confirm('此操作将' + str + '所选云主机, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        patchVms(action, idList).then(data => {
          if (data.success) {
            this.$message({
              type: 'success',
              message: data.message
            })
            this.$emit('search')
          }
        })
      })
    },
    refreshId() {
      this.idList = []
      this.selectList.forEach(item => {
        this.idList.push(item.id)
      })
    },
    // 单选
    handleSelectItem(selection, row) {
      this.refreshId()
      if (this.idList.indexOf(row.id) > -1) {
        for (let j = 0; j < this.selectList.length; j++) {
          const item = this.selectList[j]
          if (item.id == row.id) {
            this.selectList.splice(j, 1)
            break
          }
        }
      } else {
        this.selectList.push(row)
      }
    },
    // 全选
    handleSelectAll(selection) {
      this.refreshId()
      if (selection.length) {
        // 全选情况下
        selection.forEach(item => {
          if (this.idList.indexOf(item.id) == -1) {
            this.selectList.push(item)
          }
        })
      } else {
        // 全不选情况下
        this.list.forEach(item => {
          if (this.idList.indexOf(item.id) > -1) {
            for (let j = 0; j < this.selectList.length; j++) {
              const row = this.selectList[j]
              if (item.id == row.id) {
                this.selectList.splice(j, 1)
                break
              }
            }
          }
        })
      }
    },
    Create() {
      this.dialog.dialog = true
    },
    onmessage(data) {
      if (data.operate.indexOf('vm') > -1 || data.operate.indexOf('computer') > -1) {
        this.getList()
      }
      if (data.message) {
        this.getList()
      }
    },
    judgeOperate(data) {
      // 组合云主机配置
      data.hostConfig = data.cpu + 'C/' + data.memory + 'GB/' + (data.disk ? data.disk : 0) + 'GB'
      // if (data.vendorType != 'VMWARE') data.disSnap = true;
      switch (data.status) {
        case 'STOPPING':
          data.allDisabled = true
          break
        case 'STARTING':
          data.allDisabled = true
          break
        case 'SUSPENDING':
          data.allDisabled = true
          break
        case 'RESTARTING':
          data.allDisabled = true
          break
        case 'PAUSED':
          data.disControl = true
          data.disDel = false
          data.disMonitor = true
          data.disStart = true
          data.disStop = true
          data.disRestart = true
          data.disShutoff = true
          data.disSuspended = true
          data.disRecover = true
          data.disActive = false
          data.disPostpone = false
          data.disSnapshot = false
          data.disPassword = true
          break
        case 'ACTIVING':
          data.allDisabled = true
          break
        case 'INACCESSIBLE':
          data.disControl = true
          data.disStart = true
          data.disStop = true
          data.disRestart = true
          data.disShutoff = true
          data.disActive = true
          data.disSuspended = true
          data.isExpired = true
          data.disPassword = true
          data.isSHELVED = true
          data.disPostpone = true
          break
        case 'SYNSEXCEPTION':
          data.allDisabled = true
          data.disPostpone = true
          break
        case 'BUILDING':
          data.allDisabled = true
          break
        case 'EXCEPTION':
          data.disControl = true
          data.disDel = false
          data.disMonitor = true
          data.disStart = true
          data.disStop = true
          data.disRestart = true
          data.disShutoff = true
          data.disActive = true
          data.disSuspended = true
          data.disRecover = true
          data.disPostpone = true
          data.disPassword = true
          data.disSnapshot = true
          data.isSHELVED = true
          break
        case 'RUNNING':
          data.disControl = false
          data.disDel = false
          data.disMonitor = false
          data.disStart = true
          data.disStop = false
          data.disRestart = false
          data.disShutoff = false
          data.disActive = true
          data.disSuspended = false
          data.disRecover = true
          data.disPostpone = false
          data.disPassword = false
          data.disSnapshot = false
          break
        case 'STOPPED':
          data.disControl = true
          data.disDel = false
          data.disMonitor = true
          data.disStart = false
          data.disStop = true
          data.disRestart = true
          data.disShutoff = true
          data.disSuspended = true
          data.disRecover = true
          data.disActive = true
          data.disPostpone = false
          data.disSnapshot = false
          data.disPassword = true
          break
        case 'SUSPENDED':
          data.disControl = true
          data.disDel = false
          data.disMonitor = true
          data.disStart = false
          data.disStop = false
          data.disRestart = true
          data.disShutoff = true
          data.disSuspended = true
          data.disRecover = false
          data.disActive = true
          data.disPostpone = false
          data.disSnapshot = false
          data.disPassword = true
          break
        case 'UNKNOWN':
          data.allDisabled = true
          data.disPostpone = true
          break
        case 'UNKNOWNON':
          data.allDisabled = true
          data.disPostpone = true
          break
        case 'UNKNOWNOFF':
          data.allDisabled = true
          data.disPostpone = true
          break
        case 'UNKNOWNSUSPEND':
          data.allDisabled = true
          data.disPostpone = true
          break
        case 'RECOVERING':
          data.allDisabled = true
          break
        case 'PAUSING':
          data.allDisabled = true
          break
        case 'SHELVED':
          data.allDisabled = true
          data.disPostpone = true
          break
        case 'RESTORING':
          data.allDisabled = true
          break
      }
    },
    getList() {
      if (this.typelist.indexOf(this.listQuery.vendorType) > -1) {
        const params = JSON.parse(this.params.params)
        params.push({ param: { vendorType: this.listQuery.vendorType }, sign: 'EQ' })
        getVm({
          ...this.params,
          params: JSON.stringify(params)
        }).then(data => {
          if (data.success) {
            this.list = data.data.rows
            this.total = data.data.total
            this.selectList = []
            this.list.forEach(item => {
              const nowTime = new Date()
              const nowDate = nowTime.getTime()
              this.judgeOperate(item)
              item.isExpired = false
              const expiredTimeDate = new Date(item.expiredTime).getTime()
              if (expiredTimeDate < nowDate) {
                item.isExpired = true
              }
              if (item.privateIps) item.privateIpsList = JSON.parse(item.privateIps)
              if (item.publicIps) item.publicIpsList = JSON.parse(item.publicIps)
              if (item.vendorType === 'SANGFOR' && item.privateIps) {
                item.privateIps = Object.values(JSON.parse(item.privateIps))
                  .map(item => Object.keys(item)[0])
                  .toString()
              }
            })
          }
        })
      }
    },
    // 跳转详情页
    getDetail(row) {
      detailVm(row.id).then(data => {
        if (data.success) {
          if (row.vendorType === 'SANGFOR') {
            this.installDetail = {
              ...data.data,
              detail: JSON.parse(data.data.detail || '{}')
            }
            if (this.installDetail.privateIps) {
              this.installDetail.privateIps = Object.values(JSON.parse(this.installDetail.privateIps))
                .map(item => Object.keys(item)[0])
                .toString()
            }
            this.detailFlag = true
            this.installDetail.showBtn = false
            return
          }
          this.installDetail = data.data
          this.installDetail.configuration = this.installDetail.cpu + 'C/' + this.installDetail.memory + 'GB/' + this.installDetail.disk + 'GB'
          this.installDetail.osConfig = this.installDetail.osName ? this.installDetail.osName : '' + ' ' + this.installDetail.osVersion ? this.installDetail.osVersion : ''
          this.installDetail.privateIpsList = data.data.privateIps ? JSON.parse(data.data.privateIps) : []
          this.installDetail.publicIpsList = data.data.publicIps ? JSON.parse(data.data.publicIps) : []
          this.judgeOperate(this.installDetail)
          this.installDetail.expiredTime = row.expiredTime
          if (this.installDetail.vendorType == 'VMWARE' && this.installDetail.software) this.installDetail.showBtn = false
          else this.installDetail.showBtn = true
          this.detailFlag = true
        }
      })
    },
    goBack() {
      this.detailFlag = false
      this.getList()
    },
    handleClientDownlod() {
      getClient({
        type: navigator.platform
      }).then(data => {
        if (data.success) {
          this.ClientUrl = data.data
        }
      })
    }
  }
}
</script>
<style scoped></style>
