import {
  PlusOutlined,
  ExclamationCircleOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  FileAddOutlined,
  PlusCircleOutlined,
  UserOutlined,
  DownOutlined,
  MoreOutlined
} from '@ant-design/icons';

import { PageLoading } from '@ant-design/pro-layout';

import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProDescriptions, { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import MenuForm from './components/MenuForm';
import CreateTagForm from './components/CreateTagForm';
import UpdateRoleForm from './components/UpdateRoleForm';
import type { TagInfo, TagListItem } from './data';
import {
  queryRole,
  addTag,
  updateRoleMenu,
  queryAllTags,
  removeTag,
  updateTag,
} from './service';

import type { MenuProps, RadioChangeEvent } from 'antd';

import { Button, Divider, message, Drawer, Modal, Radio, Tabs, Tooltip, Select, Menu, Dropdown, Space } from 'antd';
import Title from 'antd/lib/typography/Title';
import { MenuInfo } from 'rc-menu/lib/interface';

// type TargetKey = React.MouseEvent | React.KeyboardEvent | string;

// const defaultPanes = new Array(2).fill(null).map((_, index) => {
//   const id = String(index + 1);
//   return { label: `Tab ${id}`, children: `Content of Tab Pane ${index + 1}`, key: id };
// });

// type TabPosition = 'left' | 'right' | 'top' | 'bottom';

const { confirm } = Modal;


/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: TagListItem) => {
  const hide = message.loading('正在添加');
  try {

    console.log(fields)
    await addTag({ ...fields });
    hide();
    message.success('添加成功');

    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};


/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: TagListItem) => {
  const hide = message.loading('正在更新');
  try {

    console.log("handleUpdate:", fields)

    await updateTag(fields);
    hide();

    message.success('更新成功');
    return true;
  } catch (error) {
    hide();
    message.error('更新失败请重试！');
    return false;
  }
};


/**
 *  删除节点
 * @param selectedRows
 */
