<template>
  <PageContainer v-if="!visibleIndex" :pageHeaderRender="false" style="padding: 0 10px 10px 10px">
    <pro-search :columns="searchFormSchema" target="scene" @search="handleSearch" />
    <FullPage style="min-height: calc(100vh - 170px)">
      <JTable
        model="CARD"
        :columns="columns"
        :request="list"
        ref="tableRef"
        :defaultParams="{
          column: 'createTime',
          order: 'desc',
          pageSize: 9
        }"
        :params="params"
        :gridColumn="3"
      >
        <template #headerTitle>
          <Space>
            <PermissionButton type="primary" @click="handleAdd">
              <template #icon>
                <JAIcon type="PlusOutlined" />
              </template>
              新增
            </PermissionButton>
          </Space>
        </template>
        <template #card="slotProps">
          <CardBox
            :value="slotProps"
            @click="handleView(slotProps.id, slotProps.triggerType)"
            :actions="getActions(slotProps, 'card')"
            :status="slotProps.state?.value"
            :statusText="slotProps.state?.text"
            :statusNames="{
              started: 'processing',
              disable: 'error'
            }"
          >
            <template #type>
              <span
                ><img :height="16" :src="typeMap.get(slotProps.triggerType)?.icon" style="margin-right: 5px" />{{
                  typeMap.get(slotProps.triggerType)?.text
                }}</span
              >
            </template>
            <template #img>
              <img :src="typeMap.get(slotProps.triggerType)?.img" />
            </template>
            <template #content>
              <Ellipsis style="width: calc(100% - 100px)">
                <span style="font-size: 16px; font-weight: 600">
                  {{ slotProps.name }}
                </span>
              </Ellipsis>
              <div class="subTitle">
                <span class="subTitle-title"> 说明： </span>
                <span class="subTitle-content">
                  <Ellipsis :lineClamp="2">
                    {{ slotProps?.description ? slotProps?.description : typeMap.get(slotProps.triggerType)?.tip }}
                  </Ellipsis>
                </span>
              </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 #triggerType="slotProps">
          {{ typeMap.get(slotProps.triggerType)?.text }}
        </template>
        <template #state="slotProps">
          <BadgeStatus
            :status="slotProps.state?.value"
            :text="slotProps.state?.text"
            :statusNames="{
              enabled: 'processing',
              disabled: 'error'
            }"
          />
        </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
                }"
                @click="i.onClick"
                type="link"
                :danger="i.key === 'delete'"
                style="padding: 0 5px"
              >
                <template #icon>
                  <JAIcon :type="i.icon" />
                </template>
              </PermissionButton>
            </template>
          </Space>
        </template>
      </JTable>
    </FullPage>
  </PageContainer>
  <SaveModal v-if="visible" ref="saveRef" @close="closeSave" :data="current" />
  <Index v-if="visibleIndex" @close="visibleIndex = false" :id="sceneId" />
</template>

