
import { useFormReset } from "@/hooks/useFormReset";
import TemplateContainer from "@/pages/TemplateContainer";
import { DeactivationMachine, MachinePermanent, QueryMachineList } from "@/services/services/machine";
import { FormatDate } from "@/util/time";
import { useAccess, useModel } from "@umijs/max";
import { Button, Form, Input, message, Modal, Select, SelectProps, Spin, Table, Tag } from "antd";
import { ColumnsType, TablePaginationConfig } from "antd/es/table";
import { FilterValue, SorterResult, TableCurrentDataSource } from "antd/es/table/interface";
import { delay, set } from "lodash";
import { useEffect, useState } from "react";
import ModifyMachine from "../ModifyMachine";
import { PlusOutlined } from "@ant-design/icons";
import AddMachineForm from "../AddMachineForm";

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

  const { initialState } = useModel('@@initialState');
  const [data, setData] = useState<MachineModel.MachineCollection[]>(); // 数据
  const [messageApi, messageHolder] = message.useMessage();
  const [form] = Form.useForm();
  const access = useAccess();
  const { setFormRef, resetForm } = useFormReset();
  const [tableParams, setTableParams] = useState<TableModel.TableParams>({
    pagination: {
      current: 1,
      pageSize: 10,
      showQuickJumper: true,
      totalBoundaryShowSizeChanger: true,
    },
  });
  const [id, setId] = useState<string>('');
  const [loading, setLoading] = useState<boolean>(true);
  const [openModal, setOpenModal] = useState<boolean>(false);
  const [openAddModal, setOpenAddModal] = useState<boolean>(false);
  const [spinning, setSpinning] = useState<boolean>(false);
  const [spinTip, setSpinTip] = useState<string>('');

  useEffect(() => {
    QueryMachineList(tableParams, form.getFieldsValue())
      .then((res) => {
        setData(res.collection);
        setTableParams({
          pagination: {
            ...tableParams.pagination,
            total: res.total
          }
        })
        setLoading(false);
      })
      .catch((error: any) => {
        messageApi.error(error.message);
      })
      .finally(() => {
        setLoading(false);
      })
  }, []);

  async function SetMachinePermanent(id: string): Promise<void> {
    setSpinning(true);
    setSpinTip('正在设置为永久。。。');
    try {
      // 
      await MachinePermanent(id);
      messageApi.success('设置为永久成功');
      setSpinning(false);
      // 重新加载数据
      await QueryMachineBasic(form.getFieldsValue(), tableParams.pagination);
    } catch (error: any) {
      messageApi.error(error.message);
    } finally {
      setSpinning(false);
    }
  }

  async function ChangeDeactivationMachine(id: string): Promise<void> {
    setSpinning(true);
    setSpinTip('正在停用。。。');
    try {
      await DeactivationMachine(id);
      messageApi.success('停用成功');
      setSpinning(false);
      // 重新加载数据
      await QueryMachineBasic(form.getFieldsValue(), tableParams.pagination);
    } catch (error: any) {
      messageApi.error(error.message);
    } finally {
      setSpinning(false);
    }
  }

  async function QueryMachineBasic(params: MachineModel.QueryUMachineParams | null, pagination: TablePaginationConfig | null): Promise<void> {
    setLoading(true);
    try {
      let tableParamsParams = pagination ? { pagination } : tableParams;
      let res = await QueryMachineList(tableParamsParams, params ?? form.getFieldsValue());
      setData(res.collection);
      setTableParams({
        pagination: {
          ...tableParams.pagination,
          total: res.total
        }
      })
    } catch (error: any) {
      message.error(error.message);
    } finally {
      setLoading(false);
    }
  }

  async function handleTableChange(pagination: TablePaginationConfig, filters: Record<string, FilterValue | null>, sorter: SorterResult<MachineModel.MachineCollection> | SorterResult<MachineModel.MachineCollection>[], extra: TableCurrentDataSource<MachineModel.MachineCollection>): Promise<void> {
    setLoading(true);
    try {
      let queryUser = await QueryMachineList({ pagination }, form.getFieldsValue());
      setData(queryUser.collection);
      setTableParams({
        pagination: {
          ...pagination,
          total: queryUser.total
        }
      })
    } catch (error: any) {
      message.error(error.message);
    } finally {
      setLoading(false);
    }
  }

  async function modalCancel(): Promise<void> {
    setOpenModal(false);
    setOpenAddModal(false);
    resetForm();
    setId('');
    // 这边调用加载数据的方法
    await QueryMachineBasic(null, null);
  }

  async function QueryMachineListByCondition(values: any): Promise<void> {
    await QueryMachineBasic(values, null);
  }


  const columns: ColumnsType<MachineModel.MachineCollection> = [
    {
      title: 'ID',
      dataIndex: 'machineId',
    },
    {
      title: '创建人',
      dataIndex: 'createId',
      width: '100px',
    },
    {
      title: '修改人',
      dataIndex: 'updateId',
      width: '100px',
    },
    {
      title: '所属人',
      dataIndex: 'userID',
      width: '100px',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      render: (text) => FormatDate(text),
      width: '160px',
    },
    {
      title: '使用状态',
      dataIndex: 'useStatus',
      render: (text, record) => <Tag color={record.useStatus === 1 ? 'green' : 'red'}>{record.useStatus === 1 ? '永久' : '试用'}</Tag>,
      width: '100px',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (text, record) => <Tag color={record.status === 1 ? 'blue' : 'red'}>{record.status === 1 ? '激活' : '冻结'}</Tag>,
      width: '100px',
    },
    {
      title: '停用时间',
      dataIndex: 'deactivationTime',
      render: (text) => FormatDate(text),
      width: '160px',
    },
    {
      title: '备注',
      dataIndex: 'remark',
    },
    {
      title: '操作',
      width: '200px',
      render: (text, record) => (
        <div>
          <Button hidden={!access.canEditMachine} style={{ marginRight: 5 }} type="primary" size="small"
            onClick={() => { setOpenModal(true); setFormRef(form); setId(record.id) }}>编辑</Button>
          <Button hidden={!access.canUpgradeMachine} type="primary" style={{ marginRight: 5 }} size="small"
            onClick={async () => await SetMachinePermanent(record.id)}>永久</Button>
          <Button hidden={!access.canDisableMachine} type="primary" danger size="small"
            onClick={async () => await ChangeDeactivationMachine(record.id)}>停用</Button>
        </div>
      ),
    },
  ];

  return (
    <TemplateContainer navTheme={initialState?.settings?.navTheme ?? "realDark"}>
      <Spin spinning={spinning} tip={spinTip}>
        <Form
          layout='inline'
          form={form}
          onFinish={QueryMachineListByCondition}
        >
          <Form.Item<MachineModel.QueryUMachineParams> label="机器码" name='machineId' style={{ marginBottom: 5 }}>
            <Input placeholder="请输入机器码" />
          </Form.Item>
          {
            access.isAdminOrSuperAdmin ?
              <Form.Item<MachineModel.QueryUMachineParams> label="创建用户名" name='createdUserName' style={{ marginBottom: 5 }}>
                <Input placeholder="请输入创建用户名" />
              </Form.Item> :
              null
          }
          {
            access.isAdminOrSuperAdmin ?
              <Form.Item<MachineModel.QueryUMachineParams> label="所属用户名" name='ownUserName' style={{ marginBottom: 5 }}>
                <Input placeholder="请输入所属用户名" />
              </Form.Item> :
              null
          }
          <Form.Item<MachineModel.QueryUMachineParams> label="状态" name='status' style={{ marginBottom: 5 }}>
            <Select allowClear placeholder="请选择状态" style={{ width: 200 }}>
              <Select.Option value={1}>激活</Select.Option>
              <Select.Option value={0}>冻结</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item<MachineModel.QueryUMachineParams> label="使用状态" name='useStatus' style={{ marginBottom: 5 }}>
            <Select allowClear placeholder="请选择使用状态" style={{ width: 200 }}>
              <Select.Option value={1}>永久</Select.Option>
              <Select.Option value={0}>试用</Select.Option>
            </Select>

          </Form.Item>
          <Form.Item<MachineModel.QueryUMachineParams> label="备注" name='remark' style={{ marginBottom: 5 }}>
            <Input placeholder="请输入备注" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType='submit'>查询</Button>
          </Form.Item>
          <Form.Item>
            <Button type="primary" icon={<PlusOutlined />} onClick={() => { setOpenAddModal(true); }}>新增</Button>
          </Form.Item>
        </Form>
        <Table<MachineModel.MachineCollection>
          columns={columns}
          rowKey={(record) => record.id}
          dataSource={data}
          pagination={tableParams.pagination}
          loading={loading}
          onChange={handleTableChange}
        />
      </Spin>
      <Modal width={840} title="编辑机器码" maskClosable={false} open={openModal} footer={null} onCancel={modalCancel}>
        <ModifyMachine open={openModal} setFormRef={setFormRef} id={id} />
      </Modal>
      <Modal width={600} title="新增机器码" maskClosable={false} open={openAddModal} footer={null} onCancel={modalCancel}>
        <AddMachineForm setFormRef={setFormRef} />
      </Modal>
      {messageHolder}
    </TemplateContainer>
  );
};

export default MachineManagement;