/*
 *
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */


import React, {useRef, useState} from "react";
import {DownOutlined, PlusOutlined} from '@ant-design/icons';
import ProTable, {ActionType, ProColumns} from "@ant-design/pro-table";
import {Button, Drawer, Dropdown, Menu, Modal} from 'antd';
import {FooterToolbar} from '@ant-design/pro-layout';
import ProDescriptions from '@ant-design/pro-descriptions';
import {handleAddOrUpdate, handleOption, handleRemove, queryData, updateEnabled} from "@/components/Common/crud";
import {useIntl} from 'umi';
import UserForm from "@/pages/AuthenticationCenter/UserManager/components/UserForm";
import PasswordForm from "@/pages/AuthenticationCenter/UserManager/components/PasswordForm";
import {UserTableListItem} from "@/pages/AuthenticationCenter/data.d";

const url = '/api/user';
const UserTableList: React.FC<{}> = (props: any) => {

  const intl = useIntl();

  const {dispatch} = props;
  const [row, setRow] = useState<UserTableListItem>();
  const [modalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [passwordModalVisible, handlePasswordModalVisible] = useState<boolean>(false);
  const [formValues, setFormValues] = useState({});
  const actionRef = useRef<ActionType>();
  const [selectedRowsState, setSelectedRows] = useState<UserTableListItem[]>([]);

  const editAndDelete = (key: string | number, currentItem: UserTableListItem) => {
    if (key === 'edit') {
      setFormValues(currentItem);
      handleUpdateModalVisible(true);
    } else if (key === 'password') {
      setFormValues(currentItem);
      handlePasswordModalVisible(true);
    } else if (key === 'delete') {
      Modal.confirm({
        title: intl.formatMessage({id: 'pages.user.UserDelete', defaultMessage: '删除用户',}),
        content: intl.formatMessage({id: 'pages.user.UserDeleteUser', defaultMessage: '确定删除该用户吗？',}),
        okText: intl.formatMessage({id: 'pages.user.UserConfirm', defaultMessage: '确认',}),
        cancelText: intl.formatMessage({id: 'pages.user.UserCancel', defaultMessage: '取消',}),
        onOk: async () => {
          await handleRemove(url, [currentItem]);
          actionRef.current?.reloadAndRest?.();
        }
      });
    }
  };

  const MoreBtn: React.FC<{
    item: UserTableListItem;
  }> = ({item}) => (
    <Dropdown
      overlay={
        <Menu onClick={({key}) => editAndDelete(key, item)}>
          <Menu.Item key="edit">{intl.formatMessage({id: 'pages.user.UserEdit', defaultMessage: '编辑',})}</Menu.Item>
          <Menu.Item key="password">{intl.formatMessage({
            id: 'pages.user.UserChangePassword',
            defaultMessage: '修改密码',
          })}</Menu.Item>
          {item.username == 'admin' ? '' : (<Menu.Item key="delete">{intl.formatMessage({
            id: 'pages.user.UserDelete',
            defaultMessage: '删除',
          })}</Menu.Item>)}
        </Menu>
      }
    >
      <a>
        {intl.formatMessage({id: 'pages.user.UserMore', defaultMessage: '更多',})} <DownOutlined/>
      </a>
    </Dropdown>
  );

  const columns: ProColumns<UserTableListItem>[] = [
    {
      title: intl.formatMessage({id: 'pages.user.UserName', defaultMessage: '用户名',}),
      dataIndex: 'username',
      sorter: true,
      render: (dom, entity) => {
        return <a onClick={() => setRow(entity)}>{dom}</a>;
      },
    },
    {
      title: '用户ID',
      dataIndex: 'id',
      hideInTable: true,
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({id: 'pages.user.UserNickName', defaultMessage: '昵称',}),
      sorter: true,
      dataIndex: 'nickname',
      hideInTable: false,
    },
    {
      title: intl.formatMessage({id: 'pages.user.UserJobNumber', defaultMessage: '工号',}),
      sorter: true,
      dataIndex: 'worknum',
      hideInTable: false,
    },
    {
      title: intl.formatMessage({id: 'pages.user.UserPhoneNumber', defaultMessage: '手机号',}),
      sorter: true,
      dataIndex: 'mobile',
      hideInTable: false,
    },
    {
      title: intl.formatMessage({id: 'pages.user.UserIsUse', defaultMessage: '是否启用',}),
      dataIndex: 'enabled',
      hideInForm: true,
      hideInSearch: true,
      hideInTable: false,
      filters: [
        {
          text: intl.formatMessage({id: 'pages.user.UserInUse', defaultMessage: '已启用',}),
          value: 1,
        },
        {
          text: intl.formatMessage({id: 'pages.user.UserNotUse', defaultMessage: '已禁用',}),
          value: 0,
        },
      ],
      filterMultiple: false,
      valueEnum: {
        true: {text: intl.formatMessage({id: 'pages.user.UserInUse', defaultMessage: '已启用',}), status: 'Success'},
        false: {text: intl.formatMessage({id: 'pages.user.UserNotUse', defaultMessage: '已禁用',}), status: 'Error'},
      },
    },
    {
      title: intl.formatMessage({id: 'pages.user.UserCreateTime', defaultMessage: '创建时间',}),
      dataIndex: 'createTime',
      sorter: true,
      valueType: 'dateTime',
      hideInTable: true,
    },
    {
      title: intl.formatMessage({id: 'pages.user.UserUpdateTime', defaultMessage: '最近更新时间',}),
      dataIndex: 'updateTime',
      sorter: true,
      valueType: 'dateTime',
    },
    {
      title: intl.formatMessage({id: 'pages.user.UserOperate', defaultMessage: '操作',}),
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          onClick={() => {
            handleUpdateModalVisible(true);
            setFormValues(record);
          }}
        >
          {intl.formatMessage({
            id: 'pages.user.UserConfig',
            defaultMessage: intl.formatMessage({id: 'pages.user.UserConfig', defaultMessage: '配置',}),
          })}
        </a>,
        <MoreBtn key="more" item={record}/>,
      ],
    },
  ];

  return (
    <>
      <ProTable<UserTableListItem>
        headerTitle={intl.formatMessage({id: 'pages.user.UserManger', defaultMessage: '用户管理',})}
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button type="primary" onClick={() => handleModalVisible(true)}>
            <PlusOutlined/> {intl.formatMessage({id: 'pages.user.UserCreate', defaultMessage: '新建',})}
          </Button>,
        ]}
        request={(params, sorter, filter) => queryData(url, {...params, sorter, filter})}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择 <a style={{fontWeight: 600}}>{selectedRowsState.length}</a> 项&nbsp;&nbsp;
              <span>
                被禁用的用户共 {selectedRowsState.length - selectedRowsState.reduce((pre, item) => pre + (item.enabled ? 1 : 0), 0)} 人
              </span>
            </div>
          }
        >
          <Button type="primary" danger
                  onClick={() => {
                    Modal.confirm({
                      title: '删除用户',
                      content: '确定删除选中的用户吗？',
                      okText: '确认',
                      cancelText: '取消',
                      onOk: async () => {
                        await handleRemove(url, selectedRowsState);
                        setSelectedRows([]);
                        actionRef.current?.reloadAndRest?.();
                      }
                    });
                  }}
          >
            批量删除
          </Button>
          <Button type="primary"
                  onClick={() => {
                    Modal.confirm({
                      title: '启用用户',
                      content: '确定启用选中的用户吗？',
                      okText: '确认',
                      cancelText: '取消',
                      onOk: async () => {
                        await updateEnabled(url, selectedRowsState, true);
                        setSelectedRows([]);
                        actionRef.current?.reloadAndRest?.();
                      }
                    });
                  }}
          >批量启用</Button>
          <Button danger
                  onClick={() => {
                    Modal.confirm({
                      title: '禁用用户',
                      content: '确定禁用选中的用户吗？',
                      okText: '确认',
                      cancelText: '取消',
                      onOk: async () => {
                        await updateEnabled(url, selectedRowsState, false);
                        setSelectedRows([]);
                        actionRef.current?.reloadAndRest?.();
                      }
                    });
                  }}
          >批量禁用</Button>
        </FooterToolbar>
      )}
      <UserForm
        onSubmit={async (value) => {
          const success = await handleAddOrUpdate("api/user", value);
          if (success) {
            handleModalVisible(false);
            setFormValues({});
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleModalVisible(false);
        }}
        modalVisible={modalVisible}
        values={{}}
      />
      {formValues && Object.keys(formValues).length ? (
        <>
          <PasswordForm
            onSubmit={async (value) => {
              const success = await handleOption(url + "/modifyPassword", '修改密码', value);
              if (success) {
                handlePasswordModalVisible(false);
                setFormValues({});
              }
            }}
            onCancel={() => {
              handlePasswordModalVisible(false);
            }}
            modalVisible={passwordModalVisible}
            values={formValues}
          />
          <UserForm
            onSubmit={async (value) => {
              const success = await handleAddOrUpdate("api/user", value);
              if (success) {
                handleUpdateModalVisible(false);
                setFormValues({});
                if (actionRef.current) {
                  actionRef.current.reload();
                }
              }
            }}
            onCancel={() => {
              handleUpdateModalVisible(false);
              setFormValues({});
            }}
            modalVisible={updateModalVisible}
            values={formValues}
          /></>
      ) : null}
      <Drawer
        width={600}
        visible={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.username && (
          <ProDescriptions<UserTableListItem>
            column={2}
            title={row?.username}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?.username,
            }}
            columns={columns}
          />
        )}
      </Drawer>
    </>
  );
};

export default UserTableList;