<script setup lang="ts" name="Scene">
  import SaveModal from './Save/save.vue';
  import Index from './Save/index.vue';
  import { list, _delete, _action, _execute } from '../../../api/rule-engine/scene';
  import { getImage, onlyMessage } from '@jdlinker/utils';
  import { nextTick, ref } from 'vue';
  import { FormSchema, JSearch as ProSearch, FullPage, PermissionButton, CardBox, BadgeStatus } from '@jdlinker/ui';
  import JTable from '../../../components/UI/Table/index';
  // @ts-ignore
  import { PageContainer, AIcon as JAIcon, Ellipsis, Space } from 'linker-ui-components';

  const visible = ref<boolean>(false);
  const visibleIndex = ref<boolean>(false);
  const current = ref<Record<string, any>>({});
  const sceneId = ref<string>('');
  const saveRef = ref();

  const statusMap = new Map();
  statusMap.set('started', 'success');
  statusMap.set('disable', 'error');

  const params = ref<Record<string, any>>({});
  const sceneRef = ref<Record<string, any>>({});

  const typeMap = new Map();
  typeMap.set('manual', {
    text: '手动触发',
    img: getImage('/scene/scene-hand.png'),
    icon: getImage('/scene/trigger-type-icon/manual.png'),
    tip: '适用于第三方平台向物联网平台下发指令控制设备'
  });
  typeMap.set('timer', {
    text: '定时触发',
    img: getImage('/scene/scene-timer.png'),
    icon: getImage('/scene/trigger-type-icon/timing.png'),
    tip: '适用于定期执行固定任务'
  });
  typeMap.set('device', {
    text: '设备触发',
    img: getImage('/scene/scene-device.png'),
    icon: getImage('/scene/trigger-type-icon/device.png'),
    tip: '适用于设备数据或行为满足触发条件时，执行指定的动作'
  });
  const searchFormSchema: FormSchema[] = [
    {
      label: '场景名称',
      field: 'name',
      component: 'Input'
    },
    {
      field: 'triggerType',
      label: '触发方式',
      component: 'Select',
      componentProps: {
        options: Array.from(typeMap).map((item) => {
          return {
            label: item[1]?.text,
            value: item[0]
          };
        })
      }
    },
    {
      field: 'stateExpand',
      label: '状态',
      component: 'Select',
      componentProps: {
        options: [
          { label: '正常', value: 'started' },
          { label: '禁用', value: 'disable' }
        ]
      }
    }
  ];
  const columns = [
    {
      dataIndex: 'name',
      ellipsis: true,
      align: 'center',
      title: '名称',
      search: {
        type: 'string'
      }
    },
    {
      dataIndex: 'triggerType',
      title: '触发方式',
      scopedSlots: true,
      align: 'center',
      search: {
        type: 'select',
        options: Array.from(typeMap).map((item) => {
          return {
            label: item[1]?.text,
            value: item[0]
          };
        })
      }
    },
    {
      dataIndex: 'state',
      title: '状态',
      scopedSlots: true,
      align: 'center',
      search: {
        type: 'select',
        options: [
          { label: '正常', value: 'started' },
          { label: '禁用', value: 'disable' }
        ]
      }
    },
    {
      dataIndex: 'description',
      title: '说明',
      ellipsis: true,
      align: 'center',
      search: {
        type: 'string'
      },
      scopedSlots: true
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'left',
      width: 200,
      scopedSlots: true
    }
  ];

  const getActions = (data: Partial<Record<string, any>>, type: 'card' | 'table'): any[] => {
    if (!data) return [];
    const actions: any[] = [
      {
        key: 'update',
        text: '编辑',
        tooltip: {
          title: '编辑'
        },
        icon: 'EditOutlined',
        onClick: () => {
          visible.value = true;
          current.value = data;
          nextTick(() => {
            saveRef.value.show(current.value);
          });
        }
      },
      {
        key: 'action',
        text: data.state?.value !== 'disable' ? '禁用' : '启用',
        tooltip: {
          title: !(!!data.triggerType && (data.branches || [])?.length)
            ? '未配置规则的不能启用'
            : data.state?.value !== 'disable'
            ? '禁用'
            : '启用'
        },
        disabled: !(!!data?.triggerType && (data?.branches || [])?.length),
        icon: data.state.value !== 'disable' ? 'StopOutlined' : 'CheckCircleOutlined',
        popConfirm: {
          title: `确认${data.state.value !== 'disable' ? '禁用' : '启用'}?`,
          onConfirm: async () => {
            let response = undefined;
            if (data.state.value !== 'disable') {
              response = await _action(data.id, '_disable');
            } else {
              response = await _action(data.id, '_enable');
            }
            if (response) {
              onlyMessage('操作成功！', 'success');
              sceneRef.value?.reload();
            } else {
              onlyMessage('操作失败！', 'error');
            }
          }
        }
      },
      {
        key: 'delete',
        text: '删除',
        disabled: data.state?.value !== 'disable',
        tooltip: {
          title: data.state.value !== 'disable' ? '请先禁用该场景,再删除' : '删除'
        },
        popConfirm: {
          title: '确认删除?',
          onConfirm: async () => {
            const resp = await _delete(data.id);
            if (resp) {
              onlyMessage('删除成功！', 'success');
              sceneRef.value?.reload();
            } else {
              onlyMessage('删除失败！', 'error');
            }
          }
        },
        icon: 'DeleteOutlined'
      }
    ];
    if (data.triggerType === 'manual') {
      const _item: any = {
        key: 'tigger',
        text: '手动触发',
        disabled: data.state?.value === 'disable',
        tooltip: {
          title: data.state.value !== 'disable' ? '手动触发' : '未启用，不能手动触发'
        },
        icon: 'LikeOutlined',
        popConfirm: {
          title: '确认手动触发？',
          onConfirm: async () => {
            const resp = await _execute(data.id);
            if (resp) {
              onlyMessage('操作成功！', 'success');
              sceneRef.value?.reload();
            } else {
              onlyMessage('操作失败！', 'error');
            }
          }
        }
      };
      actions.splice(1, 0, _item);
    }
    if (type === 'table') {
      actions.splice(0, 0, {
        key: 'view',
        text: '查看',
        tooltip: {
          title: '查看'
        },
        icon: 'EyeOutlined',
        onClick: () => {
          handleView(data.id, data.triggerType);
        }
      });
    }
    return actions;
  };

  const handleSearch = (_params: any) => {
    params.value = _params;
  };

  const handleAdd = () => {
    visible.value = true;
    current.value = {};
    nextTick(() => {
      saveRef.value.show(current.value);
    });
  };

  /**
   * 查看
   * @param id
   * @param triggerType 触发类型
   */
  const handleView = (id: string, triggerType: string) => {
    visibleIndex.value = true;
    sceneId.value = id;
    // menuStory.jumpPage(
    //   'rule-engine/Scene/Save',
    //   {},
    //   {triggerType: triggerType, id, type: 'view'},
    // );
  };

  const close = () => {
    visible.value = false;
    sceneRef.value?.reload();
  };
  const openSave = (id, data) => {
    current.value = data;
    sceneId.value = id;
    visible.value = false;
    visibleIndex.value = true;
  };
  const cancel = () => {
    visible.value = false;
  };

  const closeSave = (_id) => {
    visible.value = false;
    if (_id) {
      visibleIndex.value = true;
      sceneId.value = _id;
    }
  };
</script>

<style scoped lang="less">
  .subTitle {
    position: relative;
    margin-top: 18px;
    display: inline-block;
    height: 50px;

    .subTitle-title {
      position: absolute;
      top: 0;
      left: 0;
    }

    .subTitle-content {
      color: rgba(0, 0, 0, 0.65);
      font-size: 12px;
      text-indent: 38px;
    }
  }

  :deep(img) {
    display: inline-block;
  }
  :deep(.card .card-warp .card-content) {
    padding: 31px 12px 20px 30px;
  }
  :deep(.jtable-card) {
    min-height: 597px;
  }
  :deep(.ant-pagination-options) {
    display: none;
  }
</style>
<style lang="less">
.j-ellipsis-line-clamp {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  word-break: break-all;
}
.j-ellipsis {
  overflow: hidden;
  vertical-align: bottom;
}
</style>
