<template>
  <PageContainer v-if="!visible" :pageHeaderRender="false" style="padding: 0 10px 10px 10px">
    <ProSearch :columns="searchFormSchema" target="device-instance" @search="handleSearch" />
    <FullPage style="min-height: calc(100vh - 186px)">
      <JTable
        :columns="columns"
        model="CARD"
        :request="queryList"
        :gridColumn="3"
        ref="tableRef"
        :defaultParams="{
          column: 'createTime',
          order: 'desc',
          pageSize: 9
        }"
        :params="params"
      >
        <template #headerTitle>
          <Space>
            <PermissionButton type="primary" @click="add">
              <template #icon>
                <JAIcon type="PlusOutlined" />
              </template>
              新增
            </PermissionButton>
          </Space>
        </template>
        <template #card="slotProps">
          <CardBox
            :value="slotProps"
            :actions="getActions(slotProps, 'card')"
            v-bind="slotProps"
            :status="slotProps.state?.value"
            :statusText="slotProps.state?.text"
            :statusNames="{
              enabled: 'processing',
              disabled: 'error'
            }"
            @click="handleView(slotProps.id)"
          >
            <template #img>
              <slot name="img">
                <img :src="getImage('/alarm/alarm-config.png')" />
              </slot>
            </template>
            <template #content>
              <Ellipsis style="width: calc(100% - 100px)">
                <span style="font-weight: 600; font-size: 16px">
                  {{ slotProps.name }}
                </span>
              </Ellipsis>
              <Row>
                <Col :span="12">
                  <div class="content-des-title"> 关联场景联动 </div>
                  <Ellipsis style="margin-bottom: 18px">
                    <div>
                      {{ (slotProps?.scene || []).map((item: any) => item?.name).join(',') || '' }}
                    </div>
                  </Ellipsis>
                </Col>
                <Col :span="12">
                  <div class="content-des-title"> 告警级别 </div>
                  <div>
                    {{ (defaultLevel || []).find((item: any) => item?.level === slotProps.level)?.title || slotProps.level }}
                  </div>
                </Col>
              </Row>
            </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 #targetType="slotProps">
          <span>{{ map[slotProps.targetType] }}</span>
        </template>
        <template #level="slotProps">
          <Tooltip
            placement="topLeft"
            :title="(defaultLevel || []).find((item) => item?.level === slotProps.level)?.title || slotProps.level"
          >
            <div class="ellipsis">
              {{ (defaultLevel || []).find((item) => item?.level === slotProps.level)?.title || slotProps.level }}
            </div>
          </Tooltip>
        </template>
        <template #scene="slotProps">
          <span>{{ (slotProps?.scene || []).map((item) => item?.name).join(',') || '' }}</span>
        </template>
        <template #state="slotProps">
          <BadgeStatus
            :text="slotProps.state?.value === 'enabled' ? '正常' : '禁用'"
            :status="slotProps.state?.value"
            :statusNames="{
              enabled: 'processing',
              disabled: 'error'
            }"
          />
        </template>
        <template #action="slotProps">
          <Space :size="16">
            <template v-for="i in getActions(slotProps, 'table')" :key="i.key">
              <PermissionButton
                :disabled="i.disabled"
                :popConfirm="i.popConfirm"
                :tooltip="{
                  ...i.tooltip
                }"
                @click="i.onClick"
                type="link"
                style="padding: 0px"
                :danger="i.key === 'delete'"
              >
                <template #icon>
                  <JAIcon :type="i.icon" />
                </template>
              </PermissionButton>
            </template>
          </Space>
        </template>
      </JTable>
    </FullPage>
  </PageContainer>
  <Save v-if="visible" :id="id" @close="visible = false" />
  <!--  <HandTrigger @save="onSave" @close="visible = false" v-if="visible" :data="current" />-->
</template>

