import {DeviceColumns} from '@/pages/Device/DeviceList/components/Columns';
import {postDeviceGetDeviceById, postDeviceGetDeviceFkSelect, postDeviceGetDeviceNames} from '@/services/device/Device';
import {ColumnDrawer as DeviceColumnDrawer} from "@/pages/Device/DeviceList/components/ColumnDrawer";
import {deleteDeviceRelationDeleteDeviceRelation, postDeviceRelationGetDeviceRelationList, deleteDeviceRelationDeleteDeviceRelationByIds} from '@/services/device/DeviceRelation';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {
  FooterToolbar,
  PageContainer,
  ProTable,
  ProFormSelect,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl, useAccess, Access, history } from '@umijs/max';
import {Button, message} from 'antd';
import React, { useRef, useState } from 'react';
import UpdateForm from './components/UpdateForm';
import CreateForm from "./components/CreateForm";
import {ColumnDrawer} from "./components/ColumnDrawer";
const DeviceRelationList: React.FC = () => {
      /**
       * @en-US Pop-up window of new window
       * @zh-CN 新建窗口的弹窗
       *  */
      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.DeviceRelation>();
      const [selectedRowsState, setSelectedRows] = useState<API.DeviceRelation[]>([]);
      const [device_parent_fk_id_open, set_device_parent_fk_id_open] = useState(false)
      const [device_parent_fk_id, set_device_parent_fk_id] = useState<API.Device>()
      const [device_parent_fk_id_column_open, set_device_parent_fk_id_column_open] = useState(false)
      const [deviceParentFkIdIds, setDeviceParentFkIdIds] = useState([])
      const [deviceParentFkIdMap, setDeviceParentFkIdMap] = useState<{ [key: number]: string }>({})
      const [device_son_fk_id_open, set_device_son_fk_id_open] = useState(false)
      const [device_son_fk_id, set_device_son_fk_id] = useState<API.Device>()
      const [device_son_fk_id_column_open, set_device_son_fk_id_column_open] = useState(false)
      const [deviceSonFkIdIds, setDeviceSonFkIdIds] = useState([])
      const [deviceSonFkIdMap, setDeviceSonFkIdMap] = useState<{ [key: number]: string }>({})
      const handle_device_parent_fk_id = (id: any)=>{
        if (device_parent_fk_id_open) {
            set_device_parent_fk_id(undefined);
            set_device_parent_fk_id_open(false)
        }else {
          postDeviceGetDeviceById({id: id}).then((resp)=>{
          set_device_parent_fk_id(resp.data.device)
          set_device_parent_fk_id_open(true)
        })  
        }
      }
      const handle_device_parent_fk_id_column_open = ()=>{
        if (device_parent_fk_id_column_open) {
            set_device_parent_fk_id_column_open(false)
        }else {
          postDeviceGetDeviceNames({ids: deviceParentFkIdIds}).then((resp)=>{
            let a: any = {}
            resp.data.list.forEach((v: any)=>{
              if (v.id) {
                a[v.id] = v.name
              }
            })
            setDeviceParentFkIdMap(a)
          })
          set_device_parent_fk_id_column_open(true)
        }
      }
      const handle_device_son_fk_id = (id: any)=>{
        if (device_son_fk_id_open) {
            set_device_son_fk_id(undefined);
            set_device_son_fk_id_open(false)
        }else {
          postDeviceGetDeviceById({id: id}).then((resp)=>{
          set_device_son_fk_id(resp.data.device)
          set_device_son_fk_id_open(true)
        })  
        }
      }
      const handle_device_son_fk_id_column_open = ()=>{
        if (device_son_fk_id_column_open) {
            set_device_son_fk_id_column_open(false)
        }else {
          postDeviceGetDeviceNames({ids: deviceSonFkIdIds}).then((resp)=>{
            let a: any = {}
            resp.data.list.forEach((v: any)=>{
              if (v.id) {
                a[v.id] = v.name
              }
            })
            setDeviceSonFkIdMap(a)
          })
          set_device_son_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.DeviceRelation) => {
        deleteDeviceRelationDeleteDeviceRelation({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.DeviceRelation>[] = [

    {
      title: (<FormattedMessage
        id="device.device_relation.table.list.id"
        defaultMessage="id"/>),
      dataIndex: "id",
      sorter: true,
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },

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

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

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

    {
        title: (<FormattedMessage
            id="device.device_relation.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',
            render: (_, record) => [
            <Access accessible={access.canUpdate(history.location.pathname)} key={`${history.location.pathname}-add`}>
              <a
                key="update"
                onClick={() => {
                  setUpdateModalOpen(true);
                  setCurrentRow(record);
                }}
              >
                <FormattedMessage id="pages.searchTable.update" defaultMessage="Update" />
              </a>
              <a
                key="destroy"
                 onClick={() => {
                   handleDestroy(record).then(()=>{})
              }}>
                <FormattedMessage
                  id="pages.searchTable.destroy"
                  defaultMessage="Destroy"
                />
              </a>
              </Access>
            ],
        },];
return (
        <PageContainer>
          <ProTable<API.DeviceRelation>
            headerTitle={intl.formatMessage({
              id: 'pages.searchTable.title',
              defaultMessage: '$$$',
            })}
            options={{ fullScreen: true, setting: true, density: true, reload: true }}
            actionRef={actionRef}
            rowKey="key"
            search={{
              labelWidth: 120,
            }}
            onDataSourceChange={(data)=>{
              
        let DeviceParentFkIdIds: any = data.map((v)=>{
            return v.deviceParentFkId
          })
        setDeviceParentFkIdIds(DeviceParentFkIdIds)


        let DeviceSonFkIdIds: any = data.map((v)=>{
            return v.deviceSonFkId
          })
        setDeviceSonFkIdIds(DeviceSonFkIdIds)


            }}
            pagination={{
              showSizeChanger: true,
              pageSize: 10,
            }}
            columnsState={{
              persistenceKey: 'device_relation_list',
              persistenceType: 'localStorage'
            }}
            toolBarRender={() => [
            <Access accessible={access.canUpdate(history.location.pathname)} key={`${history.location.pathname}-add`}>
              
        <Button
              type="primary"
              key="device_parent_fk_id_show"
              onClick={() => {
                handle_device_parent_fk_id_column_open()
              }}
            >
              {
                device_parent_fk_id_column_open ? (<FormattedMessage
                  id="common.hide"
                defaultMessage="$$$"/>) : (<FormattedMessage
                  id="common.show"
                  defaultMessage="$$$"/>)
              }
              <FormattedMessage
                id="device.device_relation.table.list.deviceParentFkId"
                defaultMessage="$$$"/>

            </Button>    

        <Button
              type="primary"
              key="device_son_fk_id_show"
              onClick={() => {
                handle_device_son_fk_id_column_open()
              }}
            >
              {
                device_son_fk_id_column_open ? (<FormattedMessage
                  id="common.hide"
                defaultMessage="$$$"/>) : (<FormattedMessage
                  id="common.show"
                  defaultMessage="$$$"/>)
              }
              <FormattedMessage
                id="device.device_relation.table.list.deviceSonFkId"
                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 = {
            page: current,
            desc: false,
            orderKey: "",
            ...rest,
          }
          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 postDeviceRelationGetDeviceRelationList({...reqParams})
          return {
            data: resp.data.list.map((v: API.DeviceRelation)=>{
                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 () => {
              deleteDeviceRelationDeleteDeviceRelationByIds({ids: selectedRowsState.map((v: API.DeviceRelation)=>{return v.id as number})}).then(()=>{
                actionRef.current?.reloadAndRest?.();
              })
            }}
          >
            <FormattedMessage
              id="pages.searchTable.batchDeletion"
              defaultMessage="Batch deletion"
            />
          </Button>
            </FooterToolbar>
          )}
          <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}
          />
          <DeviceColumnDrawer
        handleDrawer={handle_device_parent_fk_id}
        isShowDetail={device_parent_fk_id_open}
        columns={DeviceColumns}
        currentRow={device_parent_fk_id}
      />
      <DeviceColumnDrawer
        handleDrawer={handle_device_son_fk_id}
        isShowDetail={device_son_fk_id_open}
        columns={DeviceColumns}
        currentRow={device_son_fk_id}
      />
      
        </PageContainer>
      );
};

    export default DeviceRelationList;
