import { PlusOutlined, MinusOutlined, ImportOutlined } from '@ant-design/icons';
import {
  ProTable,
  ProForm,
  ProFormSelect,
  ProFormText,
  ModalForm,
} from '@ant-design/pro-components';
import { useRef, useState, useEffect } from 'react';
import { Spin, Select, Popconfirm, Button, message, Card, Tag } from 'antd';
import React from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { adminUserConnect, adminUserAddConnect, adminUserResetConnect, adminUserRemoveConnect, limitsChangeConnect } from '@/services/SearchVehicle/searchVehicle';
import FunctionImport from '@/pages/VehicleInformationManagement/FunctionImport';


const limitsData = [
  { label: '管理员', value: 'ROLE_ADMIN' },
  { label: '维护员', value: 'ROLE_WEIHU' },
  { label: '普通用户', value: 'ROLE_USER' },
]
export default () => {
  const formRef = useRef<any>();
  const formRef2 = useRef<any>();
  const actionRef = useRef<any>();

  const [modalVisit, setModalVisit] = useState(false);
  const [modalVisit2, setModalVisit2] = useState(false);
  const [data, setData] = useState<any>([]);
  const [spinning, setSpinning] = useState<any>(false);
  const [selectedRowsData, setSelectedRowsData] = useState<any>([]);
  const [batch, setBatch] = useState<any>(true);
  const [pageSize, setPageSize] = useState<any>(10);




  useEffect(() => {
    return () => {
    };
  }, []);


  const columns = [
    { align: 'center', title: "序号",search: false, width: 68, render: (text, record, index) => `${index + 1}`, },
    {
      align: 'center',
      title: '用户名',
      dataIndex: 'login',
      render: (text: any, item: any) => {
        return <div>{item?.login}</div>
      },
    },
    {
      search: false,
      align: 'center',
      title: '联系方式',
      render: (item: any) => {
        return <div> {item?.email}</div>
      },
    },
    {
      search: false,
      align: 'center',
      title: '创建时间',
      render: (item: any) => {
        return <div> {item?.createdDate}</div>
      },
    },
    {
      search: false,
      align: 'center',
      title: '权限',
      render: (_: any, record: any) => {
        if (!record?.authorities) {
          return
        }
        return <>
          <Select
            onChange={(e) => { limitsChange(record, e) }}
            style={{ width: 120 }}
            value={record?.authorities[0]}
            bordered={false}
            options={limitsData}
          />
        </>
      },

    },
    {
      align: 'center',
      title: '操作',
      dataIndex: 'x',
      valueType: 'option',
      render: (_, record: any) => {
        return [
          <Popconfirm
            title="确认重置密码？"
            description="密码重置后默认123456"
            onConfirm={() => { reset(record) }}
            onCancel={cancel}
          >
            <Button
              key="editable"
              type="primary"
              style={{ background: '#2db7f5', border: 'none' }}
            >
              重置密码
            </Button>

          </Popconfirm>
          ,
          <Popconfirm
            title="确认删除？"
            onConfirm={() => { confirm(record) }}
            onCancel={cancel}
          >
            <Button
              key="remove"
              type="primary"
              danger
            >
              删除
            </Button>
          </Popconfirm>
        ]
      },
    },
  ];

  const limitsChange = (record: any, e: any) => {
    console.log(record);
    console.log(e);

    setSpinning(true)
    let data = {
      id: record.id,
      login: record.login,
      password: record.password,
      authorities: [e]
    }
    limitsChangeConnect(data).then((res) => {
      console.log(res);
      message.success('权限切换成功');
      setSpinning(false)
      // 刷新
      actionRef.current.reload();
    }).catch((error) => {
      console.log(error);
      message.error('请求出错');
      setSpinning(false)
    })
  }

  const confirm = (e: any) => {
    console.log(e);

    setSpinning(true)
    let data = [e.login] as any
    adminUserRemoveConnect(data).then((res) => {
      console.log(res);
      message.success('用户删除成功');
      setSpinning(false)
      // 刷新
      actionRef.current.reload();
    }).catch((error) => {
      console.log(error);
      message.error('请求出错');
      setSpinning(false)
    })
  };

  const reset = (e: any) => {
    console.log(e);

    setSpinning(true)
    let data = {
      id: e.id,
      login: e.login,
      password: e.password,
      authorities: e.authorities,
    }
    adminUserResetConnect(data).then((res) => {
      console.log(res);
      message.success('密码重置成功，默认密码: 123456');
      setSpinning(false)
      // 刷新
      actionRef.current.reload();
    }).catch((error) => {
      console.log(error);
      message.error('请求出错');
      setSpinning(false)
    })


  };


  const confirmAll = (e: any) => {
    for (let index = 0; index < selectedRowsData.length; index++) {
      const element = selectedRowsData[index];
      data.push(element.login)
    }

    console.log(e);

    setSpinning(true)
    adminUserRemoveConnect(data).then((res) => {
      console.log(res);
      message.success('用户批量删除成功');
      setSelectedRowsData([])
      setSpinning(false)
      // 刷新
      actionRef.current.reload();
    }).catch((error) => {
      console.log(error);
      message.error('请求出错');
      setSpinning(false)
    })
  };


  const cancel = (e: React.MouseEvent<HTMLElement>) => {
    console.log(e);
  };

  const rowSelection = {
    onChange: (selectedRowKeys: any, selectedRows: any) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      if (selectedRows && selectedRows.length > 0) {
        setBatch(false)
      } else {
        setBatch(true)
      }

      setSelectedRowsData(selectedRows)
    },
    getCheckboxProps: (record: any) => ({
      disabled: record.name === 'Disabled User', // Column configuration not to be checked
      name: record.name,
    }),
  };

  const toBack = (type: any) => {
    setTimeout(() => {
      setModalVisit2(false);
      if (type) {
        actionRef.current.reload();
      }
    }, 300);
  }


  return (
    <PageContainer>
      <Spin tip="Loading..." size="large" spinning={spinning}>
        <ProTable
          rowSelection={{
            type: 'checkbox',
            ...rowSelection,
          }}
          columns={columns}
          actionRef={actionRef}
          cardBordered
          request={adminUserConnect as any}
          columnsState={{
            persistenceKey: 'pro-table-singe-demos',
            persistenceType: 'sessionStorage',
            onChange(value: any) {
              console.log('value: ', value);
            },
          }}
          scroll={{ y: 480 }}
          rowKey="id"
          options={{
            setting: {
              listsHeight: 400,
            },
          }}
          pagination={{
            showSizeChanger: true,
            pageSize: pageSize,
            onChange: (page: any, pageSize: any) => setPageSize(pageSize),
          }}
          dateFormatter="string"
          toolBarRender={() => [
            <Button
              key="button"
              type="primary"
              ghost
              icon={<ImportOutlined />}
              onClick={() => {
                setModalVisit2(true);
              }}
            >
              用户录入
            </Button>,
            <Button
              key="button"
              icon={<PlusOutlined />}
              type="primary"
              onClick={() => {
                setModalVisit(true);
                formRef.current?.resetFields();
              }}
            >
              新建
            </Button>,
            <Popconfirm
              title="确认删除？"
              onConfirm={confirmAll}
              onCancel={cancel}
              disabled={batch}

            >
              <Button
                key="button"
                icon={<MinusOutlined />}
                type="primary"
                danger
                disabled={batch}
              >
                批量删除
              </Button>
            </Popconfirm>
            ,
          ]}
        //search={false}
        />

        {/* 用户编辑 */}
        <ModalForm
          formRef={formRef}
          title="用户编辑"
          visible={modalVisit}
          onVisibleChange={setModalVisit}
          onFinish={(values: any) => {
            console.log(values);
            values.authorities = [values.authorities]
            if (values?.password.length < 6) {
              message.warning('密码不能少于6位');
              return false
            }

            if (values?.email.length < 6) {
              message.warning('联系方式不能少于6位');
              return false
            }

            setSpinning(true)
            adminUserAddConnect(values).then((res) => {
              console.log(res);
              message.success('新增用户成功');
              setSpinning(false)
              // 刷新
              actionRef.current.reload();
            }).catch((error) => {
              console.log(error);
              message.error('请求出错');
              setSpinning(false)
            })
            return true;
          }}
        >
          <Card>
            <ProForm.Group>
              <ProFormText width="md" name="login" label="用户名" placeholder="请输入用户名" />
              <ProFormText width="md" name="password" label="用户密码" placeholder="请输入用户密码" />
            </ProForm.Group>
            <ProForm.Group>
            </ProForm.Group>
            <ProForm.Group>
              <ProFormText width="md" name="email" label="联系方式" placeholder="请输入联系方式" />
              <ProFormSelect
                name="authorities"
                label="分配角色权限"
                placeholder="分配角色权限"
                width="md"
                allowClear
                request={async () => limitsData}
              />
            </ProForm.Group>
          </Card>
        </ModalForm>



        {/* 用户录入 */}
        <ModalForm
          formRef={formRef2}
          title="用户录入"
          visible={modalVisit2}
          onVisibleChange={setModalVisit2}
          width={1200}
          submitter={false}
        >
          <Card>
            <FunctionImport type="user" toBack={(type: any) => { toBack(type) }}></FunctionImport>
          </Card>
        </ModalForm>
      </Spin>
    </PageContainer>
  );

};