<template>
  <d2-container>
    <d2-crud
      ref="d2Crud"
      :columns="columns"
      :data="data"
      :rowHandle="rowHandle"
      add-title="新增服务"
      edit-title="修改服务配置"
      :add-template="addTemplate"
      :edit-template="editTemplate"
      :form-options="formOptions"
      :add-rules="addRules"
      @dialog-open="handleDialogOpen"
      @row-add="handleRowAdd"
      @row-edit="handleRowEdit"
      @row-remove="handleRowRemove"
      @dialog-cancel="handleDialogCancel"
      @set-device="drawerShow"
      @exec="setServerExec">
      <el-button slot="header" style="margin-bottom: 5px" @click="addRow">新增</el-button>
    </d2-crud>

    <el-drawer
      size="95%"
      :append-to-body='true'
      :visible.sync="isDrawerShow"
      @close="closeDrawer"
      >
      <div slot="title" >
        <span class="title-text">前置服务 {{selectedServerData.name}}  URL:{{selectedServerData.url}}</span>
        <el-tag
          :color="serveStatus[selectedServerData.status].backgroundColor"
          :style="{color:serveStatus[selectedServerData.status].textColor,borderColor:serveStatus[selectedServerData.status].borderColor}"
        >
          {{serveStatus[selectedServerData.status].name}}
        </el-tag>
        <el-alert v-if="this.selectedServerData.updated === 't'" title="设备配置已更改，请在服务配置界面重启对应服务生效" type="warning" style="width:400px;display: inline-block;vertical-align: middle; margin-left: 5px;" :closable="false" />
      </div>
      <device ref="deviceTemplate" :server='server' @changeStatus='changeSelectedServerStatus' @changeServerConfig='changeSelectedServerConfig' />
    </el-drawer>

  </d2-container>
</template>

<script>
import { assign, each } from 'lodash'

const genRanHex = size => [...Array(size)].map(() => Math.floor(Math.random() * 16).toString(16).toUpperCase()).join('')

