<template>
  <PageContainer v-if="!visible" :pageHeaderRender="false" style="padding: 0 10px 10px 10px">
    <ProSearch :columns="searchFormSchema" target="search" @search="handleSearch" />
    <FullPage style="min-height: calc(100vh - 186px)">
      <JTable
        ref="tableRef"
        model="CARD"
        :columns="columns"
        :request="query"
        :defaultParams="{
          column: 'createTime',
          order: 'desc',
          pageSize: 9
        }"
        :params="params"
      >
        <template #headerTitle>
          <PermissionButton type="primary" @click="handlAdd">
            <template #icon><JLAIcon type="PlusOutlined" /></template>
            新增
          </PermissionButton>
        </template>
        <template #card="slotProps">
          <CardBox
            :showStatus="true"
            :value="slotProps"
            :actions="getActions(slotProps, 'card')"
            v-bind="slotProps"
            :status="slotProps.state.value"
            :statusText="slotProps.state.text"
            :statusNames="{
              enabled: 'processing',
              disabled: 'error'
            }"
            @click="handlEye(slotProps.id)"
          >
            <template #img>
              <slot name="img">
                <img :src="getImage('/network.png')" class="typeImg" />
              </slot>
            </template>
            <template #content>
              <div class="card-item-content">
                <Ellipsis style="width: calc(100% - 100px); margin-bottom: 18px">
                  <span style="font-size: 18px; font-weight: 800; line-height: 22px">
                    {{ slotProps.name }}
                  </span>
                </Ellipsis>
                <Row class="card-item-content-box">
                  <Col :span="8">
                    <div class="card-item-content-text-title"> 类型 </div>
                    <div class="card-item-content-text">
                      <Tooltip>
                        <template #title>{{ slotProps.type }}</template>
                        {{ slotProps.type }}
                      </Tooltip>
                    </div>
                  </Col>

                  <Col :span="16">
                    <div class="card-item-content-text-title"> 详情 </div>
                    <div class="card-item-content-text">
                      <Tooltip>
                        <template #title>{{ getDetails(slotProps) }}</template>
                        {{ getDetails(slotProps) }}
                      </Tooltip>
                    </div>
                  </Col>
                </Row>
              </div>
            </template>
            <template #actions="item">
              <PermissionButton
                :disabled="item.disabled"
                :popConfirm="item.popConfirm"
                :tooltip="{
                  ...item.tooltip
                }"
                @click="item.onClick"
              >
                <JLAIcon type="DeleteOutlined" v-if="item.key === 'delete'" />
                <template v-else>
                  <JLAIcon :type="item.icon" />
                  <span>{{ item?.text }}</span>
                </template>
              </PermissionButton>
            </template>
          </CardBox>
        </template>
        <template #action="slotProps">
          <Space>
            <template v-for="i in getActions(slotProps, 'table')" :key="i.key">
              <PermissionButton
                :disabled="i.disabled"
                :popConfirm="i.popConfirm"
                :tooltip="{
                  ...i.tooltip
                }"
                style="padding: 0px"
                @click="i.onClick"
                type="link"
                :danger="i.key === 'delete'"
              >
                <template #icon><JLAIcon :type="i.icon" /></template>
              </PermissionButton>
            </template>
          </Space>
        </template>
        <template #state="slotProps">
          <BadgeStatus
            :text="slotProps.state.text"
            :status="slotProps.state.value"
            :statusNames="{
              enabled: 'processing',
              disabled: 'error'
            }"
          />
        </template>
        <template #shareCluster="slotProps">
          {{ slotProps.shareCluster === 'true' ? '共享配置' : '独立配置' }}
        </template>
        <template #type="slotProps">
          {{ slotProps.providerObject.name }}
        </template>
        <template #details="slotProps">
          {{ getDetails(slotProps) }}
        </template>
      </JTable>
    </FullPage>
  </PageContainer>
  <Detail v-if="visible" :id="id" :view="view" @close="visible = false" />
