<template>
  <SaveChild v-if="childVisible" @close-child-save="closeChildSave" :childData="_current" />
  <div v-else>
    <pro-search :columns="columns" target="child-device" @search="handleSearch" class="device-child-device-search" />
    <JTable
      ref="childDeviceRef"
      :columns="columns"
      :request="query"
      :bodyStyle="{
        padding: 0
      }"
      :defaultParams="{
        terms: [
          {
            column: 'parentId',
            value: detail?.id || '',
            termType: 'eq'
          }
        ]
      }"
      :rowSelection="{
        selectedRowKeys: _selectedRowKeys,
        onChange: onSelectChange
      }"
      :params="params"
      :model="'TABLE'"
    >
      <template #rightExtraRender>
        <Space>
          <PermissionButton
            type="primary"
            v-if="detail?.accessProvider === 'official-edge-gateway'"
            hasPermission="device/Instance:update"
            @click="
              _current = {};
              childVisible = true;
            "
            >新增并绑定</PermissionButton
          >
          <PermissionButton type="primary" @click="visible = true" hasPermission="device/Instance:update">
            绑定
          </PermissionButton>
          <PermissionButton
            type="primary"
            hasPermission="device/Instance:update"
            :popConfirm="{
              title: '确定解绑吗？',
              onConfirm: handleUnBind
            }"
            >批量解除</PermissionButton
          >
        </Space>
      </template>
      <template #registryTime="slotProps">
        {{ slotProps.registryTime ? dayjs(slotProps.registryTime).format('YYYY-MM-DD HH:mm:ss') : '' }}
      </template>
      <template #state="slotProps">
        <Badge :text="slotProps.state.text" :status="statusMap.get(slotProps.state.value)" />
      </template>
      <template #action="slotProps">
        <Space :size="16">
          <template v-for="i in getActions(slotProps, 'table')" :key="i.key">
            <PermissionButton
              v-if="i.key !== 'update' || detail.accessProvider === 'official-edge-gateway'"
              :disabled="i.disabled"
              :popConfirm="i.popConfirm"
              :tooltip="{
                ...i.tooltip
              }"
              @click="i.onClick"
              type="link"
              style="padding: 0px"
              :hasPermission="'device/Instance:' + i.key"
            >
              <template #icon><JAIcon :type="i.icon" /></template>
            </PermissionButton>
          </template>
        </Space>
      </template>
    </JTable>
    <BindChildDevice v-if="visible" :parentIds="parentIds" @change="closeBindDevice" />
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue';
  import dayjs from 'dayjs';
  import { unbindDevice, unbindBatchDevice, deleteDeviceMapping } from '../../../../../api/device/instance';
  import { useInstanceStore } from '@jdlinker/func';
  import { storeToRefs } from 'pinia';
  import BindChildDevice from './BindChildDevice/index.vue';
  import SaveChild from './SaveChild/index.vue';
  import { onlyMessage } from '@jdlinker/utils';
  import JTable from '../../../../../components/UI/Table/index';
  import { JSearch as ProSearch, PermissionButton } from '@jdlinker/ui';
  import { AIcon as JAIcon, Badge, Space } from 'linker-ui-components';
  import { useRouter } from 'vue-router';

  const instanceStore = useInstanceStore();
  const { detail } = storeToRefs(instanceStore);
  const router = useRouter();
  const childVisible = ref(false);
  const statusMap = new Map();
  statusMap.set('online', 'success');
  statusMap.set('offline', 'error');
  statusMap.set('notActive', 'warning');

  const childDeviceRef = ref<Record<string, any>>({});
  const params = ref<Record<string, any>>({});
  const _selectedRowKeys = ref<string[]>([]);
  const visible = ref<boolean>(false);
  const _current = ref({});
  const parentIds = ref<any[]>([instanceStore.detail.id]);

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      ellipsis: true,
      search: {
        type: 'string',
        defaultTermType: 'eq'
      }
    },
    {
      title: '设备名称',
      dataIndex: 'name',
      key: 'name',
      ellipsis: true,
      search: {
        type: 'string'
      }
    },
    {
      title: '所属产品',
      dataIndex: 'productName',
      key: 'productName',
      search: {
        type: 'string'
      }
    },
    {
      title: '注册时间',
      dataIndex: 'registryTime',
      key: 'registryTime',
      scopedSlots: true,
      search: {
        type: 'date'
      }
    },
    {
      title: '状态',
      dataIndex: 'state',
      key: 'state',
      scopedSlots: true,
      search: {
        type: 'select',
        options: [
          { label: '禁用', value: 'notActive' },
          { label: '离线', value: 'offline' },
          { label: '在线', value: 'online' }
        ]
      }
    },
    {
      title: '说明',
      dataIndex: 'describe',
      key: 'describe',
      ellipsis: true,
      search: {
        type: 'string'
      }
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 200,
      scopedSlots: true
    }
  ];

  const getActions = (data: Partial<Record<string, any>>): any[] => {
    if (!data) return [];
    return [
      {
        key: 'view',
        text: '查看',
        tooltip: {
          title: '查看'
        },
        icon: 'EyeOutlined',
        onClick: () => {
          router.push('/iot/device/instance/detail/' + data.id);
        }
      },
      {
        key: 'action',
        text: '解绑',
        tooltip: {
          title: '解绑'
        },
        icon: 'DisconnectOutlined',
        popConfirm: {
          title: '确认解绑吗？',
          okText: '确定',
          cancelText: '取消',
          onConfirm: async () => {
            const resp = await unbindDevice(detail.value.id, data.id, {});
            await deleteDeviceMapping(detail.value.id, { ids: [data.id] });
            if (resp.code === 200) {
              childDeviceRef.value?.reload();
              onlyMessage('操作成功！');
            }
          }
        }
      },
      {
        key: 'update',
        text: '编辑',
        tooltip: {
          title: '编辑'
        },
        icon: 'EditOutlined',
        onClick: () => {
          _current.value = data;
          childVisible.value = true;
        }
      }
    ];
  };

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

  const onSelectChange = (keys: string[]) => {
    _selectedRowKeys.value = [...keys];
  };

  const cancelSelect = () => {
    _selectedRowKeys.value = [];
  };

  const handleUnBind = async () => {
    if (_selectedRowKeys.value.length) {
      const resp = await unbindBatchDevice(detail.value.id, _selectedRowKeys.value);
      if (resp.code === 200) {
        await deleteDeviceMapping(detail.value.id, { ids: [_selectedRowKeys.value] });
        onlyMessage('操作成功！');
        cancelSelect();
        childDeviceRef.value?.reload();
      }
    } else {
      onlyMessage('请勾选需要解绑的数据', 'warning');
    }
  };

  const closeBindDevice = (val: boolean) => {
    visible.value = false;
    if (val) {
      childDeviceRef.value?.reload();
    }
  };

  const closeChildSave = () => {
    childVisible.value = false;
  };
  onMounted(() => {
    console.log(detail.value.accessProvider);
  });
</script>

<style lang="less">
  .device-child-device-search {
    padding: 0px;
  }
</style>
