import { ColumnDrawer as DeviceCategoryColumnDrawer } from '@/pages/Device/DeviceCategoryList/components/ColumnDrawer';
import { DeviceCategoryColumns } from '@/pages/Device/DeviceCategoryList/components/Columns';
import { ColumnDrawer as DeviceGroupColumnDrawer } from '@/pages/Device/DeviceGroupList/components/ColumnDrawer';
import { DeviceGroupColumns } from '@/pages/Device/DeviceGroupList/components/Columns';
import {
  deleteDeviceDeleteDevice,
  deleteDeviceDeleteDeviceByIds,
  postDeviceCloseRtspCamera,
  postDeviceGetDeviceList,
  postDeviceOpenRtspCamera,
} from '@/services/device/Device';
import {
  postDeviceCategoryGetDeviceCategoryById,
  postDeviceCategoryGetDeviceCategoryFkSelect,
  postDeviceCategoryGetDeviceCategoryNames,
} from '@/services/device/DeviceCategory';
import {
  postDeviceGroupGetDeviceGroupById,
  postDeviceGroupGetDeviceGroupFkSelect,
  postDeviceGroupGetDeviceGroupNames,
  postDeviceGroupGetDeviceGroupTree,
} from '@/services/device/DeviceGroup';
import { PlusOutlined, RedoOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {
  FooterToolbar,
  PageContainer,
  ProCard,
  ProFormSelect,
  ProFormText,
  ProTable,
} from '@ant-design/pro-components';
import { Access, FormattedMessage, history, useAccess, useIntl } from '@umijs/max';
import { Button, Popconfirm, Tree, message } from 'antd';
import { DataNode } from 'antd/es/tree';
import React, { useEffect, useRef, useState } from 'react';
import { ColumnDrawer } from './components/ColumnDrawer';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import VideoModal from './components/VideoModal';

const DeviceList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [videoModalOpen, setVideoModalOpen] = useState<boolean>(false);

  const [createModalOpen, setCreateModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalOpen, setUpdateModalOpen] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const access = useAccess();
  const intl = useIntl();
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.Device>();
  const [selectedRowsState, setSelectedRows] = useState<API.Device[]>([]);
  const [category_fk_id_open, set_category_fk_id_open] = useState(false);
  const [category_fk_id, set_category_fk_id] = useState<API.DeviceCategory>();
  const [category_fk_id_column_open, set_category_fk_id_column_open] = useState(false);
  const [categoryFkIdIds, setCategoryFkIdIds] = useState([]);
  const [categoryFkIdMap, setCategoryFkIdMap] = useState<{ [key: number]: string }>({});
  const [group_fk_id_open, set_group_fk_id_open] = useState(false);
  const [group_fk_id, set_group_fk_id] = useState<API.DeviceGroup>();
  const [group_fk_id_column_open, set_group_fk_id_column_open] = useState(false);
  const [groupFkIdIds, setGroupFkIdIds] = useState([]);
  const [groupFkIdMap, setGroupFkIdMap] = useState<{ [key: number]: string }>({});

  const [hasInit, setHasInit] = useState<boolean>(false);
  const [nodeTreeData, setNodeTreeData] = React.useState<DataNode[]>([]);
  const [selectNodes, setSelectNodes] = React.useState<any[]>([]);
  const [videoOpening, setVideoOpening] = useState<boolean>(false);
  const [videoServerParam, setVideoServerParam] = useState<API.RtspRes>({});
  useEffect(() => {
    postDeviceGroupGetDeviceGroupTree()
      .then((resp) => {
        setNodeTreeData(resp.data.tree);
        setHasInit(true);
      })
      .catch(() => {
        message.error(intl.formatMessage({ id: 'common.failure', defaultMessage: '$$$' }));
      });
  }, []);
  const handleVideoModal = () => {
    if (videoModalOpen) {
      setVideoModalOpen(false);
      if (videoServerParam?.pid || 0) {
        postDeviceCloseRtspCamera({ pid: videoServerParam.pid }).then((resp) => {
          console.log(resp);
        });
      }
      setCurrentRow(undefined);
      setVideoServerParam({});
    } else {
      setVideoModalOpen(true);
    }
  };
  const handle_category_fk_id = (id: any) => {
    if (category_fk_id_open) {
      set_category_fk_id(undefined);
      set_category_fk_id_open(false);
    } else {
      postDeviceCategoryGetDeviceCategoryById({ id: id }).then((resp) => {
        set_category_fk_id(resp.data.deviceCategory);
        set_category_fk_id_open(true);
      });
    }
  };
  const handle_category_fk_id_column_open = () => {
    if (category_fk_id_column_open) {
      set_category_fk_id_column_open(false);
    } else {
      postDeviceCategoryGetDeviceCategoryNames({ ids: categoryFkIdIds }).then((resp) => {
        let a: any = {};
        resp.data.list.forEach((v: any) => {
          if (v.id) {
            a[v.id] = v.name;
          }
        });
        setCategoryFkIdMap(a);
      });
      set_category_fk_id_column_open(true);
    }
  };
  const handle_group_fk_id = (id: any) => {
    if (group_fk_id_open) {
      set_group_fk_id(undefined);
      set_group_fk_id_open(false);
    } else {
      postDeviceGroupGetDeviceGroupById({ id: id }).then((resp) => {
        set_group_fk_id(resp.data.deviceGroup);
        set_group_fk_id_open(true);
      });
    }
  };
  const handle_group_fk_id_column_open = () => {
    if (group_fk_id_column_open) {
      set_group_fk_id_column_open(false);
    } else {
      postDeviceGroupGetDeviceGroupNames({ ids: groupFkIdIds }).then((resp) => {
        let a: any = {};
        resp.data.list.forEach((v: any) => {
          if (v.id) {
            a[v.id] = v.name;
          }
        });
        setGroupFkIdMap(a);
      });
      set_group_fk_id_column_open(true);
    }
  };

  const handleUpdateModal = () => {
    if (updateModalOpen) {
      setUpdateModalOpen(false);
      setCurrentRow(undefined);
    } else {
      setUpdateModalOpen(true);
    }
  };
  const handleCreateModal = () => {
    if (createModalOpen) {
      setCreateModalOpen(false);
      setCurrentRow(undefined);
    } else {
      setCreateModalOpen(true);
    }
  };
  const handleColumnDrawer = () => {
    if (showDetail) {
      setShowDetail(false);
      setCurrentRow(undefined);
    } else {
      setShowDetail(true);
    }
  };
  const handleDestroy = async (selectedRow: API.Device) => {
    deleteDeviceDeleteDevice({ id: selectedRow.id })
      .then(() => {
        message.success(intl.formatMessage({ id: 'common.success', defaultMessage: '$$$' }));
        actionRef.current?.reload();
      })
      .catch(() => {
        message.error(intl.formatMessage({ id: 'common.failure', defaultMessage: '$$$' }));
      });
  };

  const columns: ProColumns<API.Device>[] = [
    {
      title: <FormattedMessage id="device.device.table.list.id" defaultMessage="id" />,
      dataIndex: 'id',
      sorter: true,
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
      renderFormItem: () => {
        return (
          <>
            <ProFormText
              width="md"
              labelCol={{ span: 4 }}
              wrapperCol={{ span: 22 }}
              name="id"
              placeholder={`${intl.formatMessage({
                id: 'common.please_input',
                defaultMessage: '$$$',
              })}`}
              required={false}
            />
          </>
        );
      },
    },

    {
      title: <FormattedMessage id="device.device.table.list.name" defaultMessage="$$$" />,
      dataIndex: 'name',
      hideInSearch: true,
    },

    {
      title: <FormattedMessage id="device.device.table.list.code" defaultMessage="$$$" />,
      dataIndex: 'code',
      hideInSearch: true,
    },

    {
      title: <FormattedMessage id="device.device.table.list.position" defaultMessage="$$$" />,
      dataIndex: 'position',
      hideInSearch: true,
    },

    {
      title: <FormattedMessage id="device.device.table.list.param" defaultMessage="$$$" />,
      dataIndex: 'param',
      hideInSearch: true,
    },

    {
      title: <FormattedMessage id="device.device.table.list.spec" defaultMessage="$$$" />,
      dataIndex: 'spec',
      hideInSearch: true,
    },

    {
      title: <FormattedMessage id="device.device.table.list.categoryFkId" defaultMessage="$$$" />,
      dataIndex: 'categoryFkId',
      hideInSearch: false,
      render: (text, record) => {
        if (category_fk_id_column_open) {
          return (
            <a
              onClick={() => {
                handle_category_fk_id(record.categoryFkId);
              }}
            >
              {record?.categoryFkId ? categoryFkIdMap[record.categoryFkId] : undefined}
            </a>
          );
        } else {
          return (
            <a
              onClick={() => {
                handle_category_fk_id(record.categoryFkId);
              }}
            >
              {record.categoryFkId}
            </a>
          );
        }
      },
      renderFormItem: () => {
        return (
          // value 和 onchange 会通过 form 自动注入。
          <ProFormSelect
            width="md"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 22 }}
            placeholder={`${intl.formatMessage({
              id: 'common.please_select',
              defaultMessage: '$$$',
            })}`}
            required={false}
            showSearch
            debounceTime={1000}
            request={async (keyWord) => {
              const resp = await postDeviceCategoryGetDeviceCategoryFkSelect({
                keyword: keyWord?.keyWords || '',
              });
              return resp.data.list.map((v: any) => {
                return {
                  label: v.name,
                  value: v.id,
                };
              });
            }}
          />
        );
      },
    },

    {
      title: <FormattedMessage id="device.device.table.list.groupFkId" defaultMessage="$$$" />,
      dataIndex: 'groupFkId',
      hideInSearch: false,
      render: (text, record) => {
        if (group_fk_id_column_open) {
          return (
            <a
              onClick={() => {
                handle_group_fk_id(record.groupFkId);
              }}
            >
              {record?.groupFkId ? groupFkIdMap[record.groupFkId] : undefined}
            </a>
          );
        } else {
          return (
            <a
              onClick={() => {
                handle_group_fk_id(record.groupFkId);
              }}
            >
              {record.groupFkId}
            </a>
          );
        }
      },
      renderFormItem: () => {
        return (
          // value 和 onchange 会通过 form 自动注入。
          <ProFormSelect
            width="md"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 22 }}
            placeholder={`${intl.formatMessage({
              id: 'common.please_select',
              defaultMessage: '$$$',
            })}`}
            required={false}
            showSearch
            debounceTime={1000}
            request={async (keyWord) => {
              const resp = await postDeviceGroupGetDeviceGroupFkSelect({
                keyword: keyWord?.keyWords || '',
              });
              return resp.data.list.map((v: any) => {
                return {
                  label: v.name,
                  value: v.id,
                };
              });
            }}
          />
        );
      },
    },

    {
      title: <FormattedMessage id="device.device.table.list.isEnable" defaultMessage="$$$" />,
      dataIndex: 'isEnable',
      filters: true,
      onFilter: true,
      hideInSearch: true,
      valueType: 'switch',
    },

    {
      title: <FormattedMessage id="device.device.table.list.remark" defaultMessage="$$$" />,
      dataIndex: 'remark',
      hideInSearch: true,
    },

    {
      title: <FormattedMessage id="device.device.table.list.createTime" defaultMessage="$$$" />,
      dataIndex: 'createTime',
      sorter: true,
      hideInSearch: true,
      valueType: 'dateTime',
    },

    {
      title: <FormattedMessage id="device.device.table.list.updateTime" defaultMessage="$$$" />,
      dataIndex: 'updateTime',
      sorter: true,
      hideInSearch: true,
      valueType: 'dateTime',
    },

    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="Operating" />,
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      width: 250,
      render: (_, record) => [
        <Access
          accessible={access.canUpdate(history.location.pathname)}
          key={`${history.location.pathname}-add`}
        >
          <Button
            key="update"
            type="link"
            size="small"
            onClick={() => {
              setUpdateModalOpen(true);
              setCurrentRow(record);
            }}
          >
            <FormattedMessage id="pages.searchTable.update" defaultMessage="Update" />
          </Button>
          <Popconfirm
            placement="topLeft"
            title={intl.formatMessage({ id: 'common.tip.title', defaultMessage: '$$$' })}
            description={intl.formatMessage({
              id: 'common.modal.table.delete.content',
              defaultMessage: '$$$',
            })}
            okText={intl.formatMessage({ id: 'common.yes', defaultMessage: '$$$' })}
            cancelText={intl.formatMessage({ id: 'common.no', defaultMessage: '$$$' })}
            onConfirm={() => {
              handleDestroy(record).then(() => {});
            }}
          >
            <Button key="destroy" type="link" size="small" danger>
              <FormattedMessage id="pages.searchTable.destroy" defaultMessage="Destroy" />
            </Button>
          </Popconfirm>
          <Button
            key="video"
            type="link"
            size="small"
            onClick={() => {
              setVideoOpening(true);
              if (record.param) {
                postDeviceOpenRtspCamera({ url: record.param })
                  .then((resp) => {
                    setVideoServerParam(resp.data);
                    setVideoOpening(false);
                    setVideoModalOpen(true);
                    console.log(resp.data);
                    setCurrentRow(record);
                  })
                  .catch(() => {
                    setVideoOpening(false);
                    message.error(
                      intl.formatMessage({ id: 'common.open_failure', defaultMessage: '$$$' }),
                    );
                  });
              } else {
                setVideoOpening(false);
                message.error(
                  intl.formatMessage({ id: 'common.open_failure', defaultMessage: '$$$' }),
                );
              }
            }}
          >
            <FormattedMessage id="common.open_video" defaultMessage="$$$" />
          </Button>
        </Access>,
      ],
    },
  ];
  return (
    <PageContainer>
      <ProCard split="vertical">
        <ProCard
          title="网点选择"
          colSpan="20%"
          extra={
            <Button
              icon={<RedoOutlined />}
              onClick={() => {
                setSelectNodes([]);
                actionRef.current?.reload();
              }}
            >
              重置
            </Button>
          }
        >
          {hasInit && (
            <Tree
              checkable={false}
              defaultExpandAll={true}
              selectedKeys={selectNodes}
              treeData={nodeTreeData}
              onSelect={(selectKeys) => {
                setSelectNodes(selectKeys);
                actionRef.current?.reload();
              }}
            />
          )}
        </ProCard>
        <ProCard title="" headerBordered>
          <ProTable<API.Device>
            headerTitle={intl.formatMessage({
              id: 'pages.searchTable.title',
              defaultMessage: '$$$',
            })}
            loading={{
              tip: intl.formatMessage({
                id: 'common.video_opening',
                defaultMessage: '$$$',
              }),
              spinning: videoOpening,
            }}
            options={{ fullScreen: true, setting: true, density: true, reload: true }}
            actionRef={actionRef}
            rowKey="key"
            scroll={{ x: 1600 }}
            search={{
              labelWidth: 120,
            }}
            onDataSourceChange={(data) => {
              let CategoryFkIdIds: any = data.map((v) => {
                return v.categoryFkId;
              });
              setCategoryFkIdIds(CategoryFkIdIds);

              let GroupFkIdIds: any = data.map((v) => {
                return v.groupFkId;
              });
              setGroupFkIdIds(GroupFkIdIds);
            }}
            pagination={{
              showSizeChanger: true,
              pageSize: 10,
            }}
            columnsState={{
              persistenceKey: 'device_list',
              persistenceType: 'localStorage',
            }}
            toolBarRender={() => [
              <Access
                accessible={access.canUpdate(history.location.pathname)}
                key={`${history.location.pathname}-add`}
              >
                <Button
                  type="primary"
                  key="category_fk_id_show"
                  onClick={() => {
                    handle_category_fk_id_column_open();
                  }}
                >
                  {category_fk_id_column_open ? (
                    <FormattedMessage id="common.hide" defaultMessage="$$$" />
                  ) : (
                    <FormattedMessage id="common.show" defaultMessage="$$$" />
                  )}
                  <FormattedMessage
                    id="device.device.table.list.categoryFkId"
                    defaultMessage="$$$"
                  />
                </Button>

                <Button
                  type="primary"
                  key="group_fk_id_show"
                  onClick={() => {
                    handle_group_fk_id_column_open();
                  }}
                >
                  {group_fk_id_column_open ? (
                    <FormattedMessage id="common.hide" defaultMessage="$$$" />
                  ) : (
                    <FormattedMessage id="common.show" defaultMessage="$$$" />
                  )}
                  <FormattedMessage id="device.device.table.list.groupFkId" defaultMessage="$$$" />
                </Button>

                <Button
                  type="primary"
                  key="primary"
                  onClick={() => {
                    setCreateModalOpen(true);
                  }}
                >
                  <PlusOutlined />{' '}
                  <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
                </Button>
              </Access>,
            ]}
            request={async (params = {}, sort) => {
              const { current, ...rest } = params;
              const reqParams: any = {
                page: current,
                desc: false,
                orderKey: '',
                ...rest,
              };
              if (selectNodes.length) {
                reqParams.groupFkId = selectNodes[0];
              }
              if (sort && Object.keys(sort).length) {
                reqParams.orderKey = Object.keys(sort)[0];
                let sort_select = sort[reqParams.orderKey];
                reqParams.desc = sort_select === 'descend';
              }
              let resp = await postDeviceGetDeviceList({ ...reqParams });
              return {
                data: resp.data.list.map((v: API.Device) => {
                  return { ...v, key: v.id };
                }),
                success: resp.success,
                total: resp.data.total,
                current: resp.data.page,
                pageSize: resp.data.pageSize,
              };
            }}
            columns={columns}
            rowSelection={{
              onChange: (_, selectedRows) => {
                setSelectedRows(selectedRows);
              },
            }}
          />
          {selectedRowsState?.length > 0 && (
            <FooterToolbar
              extra={
                <div>
                  <FormattedMessage id="pages.searchTable.chosen" defaultMessage="Chosen" />{' '}
                  <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
                  <FormattedMessage id="pages.searchTable.item" defaultMessage="$$$" />
                </div>
              }
            >
              <Button
                onClick={async () => {
                  deleteDeviceDeleteDeviceByIds({
                    ids: selectedRowsState.map((v: API.Device) => {
                      return v.id as number;
                    }),
                  }).then(() => {
                    actionRef.current?.reloadAndRest?.();
                  });
                }}
              >
                <FormattedMessage
                  id="pages.searchTable.batchDeletion"
                  defaultMessage="Batch deletion"
                />
              </Button>
            </FooterToolbar>
          )}
        </ProCard>
      </ProCard>
      <CreateForm
        createModalOpen={createModalOpen}
        values={currentRow || {}}
        handleModal={handleCreateModal}
        reload={actionRef.current?.reload}
      />
      <UpdateForm
        updateModalOpen={updateModalOpen}
        values={currentRow || {}}
        handleModal={handleUpdateModal}
        reload={actionRef.current?.reload}
      />

      <ColumnDrawer
        handleDrawer={handleColumnDrawer}
        isShowDetail={showDetail}
        columns={columns}
        currentRow={currentRow}
      />
      <DeviceCategoryColumnDrawer
        handleDrawer={handle_category_fk_id}
        isShowDetail={category_fk_id_open}
        columns={DeviceCategoryColumns}
        currentRow={category_fk_id}
      />
      <DeviceGroupColumnDrawer
        handleDrawer={handle_group_fk_id}
        isShowDetail={group_fk_id_open}
        columns={DeviceGroupColumns}
        currentRow={group_fk_id}
      />
      <VideoModal
        modalOpen={videoModalOpen}
        handleModal={handleVideoModal}
        values={currentRow || {}}
        videoServerParam={videoServerParam}
        reload={actionRef.current?.reload}
      />
    </PageContainer>
  );
};

export default DeviceList;
