import {postDepartmentGetDepartmentList, deleteDepartmentDeleteDepartment} from '@/services/system/Department';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {
  FooterToolbar,
  PageContainer,
  ProTable,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl, useAccess, Access, history } from '@umijs/max';
import {Button, Popconfirm, message} from 'antd';
import React, { useRef, useState } from 'react';
import UpdateForm from '@/pages/System/DepartmentList/components/UpdateForm'
import CreateForm from '@/pages/System/DepartmentList/components/CreateForm'
import {ColumnDrawer} from '@/pages/System/DepartmentList/components/ColumnDrawer'
// 列表操作栏组件
import TableActionCard from '@/components/TableActionCard';
import IsDelete from '@/components/TableActionCard/isDelete';
// 批量删除
import IsBatchDelete from '@/components/BatchOperation/isBatchDelete';

const DepartmentList: 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 intl = useIntl();
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.Department>();
  const access = useAccess();
  const [selectedRowsState, setSelectedRows] = useState<API.Department[]>([]);
  const handleUpdateModal = ()=>{
    if (updateModalOpen) {
      setCurrentRow(undefined);
      setUpdateModalOpen(false)
    } else {
      setUpdateModalOpen(true)
    }
  }
  const handleCreateModal = ()=>{
    if (createModalOpen) {
      setCurrentRow(undefined)
      setCreateModalOpen(false)
    } else {
      setCreateModalOpen(true)
    }
  }
  const handleColumnDraw = ()=>{
    if (showDetail) {
      setShowDetail(false)
    } else {
      setShowDetail(true)
    }
  }
  const handleDestroy = async (selectedRow: API.Department) => {
    deleteDepartmentDeleteDepartment({id: selectedRow.id}).then(()=>{
      message.success(intl.formatMessage({id: 'common.success', defaultMessage: '$$$'}))
      actionRef.current?.reload()
    }).catch(()=>{
      message.error(intl.formatMessage({id: 'common.error', defaultMessage: '$$$'}))
    })
  };

  const columns: ProColumns<API.Department>[] = [


    {
      title: (<FormattedMessage
        id="system.department.table.list.id"
        defaultMessage="id"/>),
      dataIndex: "id",
      sorter: true,
      render: (dom, entity) => {
        return (
          <a
            style={{color: '#155BD4'}}
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },

    {
      title: (<FormattedMessage
        id="system.department.table.list.name"
        defaultMessage="$$$"/>),
      dataIndex: "name",
      hideInSearch: true,
    },
    {
      title: (<FormattedMessage
        id="system.department.table.list.code"
        defaultMessage="$$$"/>),
      dataIndex: "code",
      hideInSearch: true,
    },

    // {
    //   title: (<FormattedMessage
    //     id="system.department.table.list.type"
    //     defaultMessage="$$$"/>),
    //   dataIndex: "type",
    //   hideInSearch: true,
    //   render: (_, record)=>{
    //     if (record.type === 'M') {
    //       return <FormattedMessage id="system.department.table.list.type_M" defaultMessage="$$$"/>
    //     } else if (record.type === 'C') {
    //       return <FormattedMessage id="system.department.table.list.type_C" defaultMessage="$$$"/>
    //     } else if (record.type === 'F') {
    //       return <FormattedMessage id="system.department.table.list.type_F" defaultMessage="$$$"/>
    //     } else {
    //       return <span>-</span>
    //     }
    //   }
    // },


    // {
    //   title: (<FormattedMessage
    //     id="system.department.table.list.name"
    //     defaultMessage="$$$"/>),
    //   dataIndex: "name",
    //   hideInSearch: true,
    // },

    // {
    //   title: (<FormattedMessage
    //     id="system.department.table.list.icon"
    //     defaultMessage="$$$"/>),
    //   dataIndex: "icon",
    //   hideInSearch: true,
    //   render: (_, record)=>{
    //     if (record.icon === undefined || record.icon === '') {
    //       return <span>-</span>
    //     } else {
    //       return <Icon icon={record.icon} />
    //     }
    //   }
    // },
    {
      title: (<FormattedMessage
        id="system.department.table.list.sort"
        defaultMessage="$$$"/>),
      dataIndex: "sort",
      hideInSearch: true,
    },


    {
      title: (<FormattedMessage
        id="system.department.table.list.status"
        defaultMessage="$$$"/>),
      dataIndex: "status",
      valueEnum: {
        true: {
          text: (<FormattedMessage
            id="common.yes"
            defaultMessage="$$"/>),
          status: 'Success'
        },
        false: {
          text: (<FormattedMessage
            id="common.no"
            defaultMessage="$$"/>),
          status: 'Error'
        }
      },
      filters: true, onFilter: true,
    },


    // {
    //   title: (<FormattedMessage
    //     id="system.department.table.list.components"
    //     defaultMessage="$$$"/>),
    //   dataIndex: "components",
    //   hideInSearch: true,
    // },
    //
    //
    // {
    //   title: (<FormattedMessage
    //     id="system.department.table.list.path"
    //     defaultMessage="$$$"/>),
    //   dataIndex: "path",
    //   hideInSearch: true,
    // },


    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="Operating" />,
      dataIndex: 'option',
      valueType: 'option',
      fixed:'right',
      render: (_, record) => [
        <TableActionCard
          key="TableActionCardRef"
          renderActions={[
            {
              key: 'create',
              renderDom: (
                <Button
                  key="create"
                  type="link"
                  size="small"
                  onClick={() => {
                    setCreateModalOpen(true);
                    setCurrentRow(record);
                  }}
                >
                  <FormattedMessage id="pages.searchTable.create_son_department" defaultMessage="Create" />
                </Button>
              ),
            },
            {
              key: 'update',
              renderDom: (
                <Button
                  key="update"
                  type="link"
                  size="small"
                  onClick={() => {
                    setUpdateModalOpen(true);
                    setCurrentRow(record);
                  }}
                >
                  <FormattedMessage id="pages.searchTable.update" defaultMessage="Update" />
                </Button>
              ),
            },
            {
              key: 'destroy',
              renderDom: (
                <IsDelete
                  deleteApi={() => {
                    handleDestroy(record).then(() => {});
                  }}
                ></IsDelete>
              ),
            },
          ]}
        ></TableActionCard>
        // <Access accessible={access.canUpdate(history.location.pathname)} key={`${history.location.pathname}-add`}>
        //   <a
        //     key="create"
        //     onClick={() => {
        //       setCreateModalOpen(true);
        //       setCurrentRow(record);
        //     }}
        //   >
        //     <FormattedMessage id="pages.searchTable.create_son_department" defaultMessage="Create" />
        //   </a>
        //   <a
        //     key="update"
        //     onClick={() => {
        //       setUpdateModalOpen(true);
        //       setCurrentRow(record);
        //     }}
        //   >
        //     <FormattedMessage id="pages.searchTable.update" defaultMessage="Update" />
        //   </a>
        //   <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>
        // </Access>
      ],
    },];
  return (
    <PageContainer>
      <ProTable<API.Department, API.DepartmentResponse>
        headerTitle={intl.formatMessage({
          id: 'pages.searchTable.title',
          defaultMessage: '$$$',
        })}
        options={{ fullScreen: true, setting: true, density: true, reload: true }}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 'auto',
        }}
        pagination={{
          showSizeChanger: true,
        }}
        columnsState={{
          persistenceKey: 'department-list',
          persistenceType: 'localStorage'
        }}
        toolBarRender={() => [
          <Access accessible={access.canUpdate(history.location.pathname)} key={`${history.location.pathname}-add`}>
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                setCurrentRow(undefined)
                setCreateModalOpen(true);
              }}
            >
              <PlusOutlined /> <FormattedMessage id="pages.searchTable.create_root_department" 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 postDepartmentGetDepartmentList({...reqParams})
          return {
            data: resp.data?.list?.map((v: API.Department)=>{ 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);
          },
        }}
        tableAlertOptionRender={() => {
          return (
            <>
              {selectedRowsState?.length > 0 && (
                <IsBatchDelete
                  deleteApi={() => {
                    actionRef.current?.reloadAndRest?.();
                  }}
                />
              )}
            </>
          );
        }}
      />
      {/* {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 () => {
              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={handleColumnDraw}
        isShowDetail={showDetail}
        columns={columns}
        currentRow={currentRow}
      />
    </PageContainer>
  );
};

export default DepartmentList;