export default {
  components: {
    Device: () => import('./device')
  },
  data () {
    return {
      columns: [
        {
          title: '序号',
          key: 'id'
        },
        {
          title: '名称',
          key: 'name'
        },
        {
          title: 'URL',
          key: 'url'
        },
        {
          title: '端口',
          key: 'port'
        },
        {
          title: '绑定地址',
          key: 'address'
        },
        {
          title: '创建时间',
          key: 'create_date'
        },
        {
          title: '备注',
          key: 'note'
        }
      ],
      isDrawerShow: false,
      server: {},
      serveStatus: {
        online: {
          name: '在线',
          textColor: '#67c23a',
          backgroundColor: '#f0f9eb',
          borderColor: '#e1f3d8'
        },
        offline: {
          name: '离线',
          textColor: '#67c23a',
          backgroundColor: '#f0f9eb',
          borderColor: '#e1f3d8'
        }
      },
      selectedServerData: {
        name: '',
        url: '',
        port: '',
        updated: 'f',
        status: 'offline'
      },
      data: [],
      serverSettings: {},
      rowHandle: {
        minWidth: '200',
        edit: {
          icon: 'el-icon-edit',
          text: '编辑',
          size: 'small',
          show (index, row) {
            if (row.showEditButton) {
              return true
            }
            return false
          }
        },
        remove: {
          icon: 'el-icon-delete',
          size: 'small',
          fixed: 'right',
          confirm: true,
          show (index, row) {
            if (row.showRemoveButton) {
              return true
            }
            return false
          }
        },
        custom: [
          {
            text: '设备配置',
            size: 'small',
            emit: 'set-device'
          },
          {
            text: '重启服务',
            size: 'small',
            emit: 'exec'
          }
        ]
      },
      addTemplate: {
        deviceName: {
          title: '服务名称',
          value: 'Edge:' + genRanHex(12)
        },
        uniqueID: {
          title: '唯一标识',
          value: '',
          component: {
            disabled: true,
            placeholder: '采集服务唯一标识，测试成功后返回'
          }
        },
        url: {
          title: 'URL',
          value: '',
          component: {
            span: 12
          }
        },
        port: {
          title: '端口',
          value: 522,
          component: {
            span: 12
          }
        },
        address: {
          title: '绑定地址',
          value: '',
          component: {
            placeholder: '请填入绑定EdgeManager实例的地址，比如http://xxx.xxx:xxxx'
          }
        }
      },
      editTemplate: {
        address: {
          title: '绑定地址',
          component: {
            placeholder: '仅可以修改已绑定EdgeManager实例的地址'
          }
        }
      },
      formOptions: {
        labelWidth: '80px',
        labelPosition: 'left',
        saveLoading: false,
        saveButtonText: '测试',
        saveButtonType: 'text'
      },
      addRules: {
        deviceName: [{ required: true, type: 'string', message: '服务名称不可为空', trigger: 'blur' }],
        url: [{ required: true, type: 'string', message: '服务地址不可为空', trigger: 'blur' }],
        port: [{ required: true, type: 'integer', transform: v => +v, message: '端口号必须指定，且需为(0, 65535]内的正整数', trigger: 'blur' }],
        userName: [{ required: true, message: '用户名不可为空', trigger: 'blur' }],
        password: [{ required: true, type: 'string', message: '密码不可为空', trigger: 'blur' }],
        address: [{ type: 'url', message: '绑定地址必须为合法URL', trigger: 'blur' }]
      }
    }
  },
  methods: {
    async getServers () {
      try {
        const res = await this.$api.QUERY_SERVERS()
        this.data = each(res, (o) => (
          assign(o, {
            showEditButton: true,
            showRemoveButton: true
          })
        ))
      } catch (e) {
        console.log(e)
      }
    },
    handleDialogOpen ({ mode }) {
      if (mode === 'edit') {
        this.formOptions.saveButtonText = '确定'
        this.formOptions.saveButtonType = 'text'
      }
    },
    // 普通的新增
    addRow () {
      this.$refs.d2Crud.showDialog({
        mode: 'add'
      })
    },
    async handleRowAdd (row, done) {
      this.formOptions.saveLoading = true
      try {
        // 定义测试动作
        if (this.formOptions.saveButtonText === '测试') {
          this.serverSettings = await this.$api.VERIFY_SERVER(
            'http://' + row.url + ':' + row.port
          )
          if (this.serverSettings) {
            this.$message({
              message: '测试通过！',
              type: 'success'
            })
          }
          each(Object.keys(row), (p) => {
            this.addTemplate[p].value = row[p]
          })
          this.addTemplate.uniqueID.value = this.serverSettings.Content.ServerInfoConfig.UniqueId
          this.$refs.d2Crud.showDialog({
            mode: 'add'
          })
          this.formOptions.saveButtonText = '添加'
          this.formOptions.saveButtonType = 'success'
        // 定义添加动作
        } else {
          this.serverSettings.Content.ServerInfoConfig.DeviceName = row.deviceName
          this.serverSettings.Content.ServerInfoConfig.CaptureURL = row.address
          this.$api.MODIFY_SERVER(
            'http://' + row.url + ':' + row.port,
            { data: this.serverSettings.Content }
          )
          await this.$api.ADD_SERVER({
            action: 'add_server',
            name: row.deviceName,
            url: row.url,
            port: row.port,
            address: row.address
          })
          this.$message({
            message: '添加成功',
            type: 'success'
          })
          this.getServers()
          done()
        }
      } catch (e) {
        this.$message({
          message: '测试/添加失败！',
          type: 'error'
        })
        console.log(e)
      }
      this.formOptions.saveLoading = false
    },
    async handleRowEdit ({ index, row }, done) {
      this.formOptions.saveLoading = true
      const serverSettings = await this.$api.VERIFY_SERVER(
        'http://' + row.url + ':' + row.port
      )
      serverSettings.Content.ServerInfoConfig.CaptureURL = row.address
      this.$api.MODIFY_SERVER(
        'http://' + row.url + ':' + row.port,
        { data: serverSettings.Content }
      )
      this.$api.UPDATE_SERVER({
        action: 'update_server',
        id: row.id,
        address: row.address
      })
      this.$message({
        message: '编辑成功',
        type: 'success'
      })
      done()
      this.formOptions.saveLoading = false
    },
    async handleRowRemove ({ index, row }, done) {
      await this.$api.REMOVE_SERVER({
        action: 'remove_server',
        id: row.id
      })
      this.$message({
        message: '删除成功',
        type: 'success'
      })
      done()
    },
    setServerExec ({ row }) {
      this.$confirm('是否要重启动该服务', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await this.$api.SET_SERVER_EXEC({
            action: 'exec',
            server_id: row.id,
            command: 'server_restart'
          })
          this.$message({
            message: '服务应用请求成功，请求动作已添加至请求队列中，请从服务监控页面查看结果',
            type: 'success'
          })
          this.getServers()
        } catch (e) {
          console.log(e)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已重启动该服务'
        })
      })
    },
    handleDialogCancel (done) {
      this.$message({
        message: '用户放弃改动',
        type: 'warning'
      })
      done()
    },
    drawerShow ({ row }) {
      this.selectedServerData = {
        name: row.name,
        url: row.url,
        port: row.port,
        updated: row.updated,
        status: row.status ? row.status : 'offline'
      }
      this.server = { id: row.id, url: row.url, port: row.port }
      this.isDrawerShow = true
    },
    closeDrawer () {
      this.server = { id: 0, url: '', port: '' }
      if (this.$refs.deviceTemplate.timing) {
        this.$refs.deviceTemplate.clearTime()
      }
    },
    changeSelectedServerStatus (status) {
      this.selectedServerData.status = status || 'offline'
    },
    changeSelectedServerConfig (updated) {
      this.getServers()
      this.selectedServerData.updated = updated || 'f'
    }
  },
  mounted () {
    this.getServers()
  }
}
</script>
<style scoped>
.title-text{
  font-weight: bold;
  font-size: 20px;
  color: black;
  vertical-align: middle;
  margin-right: 15px;
}
</style>