<script lang="ts" setup>
  import { queryList, _enable, _disable, remove } from '../../../../api/rule-engine/configuration';
  import { queryLevel } from '../../../../api/rule-engine/config';
  import { getImage, onlyMessage } from '@jdlinker/utils';
  import Save from './Save/index.vue';
  import { nextTick, ref } from 'vue';
  import JTable from '../../../../components/UI/Table/index';
  import { FormSchema, JSearch as ProSearch, FullPage, PermissionButton, CardBox, BadgeStatus } from '@jdlinker/ui';
  import { PageContainer, AIcon as JAIcon, Space, Ellipsis, Tooltip, Row, Col } from 'linker-ui-components';

  const id = ref<any>('');
  const params = ref<Record<string, any>>({});
  // let isAdd = ref<number>(0);
  // let title = ref<string>('');
  const tableRef = ref<Record<string, any>>({});
  const searchFormSchema: FormSchema[] = [
    {
      label: '告警名称',
      field: 'name',
      component: 'Input'
    },
    {
      field: 'provider',
      label: '网关类型',
      component: 'Select',
      componentProps: {
        options: [
          { label: '产品', value: 'product' },
          { label: '设备', value: 'device' },
          { label: '组织', value: 'org' },
          { label: '其他', value: 'other' }
        ]
      }
    }
  ];
  const columns = [
    {
      title: '配置名称',
      dataIndex: 'name',
      key: 'name',
      search: {
        type: 'string'
      },
      align: 'center',
      ellipsis: true
    },
    {
      title: '类型',
      dataIndex: 'targetType',
      key: 'targetType',
      scopedSlots: true,
      align: 'center',
      search: {
        type: 'select',
        options: [
          {
            label: '产品',
            value: 'product'
          },
          {
            label: '设备',
            value: 'device'
          },
          {
            label: '组织',
            value: 'org'
          },
          {
            label: '其他',
            value: 'other'
          }
        ]
      },
      width: 100
    },
    {
      title: '告警级别',
      dataIndex: 'level',
      key: 'level',
      scopedSlots: true,
      align: 'center',
      search: {
        type: 'select',
        options: async () => {
          const res = await queryLevel();
          if (res.code === 200) {
            return (res?.result?.levels || [])
              .filter((i: any) => i?.level && i?.title)
              .map((item: any) => ({
                label: item.title,
                value: item.level
              }));
          }
          return [];
        }
      },
      ellipsis: true
    },
    {
      title: '关联场景联动',
      dataIndex: 'scene',
      align: 'center',
      scopedSlots: true,
      key: 'scene',
      search: {
        type: 'select',
        options: async () => {
          const allData = await queryList({ paging: false, sorts: [{ name: 'createTime', order: 'desc' }] });
          const result = allData.result?.data as any[];
          if (allData.success && result && result.length) {
            const sceneDataMap = new Map(); // 用于去重
            result.forEach((item) => {
              item.scene.forEach((a: any) => {
                sceneDataMap.set(a.id, {
                  label: a.name,
                  value: a.id
                });
              });
            });

            return [...sceneDataMap.values()];
          }
          return [];
        }
      },
      ellipsis: true
    },
    {
      title: '状态',
      dataIndex: 'state',
      key: 'state',
      align: 'center',
      scopedSlots: true,
      search: {
        type: 'select',
        options: [
          {
            label: '正常',
            value: 'enabled'
          },
          {
            label: '禁用',
            value: 'disabled'
          }
        ]
      },
      width: 90
    },
    {
      title: '说明',
      dataIndex: 'description',
      key: 'description',
      search: {
        type: 'string'
      },
      ellipsis: true
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 150,
      scopedSlots: true
    }
  ];
  const visible = ref<boolean>(false);
  const current = ref<any>({});

  const defaultLevel = ref<any[]>([]);
  const map = {
    product: '产品',
    device: '设备',
    org: '组织',
    other: '其他'
  };
  const handleSearch = (e: any) => {
    params.value = e;
  };
  const queryDefaultLevel = () => {
    queryLevel().then((res) => {
      if (res.code === 200) {
        defaultLevel.value = res.result?.levels || [];
      }
    });
  };
  queryDefaultLevel();
  const getActions = (data: Partial<Record<string, any>>, type?: 'card' | 'table'): any[] => {
    if (!data) {
      return [];
    }
    const actions = [
      {
        key: 'tigger',
        text: '手动触发',
        disabled: data?.state?.value === 'disabled',
        tooltip: {
          title: data?.state?.value === 'disabled' ? '未启用,不能手动触发' : '手动触发'
        },
        onClick: () => {
          visible.value = true;
          current.value = data;
        },
        icon: 'LikeOutlined'
      },
      {
        key: 'update',
        text: '编辑',
        tooltip: {
          title: '编辑'
        },

        icon: 'EditOutlined',
        onClick: () => {
          visible.value = true;
          id.value = data.id;
        }
      },
      {
        key: 'action',
        text: data.state?.value !== 'disabled' ? '禁用' : '启用',
        tooltip: {
          title: data.state?.value !== 'disabled' ? '禁用' : '启用'
        },
        icon: data.state?.value !== 'disabled' ? 'StopOutlined' : 'CheckCircleOutlined',
        popConfirm: {
          title: `${data.state?.value !== 'disabled' ? '禁用告警不会影响关联的场景状态，确定要禁用吗' : '确认启用'}?`,
          onConfirm: async () => {
            let response = undefined;
            if (data.state?.value === 'disabled') {
              response = await _enable(data.id);
            } else {
              response = await _disable(data.id);
            }
            if (response) {
              onlyMessage('操作成功！');
              tableRef.value?.reload();
            } else {
              onlyMessage('操作失败！', 'error');
            }
          }
        }
      },
      {
        key: 'delete',
        text: '删除',
        disabled: data?.state?.value !== 'disabled',
        tooltip: {
          title: data?.state?.value !== 'disabled' ? '请先禁用该告警，再删除' : '删除',
          placement: 'topLeft'
        },
        popConfirm: {
          title: '确认删除?',
          onConfirm: async () => {
            const resp = await remove(data.id);
            if (resp) {
              onlyMessage('操作成功！');
              tableRef.value?.reload();
            } else {
              onlyMessage('操作失败！', 'error');
            }
          }
        },
        icon: 'DeleteOutlined'
      }
    ];
    return actions.filter((item) => item.key != 'tigger' || data.sceneTriggerType == 'manual');
  };
  const onSave = () => {
    visible.value = false;
    tableRef.value?.reload();
  };
  const add = () => {
    visible.value = true;
    id.value = undefined;
  };
  const handleView = (_id: string) => {
    id.value = _id;
    nextTick(() => {
      visible.value = true;
    });
  };
</script>
<style lang="less" scoped>
  .content-des-title {
    font-size: 12px;
  }
  :deep(.card .card-warp .card-content) {
    padding: 32px 12px 32px 30px;
  }
  :deep(.jtable-card) {
    min-height: 597px;
  }
  :deep(.ant-pagination-options) {
    display: none;
  }
  :deep(.jtable-body-spin .jtable-body .jtable-pagination) {
    margin-bottom: 8px;
  }
</style>
