import React from 'react'
import {
  amisRender,
  commonInfo,
  crudCommonOptions,
  serviceLogByAppName,
  serviceLogByAppNameAndHost,
  time,
} from '../../util/amis.tsx'

const cloudCrud = (title: string, path: string) => {
  return {
    type: 'crud',
    title: title,
    api: `${commonInfo.baseUrl}${path}`,
    ...crudCommonOptions(),
    interval: 2000,
    headerToolbar: ['reload'],
    loadDataOnce: true,
    perPage: 100,
    columns: [
      {
        label: '名称',
        type: 'tpl',
        tpl: `\${name} \${IF(size === undefined, '', '<span class="font-bold label label-primary">' + size + '</span>')}`,
      },
      {
        name: 'status',
        label: '状态',
        align: 'center',
        width: 60,
      },
      {
        name: 'serviceUpTime',
        label: '启动时间',
        ...time('serviceUpTime'),
        align: 'center',
        width: 160,
      },
      {name: 'url', label: '地址'},
      {
        type: 'operation',
        label: '操作',
        width: 100,
        fixed: 'right',
        className: 'nowrap',
        buttons: [
          {
            label: '日志',
            type: 'action',
            level: 'link',
            tooltip: '打开Grafana日志',
            onEvent: {
              click: {
                actions: [
                  {
                    actionType: 'custom',
                    // @ts-ignore
                    script: (context, doAction, event) => {
                      let data = context.props.data
                      let url = ''
                      if (data['metadata']) {
                        url = serviceLogByAppNameAndHost(data.serviceId, data.metadata.hostname)
                      } else if (data['name']) {
                        url = serviceLogByAppName(data.name)
                      }
                      window.open(url, '_blank')
                    },
                  },
                ],
              },
            },
          },
        ],
      },
    ],
  }
}

const Cloud: React.FC = () => {
  return (
    <div className="hudi-cloud">
      {amisRender(
        {
          type: 'wrapper',
          body: [
            cloudCrud('服务列表', '/cloud/list'),
            cloudCrud('服务列表 (IP)', '/cloud/list_ip'),
          ],
        },
      )}
    </div>
  )
}

export default Cloud