</template>
<script lang="ts" setup name="TypePage">
  import { getImage } from '@jdlinker/utils';
  import { supports, query, remove, start, shutdown } from '../../../api/link/type';
  import { onlyMessage } from '@jdlinker/utils';
  import Detail from './Detail/index.vue';
  import { FormSchema, JSearch as ProSearch, FullPage, PermissionButton, CardBox, BadgeStatus } from '@jdlinker/ui';
  import { ref } from 'vue';
  import { PageContainer, AIcon as JLAIcon, Ellipsis, Space, Row, Col, Tooltip } from 'linker-ui-components';
  import JTable from '../../../components/UI/Table/index';

  const visible = ref<boolean>(false);
  const id = ref<string>('');
  const view = ref<boolean>(false);
  const tableRef = ref<Record<string, any>>({});
  const params = ref<Record<string, any>>({});
  const options = ref([]);
  const searchFormSchema: FormSchema[] = [
    {
      label: '组件名称',
      field: 'name',
      component: 'Input'
    },
    {
      field: 'provider',
      label: '网关类型',
      component: 'Select',
      componentProps: {
        options: options
      }
    },
    {
      field: 'state',
      label: '状态',
      component: 'Select',
      componentProps: {
        options: [
          { label: '正常', value: 'enabled' },
          { label: '禁用', value: 'disabled' }
        ]
      }
    }
  ];
  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      ellipsis: true,
      align: 'center',
      search: {
        type: 'string'
      }
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      ellipsis: true,
      align: 'center',
      search: {
        type: 'select',
        options: options
      },
      scopedSlots: true
    },
    {
      title: '集群',
      dataIndex: 'shareCluster',
      key: 'shareCluster',
      align: 'center',
      ellipsis: true,
      scopedSlots: true,
      search: {
        type: 'select',
        options: [
          { label: '共享配置', value: 'true' },
          { label: '独立配置', value: 'false' }
        ]
      }
    },
    {
      title: '详情',
      dataIndex: 'details',
      key: 'details',
      ellipsis: true,
      width: 240,
      scopedSlots: true
    },
    {
      title: '状态',
      dataIndex: 'state',
      key: 'state',
      width: 100,
      ellipsis: true,
      align: 'center',
      scopedSlots: true,
      search: {
        type: 'select',
        options: [
          { label: '正常', value: 'enabled' },
          { label: '禁用', value: 'disabled' }
        ]
      }
    },
    {
      title: '说明',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
      align: 'center',
      search: {
        type: 'string'
      }
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      fixed: true,
      width: 200,
      scopedSlots: true
    }
  ];

  const getActions = (data: Partial<Record<string, any>>, type: 'card' | 'table'): any[] => {
    if (!data) return [];
    const state = data.state.value;
    const stateText = state === 'enabled' ? '禁用' : '启用';
    const actions = [
      {
        key: 'view',
        text: '查看',
        tooltip: {
          title: '查看'
        },
        icon: 'EyeOutlined',
        onClick: async () => {
          handlEye(data.id);
        }
      },
      {
        key: 'update',
        text: '编辑',
        tooltip: {
          title: '编辑'
        },
        icon: 'EditOutlined',
        onClick: () => {
          handlEdit(data.id);
        }
      },
      {
        key: 'action',
        text: stateText,
        tooltip: {
          title: stateText
        },
        icon: state === 'enabled' ? 'StopOutlined' : 'CheckCircleOutlined',
        popConfirm: {
          title: `确认${stateText}?`,
          onConfirm: async () => {
            let res = state === 'enabled' ? await shutdown(data.id) : await start(data.id);
            if (res.success) {
              onlyMessage('操作成功', 'success');
              tableRef.value?.reload();
            }
          }
        }
      },
      {
        key: 'delete',
        text: '删除',
        disabled: state === 'enabled',
        tooltip: {
          title: state === 'enabled' ? '请先禁用该组件，再删除。' : '删除'
        },
        popConfirm: {
          title: '确认删除?',
          onConfirm: async () => {
            const res: any = await remove(data.id);
            if (res.code === 200) {
              onlyMessage('操作成功', 'success');
              tableRef.value.reload();
            } else {
              onlyMessage(res?.message, 'error');
            }
          }
        },
        icon: 'DeleteOutlined'
      }
    ];
    return type === 'table' ? actions : actions.filter((item) => item.key !== 'view');
  };
  const handlAdd = () => {
    visible.value = true;
    id.value = '';
  };
  const handlEye = (data: string) => {
    visible.value = true;
    id.value = data;
    view.value = true;
  };

  const handlEdit = (data: string) => {
    visible.value = true;
    id.value = data;
    view.value = false;
  };

  const getDetails = (slotProps: Partial<Record<string, any>>) => {
    const { providerObject, shareCluster, configuration, cluster } = slotProps;
    const headers = providerObject.name.replace(/[^j-zA-Z]/g, '').toLowerCase() + '://';
    const content = !!shareCluster
      ? (configuration.publicHost || configuration.remoteHost) + ':' + (configuration.publicPort || configuration.remotePort)
      : (cluster[0].configuration.publicHost || cluster[0].configuration.remoteHost) +
        ':' +
        (cluster[0].configuration.publicPort || cluster[0].configuration.remotePort);
    let head = '远程:';
    if (!!shareCluster) {
      !!configuration.publicHost && (head = '公网:');
    } else {
      !!cluster[0].configuration.publicHos && (head = '公网:');
    }
    return head + headers + content;
  };

  const getSupports = async () => {
    const res: any = await supports();
    options.value = res.result.map((item: any) => ({
      value: item.id,
      label: item.name
    }));
  };
  getSupports();

  /**
   * 搜索
   * @param params
   */
  const handleSearch = (e: any) => {
    params.value = e;
  };
</script>
<style lang="less" scoped>
  .typeImg {
    width: 80px;
    height: 80px;
  }
  .card-item-content {
    .card-item-content-text {
      font-style: normal;
      font-weight: 400;
      font-size: 14px;
      line-height: 170%;
      color: rgba(0, 0, 0, 0.85);
      opacity: 0.75;
      overflow: hidden; //超出的文本隐藏
      text-overflow: ellipsis; //溢出用省略号显示
      white-space: nowrap; //溢出不换行
    }
    .card-item-content-text-title {
      font-style: normal;
      font-weight: 400;
      font-size: 12px;
      line-height: 170%;
      color: rgba(0, 0, 0, 0.75);
      opacity: 0.75;
    }
  }
  :deep(.card .card-warp .card-content) {
    padding: 24px 12px 24px 30px;
  }
  :deep(.card-item-content) {
    padding-top: 10px;
  }
  :deep(.jtable-card) {
    min-height: 597px;
  }
  :deep(.ant-pagination-options) {
    display: none;
  }
</style>
