<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="list"
        :defaultParams="{
          column: 'createTime',
          order: 'desc',
          pageSize: 9
        }"
        :gridColumn="2"
        :params="params"
      >
        <template #headerTitle>
          <PermissionButton type="primary" @click="handlAdd">
            <template #icon><JAIcon type="PlusOutlined" /></template>
            新增
          </PermissionButton>
        </template>
        <template #card="slotProps">
          <CardBox
            :showStatus="true"
            :value="slotProps"
            :actions="getActions(slotProps)"
            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('/device-access.png')" style="width: 80px; height: 80px" />
              </slot>
            </template>
            <template #content>
              <div class="card-item-content">
                <Ellipsis style="width: calc(100% - 100px); margin-bottom: 20px">
                  <span class="card-title">
                    {{ slotProps.name }}
                  </span>
                </Ellipsis>
                <Row class="card-item-content-box">
                  <Col :span="12" v-if="slotProps.channelInfo" class="card-item-content-text">
                    <div class="card-item-content-text-title">
                      {{ slotProps.channelInfo.name }}
                    </div>
                    <Ellipsis
                      style="width: calc(100% - 10px); display: flex; margin-top: 4px"
                      v-if="slotProps.channelInfo.addresses"
                    >
                      <Badge :status="getStatus(slotProps)" />
                      <span>
                        {{ slotProps.channelInfo.addresses[0].address }}
                      </span>
                    </Ellipsis>
                  </Col>
                  <Col :span="12" v-if="slotProps.protocolDetail" class="card-item-content-text">
                    <div class="card-item-content-text-title"> 协议 </div>
                    <Ellipsis style="width: calc(100% - 10px); display: flex; margin-top: 4px">
                      <span>
                        {{ slotProps.protocolDetail.name }}
                      </span>
                    </Ellipsis>
                  </Col>
                </Row>
                <Row>
                  <Col :span="24" class="card-item-content-description">
                    <Tooltip>
                      <template #title>
                        {{ getDescription(slotProps) }}
                      </template>
                      {{ getDescription(slotProps) }}
                    </Tooltip>
                  </Col>
                </Row>
              </div>
            </template>

            <template #actions="item">
              <PermissionButton
                :disabled="item.disabled"
                :popConfirm="item.popConfirm"
                :tooltip="{
                  ...item.tooltip
                }"
                @click="item.onClick"
              >
                <JAIcon type="DeleteOutlined" v-if="item.key === 'delete'" />
                <template v-else>
                  <JAIcon :type="item.icon" />
                  <span>{{ item?.text }}</span>
                </template>
              </PermissionButton>
            </template>
          </CardBox>
        </template>
        <template #state="slotProps">
          <Badge :text="slotProps.state.text" :status="statusMap.get(slotProps.state.value)" />
        </template>
      </JTable>
    </FullPage>
  </PageContainer>
  <Detail v-if="visible" :id="id" :view="view" @close="visible = false" />
</template>
<script lang="ts" setup name="AccessConfigPage">
  import { getImage, onlyMessage, accessConfigTypeFilter } from '@jdlinker/utils';
  import { list, getProviders, remove, undeploy, deploy } from '../../../api/link/accessConfig';
  import Detail from './Detail/index.vue';
  import { FormSchema, JSearch as ProSearch, FullPage, PermissionButton, CardBox } from '@jdlinker/ui';
  // @ts-ignore
  import { PageContainer, AIcon as JAIcon, Badge, Ellipsis, Row, Col, Tooltip } from 'linker-ui-components';
  import { ref } from 'vue';
  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>>({});

  let providersList = ref<Record<string, any>>([]);
  const providersOptions = ref<Record<string, any>>([]);

  const statusMap = new Map();
  statusMap.set('enabled', 'success');
  statusMap.set('disabled', 'error');

  const searchFormSchema: FormSchema[] = [
    {
      label: '网关名称',
      field: 'name',
      component: 'Input'
    },
    {
      field: 'provider',
      label: '网关类型',
      component: 'Select',
      componentProps: {
        options: providersOptions
      }
    },
    {
      field: 'stateExpand',
      label: '状态',
      component: 'Select',
      componentProps: {
        options: [
          { label: '正常', value: 'enabled' },
          { label: '禁用', value: 'disabled' }
        ]
      }
    }
  ];

  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      search: {
        type: 'string'
      }
    },
    {
      title: '网关类型',
      dataIndex: 'provider',
      key: 'provider',
      search: {
        type: 'select',
        options: providersOptions
      }
    },
    {
      title: '状态',
      dataIndex: 'state',
      key: 'state',
      search: {
        type: 'select',
        options: [
          {
            label: '禁用',
            value: 'disabled'
          },
          {
            label: '正常',
            value: 'enabled'
          }
        ]
      },
      scopedSlots: true
    },
    {
      title: '说明',
      dataIndex: 'description',
      key: 'description',
      search: {
        type: 'string'
      }
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 200,
      scopedSlots: true
    }
  ];

  const getActions = (data: Partial<Record<string, any>>): any[] => {
    if (!data) return [];
    const state = data.state.value;
    const stateText = state === 'enabled' ? '禁用' : '启用';
    return [
      {
        key: 'update',
        text: '编辑',
        tooltip: {
          title: '编辑'
        },
        icon: 'EditOutlined',
        onClick: async () => {
          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 undeploy(data.id) : await deploy(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'
      }
    ];
  };

  const getProvidersList = async () => {
    const res: any = await getProviders();
    providersList.value = res.result;
    // @ts-ignore
    providersOptions.value = accessConfigTypeFilter(res.result || []);
  };
  getProvidersList();

  const handlAdd = () => {
    visible.value = true;
    id.value = '';
  };
  const handlEdit = (_id: string) => {
    visible.value = true;
    id.value = _id;
  };
  const handlEye = (_id: string) => {
    visible.value = true;
    id.value = _id;
    view.value = true;
  };

  const getDescription = (slotProps: Record<string, any>) =>
    slotProps.description
      ? slotProps.description
      : providersList.value?.find((item: Record<string, any>) => item.id === slotProps.provider)?.description;

  const getStatus = (slotProps: Record<string, any>) =>
    slotProps.channelInfo.addresses[0].health === -1 ? 'error' : 'processing';

  /**
   * 搜索
   * @param e
   */
  const handleSearch = (e: any) => {
    params.value = e;
  };
</script>
<style lang="less" scoped>
  .table {
    max-height: 700px;
    overflow-y: auto;
    overflow-x: hidden;
  }

  .card-item-content {
    min-height: 100px;
    .card-title {
      font-size: 18px;
      font-weight: 800;
      line-height: 22px;
    }

    //.card-item-content-box {
    //  min-height: 50px;
    //}

    .card-item-content-text-title {
      font-style: normal;
      font-weight: 400;
      font-size: 12px;
      color: rgba(0, 0, 0, 0.75);
      opacity: 0.75;
    }
    .card-item-content-description {
      font-style: normal;
      font-weight: 400;
      font-size: 12px;
      line-height: 20px;
      color: #666666;
      overflow: hidden; //超出的文本隐藏
      text-overflow: ellipsis; //溢出用省略号显示
      white-space: nowrap; //溢出不换行
    }
  }
  :deep(.jtable-card) {
    min-height: 602px;
  }
  :deep(.jtable-body-spin .jtable-body .jtable-content) {
    padding: 12px 0;
  }
  :deep(.card .card-warp .card-content) {
    padding: 24px 12px 10px 30px;
  }
  :deep(.ant-pagination-options) {
    display: none;
  }
</style>
