<template>
  <PageContainer :pageHeaderRender="false" style="padding: 0 10px 10px 10px">
    <ProSearch :columns="searchFormSchema" target="device-instance" @search="handleSearch" />
    <FullPage style="min-height: calc(100vh - 186px)">
      <JTable
        model="CARD"
        :columns="columns"
        :request="queryList"
        ref="tableRef"
        :defaultParams="{
          column: 'createTime',
          order: 'desc',
          pageSize: 9
        }"
        :params="params"
        :gridColumn="3"
      >
        <template #headerTitle>
          <Space>
            <PermissionButton type="primary" @click="add">
              <template #icon><AIcon 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"
            @click="openRuleEditor"
            :statusNames="{
              started: 'processing',
              disable: 'error'
            }"
          >
            <template #img>
              <slot name="img">
                <img :src="getImage('/scene/trigger-type/scene.png')" />
              </slot>
            </template>
            <template #content>
              <Ellipsis style="width: calc(100% - 100px); margin-bottom: 18px">
                <span style="font-weight: 600; font-size: 16px">
                  {{ slotProps.name }}
                </span>
              </Ellipsis>
              <Row>
                <Col :span="12">
                  <Ellipsis>
                    <div>
                      {{ slotProps.description }}
                    </div>
                  </Ellipsis>
                </Col>
              </Row>
            </template>
            <template #actions="item">
              <PermissionButton
                :disabled="item.disabled"
                :popConfirm="item.popConfirm"
                :tooltip="{
                  ...item.tooltip
                }"
                @click="item.onClick"
              >
                <AIcon type="DeleteOutlined" v-if="item.key === 'delete'" />
                <template v-else>
                  <AIcon :type="item.icon" />
                  <span>{{ item?.text }}</span>
                </template>
              </PermissionButton>
            </template>
          </CardBox>
        </template>
        <template #state="slotProps">
          <BadgeStatus
            :text="slotProps.state?.value === 'started' ? '正常' : '禁用'"
            :status="slotProps.state?.value"
            :statusNames="{
              started: 'processing',
              disable: '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><AIcon :type="i.icon" /></template>
              </PermissionButton>
            </template>
          </Space>
        </template>
      </JTable>
    </FullPage>
    <!-- 新增、编辑 -->
    <Save ref="saveRef" :data="current" @success="refresh" v-if="visiable" @close-save="closeSave" />
  </PageContainer>
</template>

<script lang="ts" setup>
  import { queryList, startRule, stopRule, deleteRule } from '../../../api/rule-engine/instance';
  import { getImage, onlyMessage, SystemConst } from '@jdlinker/utils';
  import Save from './Save/index.vue';
  import { ref, onMounted, nextTick } from "vue";
  import JTable from '../../../components/UI/Table/index';
  import { FormSchema, JSearch as ProSearch, FullPage, PermissionButton, CardBox, BadgeStatus } from '@jdlinker/ui';
  import { PageContainer, AIcon, Space, Ellipsis, Row, Col } from 'linker-ui-components';

  const saveRef = ref();
  const params = ref<any>({});
  let visiable = ref(false);
  const tableRef = ref<any>({});
  const searchFormSchema: FormSchema[] = [
    {
      label: '规则名称',
      field: 'name',
      component: 'Input'
    },
    {
      label: '状态',
      field: 'stateExpand',
      component: 'Select',
      componentProps: {
        options: [
          {
            label: '正常',
            value: 'started'
          },
          {
            label: '禁用',
            value: 'disable'
          }
        ]
      }
    }
  ];
  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '状态',
      dataIndex: 'state',
      key: 'state',
      scopedSlots: true
    },
    {
      title: '说明',
      dataIndex: 'description',
      key: 'description'
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 250,
      scopedSlots: true
    }
  ];
  const current = ref();
  const getActions = (data: Partial<Record<string, any>>, type?: 'card' | 'table'): any[] => {
    if (!data) {
      return [];
    }
    const actions = [
      {
        key: 'update',
        text: '编辑',
        tooltip: {
          title: '编辑'
        },

        icon: 'EditOutlined',
        onClick: () => {
          current.value = data;
          visiable.value = true;
          nextTick(() => {
            saveRef.value.show(current.value);
          });
        }
      },
      {
        key: 'view',
        text: '查看',
        tooltip: {
          title: '查看'
        },
        icon: 'EyeOutlined',
        onClick: () => {
          openRuleEditor(data);
        }
      },
      {
        key: 'action',
        text: data.state?.value !== 'disable' ? '禁用' : '启用',
        tooltip: {
          title: data.state?.value !== 'disable' ? '禁用' : '启用'
        },
        icon: data.state?.value !== 'disable' ? 'StopOutlined' : 'CheckCircleOutlined',
        popConfirm: {
          title: `确认${data.state !== 'disable' ? '禁用' : '启用'}?`,
          onConfirm: async () => {
            let response: any = undefined;
            if (data.state?.value !== 'started') {
              response = await startRule(data.id);
            } else {
              response = await stopRule(data.id);
            }
            if (response && response.code === 200) {
              onlyMessage('操作成功！', 'success');
              tableRef.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 deleteRule(data.id);
            if (resp.code === 200) {
              onlyMessage('操作成功！', 'success');
              tableRef.value?.reload();
            } else {
              onlyMessage('操作失败！', 'error');
            }
          }
        },
        icon: 'DeleteOutlined'
      }
    ];
    if (type === 'card') return actions.filter((i: any) => i.key !== 'view');
    return actions;
  };
  const add = () => {
    (current.value = {
      name: '',
      description: ''
    }),
      (visiable.value = true);
      nextTick(() => {
        saveRef.value.show(current.value);
      });
  };
  /**
   * 刷新数据
   */
  const refresh = () => {
    tableRef.value?.reload();
  };
  const handleSearch = (e: any) => {
    params.value = e;
  };
  const openRuleEditor = (item: any) => {
    window.open(`/${SystemConst.API_BASE}/rule-editor/index.html#flow/${item.id}`);
  };
  const closeSave = () => {
    visiable.value = false;
  };
  onMounted(() => {
    if (history.state?.params) {
      add();
    }
  });
</script>
<style scoped lang="less">
  :deep(.card .card-warp .card-content) {
    padding: 32px 12px 32px 30px;
  }
  :deep(.jtable-card) {
    min-height: 597px;
  }
  :deep(.ant-pagination-options) {
    display: none;
  }
</style>