const handleRemove = async (selectedRows: TagListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await removeTag({
      ids: selectedRows.map((row) => row.id),
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList: React.FC = () => {

  const actionRef = useRef<ActionType>();
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [updateMenuModalVisible, handleUpdateMenuModalVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<TagInfo>();

  // const [mode, setMode] = useState<TabPosition>('top');
  const [initPage, setInitPage] = useState<boolean>(false);

  // const [activeKey, setActiveKey] = useState(defaultPanes[0].key);
  const [items, setItems] = useState<TagInfo[]>([]);
  const newTabIndex = useRef(0);

  const initFunc = async () => {
    queryAllTags({ pageSize: 100, current: 0 }).then((res) => {
      console.log("--queryAllTags---->", res)

      setInitPage(true)

      let newRes = res.data

      newRes.map((_item: any, _index: any) => {
        newRes[_index] = {
          ...newRes[_index],
          label: `${_item.name}`, children: `Content of Tab Pane ${_index + 1}`, key: _item.id
        }

      })
      setItems(newRes)

      console.log("items", items)

    });
  }


  useEffect(() => {
    let isMounted = true
    const fetchPost = async () => {
      initFunc()

    }

    fetchPost()

    return () => {
      isMounted = false
    }
  }, [])






  // const onChange = (key: string) => {
  //   setActiveKey(key);
  // };

  // const add = () => {
  //   handleModalVisible(true)
  //   const newActiveKey = `newTab${newTabIndex.current++}`;
  //   setItems([...items, { label: 'New Tab', children: 'New Tab Pane', key: newActiveKey }]);
  //   setActiveKey(newActiveKey);
  // };

  // const remove = (targetKey: TargetKey) => {
  //   const targetIndex = items.findIndex((pane) => pane.key === targetKey);
  //   const newPanes = items.filter((pane) => pane.key !== targetKey);
  //   if (newPanes.length && targetKey === activeKey) {
  //     const { key } = newPanes[targetIndex === newPanes.length ? targetIndex - 1 : targetIndex];
  //     setActiveKey(key);
  //   }
  //   setItems(newPanes);
  // };

  // const onEdit = (targetKey: TargetKey, action: 'add' | 'remove') => {
  //   if (action === 'add') {
  //     add();
  //   } else {
  //     remove(targetKey);
  //   }
  // };



  const handleButtonClick = (e: React.MouseEvent<HTMLButtonElement>) => {
    // message.info('Click on left button.');
    console.log('click left button', e);
  };

  const handleMenuClick: MenuProps['onClick'] = e => {
    // message.info('Click on menu item.');
    console.log('click', e);
  };


  const showDeleteConfirm = (item: TagListItem) => {
    confirm({
      title: '是否删除记录?',
      icon: <ExclamationCircleOutlined />,
      content: '删除的记录不能恢复,请确认!',
      onOk() {
        handleRemove([item]).then((success: boolean) => {

          console.log("=======", success)
          // actionRef.current?.reloadAndRest?.();
          if (success) {
            initFunc()
          }
        });


      },
      onCancel() {
      },
    });
  };




  return (
    <PageContainer>

      {/* <Dropdown.Button menu={menuProps} placement="bottom" icon={<UserOutlined />}>
          Dropdown
        </Dropdown.Button>
        <Dropdown.Button menu={menuProps} onClick={handleButtonClick} disabled>
          Dropdown
        </Dropdown.Button>
        <Dropdown.Button
          menu={menuProps}
          buttonsRender={([leftButton, rightButton]) => [
            <Tooltip title="tooltip" key="leftButton">
              {leftButton}
            </Tooltip>,
            React.cloneElement(rightButton as React.ReactElement<any, string>, { loading: true }),
          ]}
        >
          With Tooltip
        </Dropdown.Button> */}




      {/* <Button type="primary">primary</Button>
        <Button>secondary</Button>
        <Dropdown.Button menu={{ items, onClick: onMenuClick }}>Actions</Dropdown.Button> */}



      {
        !initPage ? <PageLoading />
          : <Space wrap>

            <Dropdown disabled placement="bottom">
              <Button>#ALL</Button>
            </Dropdown>
            {
              items.map((item, index) => {
                return <Dropdown.Button
                  key={index}

                  disabled={item.is_inherent ? true : false}
                  menu={{
                    items: [
                      {
                        label: '重命名',
                        key: '1',
                        // icon: <UserOutlined />,
                      },
                      {
                        label: '删除标签',
                        key: '2',
                        // icon: <UserOutlined />,
                      },

                    ],
                    onClick: async (e: MenuInfo) => {

                      console.log('click', e);

                      if (e.key == '1') {
                        handleUpdateModalVisible(true)

                        setCurrentRow(item)
                      } else if (e.key == '2') {
                        // message.info(`删除: ${item.name}`);
                        // const { success } = await removeTag(item.id);
                        showDeleteConfirm(item);
                        // console.log("----:", item, success)


                      }
                    },
                  }}
                  // danger={true}
                  onClick={handleButtonClick}
                  icon={item.is_inherent ? <MoreOutlined /> : <MoreOutlined />}

                >
                  {item.label}
                </Dropdown.Button>
              })

            }

            <Button type="default" icon={<PlusOutlined />} onClick={() => handleModalVisible(true)}>
              新增标签
            </Button>
          </Space>
      }
      <CreateTagForm
        key={'CreateRoleForm'}
        onSubmit={async (value) => {
          const success = await handleAdd(value);
          if (success) {
            handleModalVisible(false);
            setCurrentRow(undefined);
            // if (actionRef.current) {
            //   actionRef.current.reload();
            // }
            initFunc()
          }
        }}
        onCancel={() => {
          handleModalVisible(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        createModalVisible={createModalVisible}
      />

      <UpdateRoleForm
        key={'UpdateRoleForm'}
        onSubmit={async (value) => {
          const success = await handleUpdate(value);
          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);
            // if (actionRef.current) {
            //   actionRef.current.reload();
            // }
            initFunc()
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        updateModalVisible={updateModalVisible}
        currentData={currentRow || {}}
      />



    </PageContainer>
  );

  // return (
  //   <PageContainer>
  //     {
  //       !initPage ? <PageLoading />
  //         : <div>
  //           <div style={{ marginBottom: 16 }}>
  //             <Tooltip title="search">
  //               标签({items.length})
  //               <Button type="link" onClick={() => handleModalVisible(true)} icon={<PlusCircleOutlined />} />
  //             </Tooltip>
  //             {/* <Button >ADD</Button> */}
  //           </div>
  //           {/* <Tabs
  //         defaultActiveKey="1"
  //         tabPosition={mode}
  //         style={{ height: 220 }}
  //         items={new Array(30).fill(null).map((_, i) => {
  //           const id = String(i);
  //           return {
  //             label: `Tab-${id}`,
  //             key: id,
  //             disabled: i === 28,
  //             children: `Content of tab ${id}`,
  //           };
  //         })}
  //       /> */}

  //           <Tabs
  //             hideAdd
  //             defaultActiveKey="1"
  //             tabPosition={mode}
  //             onChange={onChange}
  //             activeKey={activeKey}
  //             // type="editable-card"
  //             type="card"
  //             // onEdit={onEdit}
  //             items={items}
  //           />
  //         </div>
  //     }
  //     <CreateTagForm
  //       key={'CreateRoleForm'}
  //       onSubmit={async (value) => {
  //         const success = await handleAdd(value);
  //         if (success) {
  //           handleModalVisible(false);
  //           setCurrentRow(undefined);
  //           // if (actionRef.current) {
  //           //   actionRef.current.reload();
  //           // }
  //           initFunc()
  //         }
  //       }}
  //       onCancel={() => {
  //         handleModalVisible(false);
  //         if (!showDetail) {
  //           setCurrentRow(undefined);
  //         }
  //       }}
  //       createModalVisible={createModalVisible}
  //     />

  //   </PageContainer>
  // );
};

export default TableList;
