// import {getMenuPage, login} from "@/services/ant-design-pro/api";
import {
  Button,
  Card,
  Col,
  Divider,
  Form,
  FormInstance,
  Input,
  message,
  Modal,
  Row,
  Select,
  Space,
  Switch,
  Table
} from "antd";
import {history} from "@umijs/max";
import {PageContainer} from "@ant-design/pro-components";
import {SearchOutline} from "antd-mobile-icons";
import React, {useEffect, useState} from "react";
import {addMenu, delMenu, getMenuPage, saveMenu} from "@/services/role";
import MenuTree from "@/pages/Auth/MenuTree";

const Auth = () => {

  // 表单域
  const [form] = Form.useForm();
  const formRef = React.useRef<FormInstance>(null);
  const [messageApi, contextHolder] = message.useMessage();

  const [status,setStatus] = useState(0) // edit 1 add 0 menu 2

  const [dataSource,setDataSource] = useState()
  const [params,setParams] = useState<ROLE_API.RuleParmes>({
    page: 1,
    page_size: 10
  })
  const [total, setTotal] = useState<number | undefined>(0)
  const [isModalOpen, setIsModalOpen] = useState(false);

  const success = () => {
    messageApi.open({
      type: 'success',
      content: '操作成功',
    });
  };

  const isEmptyObject = (obj: { constructor?: any; }) => {
    return Object.keys(obj).length === 0 && obj.constructor === Object;
  }

  // 初始化
  const search = () => {
    ( async ()=> {
      let { items,total } = await getMenuPage(params)
      setDataSource(items)
      setTotal(total)
    })()
  }

  // 显示表单模拟态
  const showModal = () => {
    setIsModalOpen(true);
  };
  const handleOk = () => {

    // 提交数据
    const fie = form.validateFields()
    fie.then(()=> {
      ( async ()=> {
        let msg = await (status === 0 ? addMenu({menu:{...form.getFieldsValue()}}) : status === 1 ? saveMenu({menu:{...form.getFieldsValue()}}): null)
        if (isEmptyObject(msg) || (msg !== null || msg !== '')) {
          success()
          setIsModalOpen(false);
          search()
        }
      })()
    })
  };

  const delHandle = (id:string) => {
    ( async ()=> {
      let msg = await delMenu({id:id})
      if (isEmptyObject(msg)) {
        success()
        search()
      }
    })()
  }
  const onGenderChange = (value: string) => {
    switch (value) {
      case 'male':
        formRef.current?.setFieldsValue({ note: 'Hi, man!' });
        break;
      case 'female':
        formRef.current?.setFieldsValue({ note: 'Hi, lady!' });
        break;
      case 'other':
        formRef.current?.setFieldsValue({ note: 'Hi there!' });
        break;
      default:
        break;
    }
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const columns = [
    {
      title: 'ID',
      key: 'menu',
      width: 80,
      render: (_, record) => {
        // console.log(_)
        console.log(record)
        return record.menu.id
      }
    },{
      title: '上级菜单id',
      key: 'menu',
      width: 80,
      render: (_, record) => {
        // console.log(_)
        console.log(record)
        return record.menu.pid
      }
    },{
      title: '菜单名称',
      key: 'menu',
      width: 80,
      render: (_, record) => {
        // console.log(_)
        console.log(record)
        return record.menu.name
      }
    },{
      title: '链接地址',
      key: 'menu',
      width: 80,
      render: (_, record) => {
        // console.log(_)
        console.log(record)
        return record.menu.link
      }
    },{
      title: '类型 ',
      key: 'menu',
      width: 80,
      render: (_, record) => {
        // console.log(_)
        // console.log(record)
        return record.type === 1 ? '菜单' : '接口'
      }
    },
    {
      title: '是否显示',
      key: 'menu',
      width: 80,
      render: (_, record) => {
        // console.log(_)
        console.log(record)
        return (
          record.menu?.is_show === 1 ? <div>是</div> : <div>否</div>
        )
      }
    },

    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">

          <a onClick={()=> {
            showModal()
            setStatus(1)

            form.setFieldsValue({
              id: record.menu.id,
              link: record.menu.link,
              pid: record.menu.pid,
              type: record.menu.type,
              name:record.menu.name,
              is_show:record.menu.is_show
            });

          }}>编辑菜单</a>
          <a onClick={() =>{
            delHandle(record.menu.id)
          }}>删除</a>
        </Space>
      ),
    },



  ];



  useEffect(() => {

    // 发请求
    search()
  }, [params]);


  return <>
    {contextHolder}
    <PageContainer>
      <Card>
        <Form form={form} name="advanced_search" size={"large"}>
          {/*gutter 是分割距离*/}
          <Row gutter={8}>
            <Col span={12}>
              <Button type={'primary'} onClick={()=> {
                formRef.current?.resetFields();
                setStatus(0)
                showModal()
              }}>
                新增菜单
              </Button>
            </Col>

          </Row>

        </Form>
      </Card>
      <Card style={{ marginTop: 20 }}>

        <Table dataSource={dataSource} columns={columns}
               pagination={{ total: total, onChange:(page,pageSize)=> {
                   setParams({
                     ...params, page: page,page_size:pageSize
                   })
                 },pageSize: params.page_size}} />
      </Card>

    </PageContainer>

    {/*模拟态*/}
    <Modal title={status === 0 ? '新增' : status === 1 ? '编辑' : status === 2 ? '设置权限' : null} open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
      {/*角色添加修改*/}
   <Divider />
      {
        status === 2 ? <MenuTree /> : <Form form={form} ref={formRef} name="advanced_search" size={"large"} labelCol={{ span: 6 }}
                                            wrapperCol={{ span: 24 }}
                                            style={{ maxWidth: 600 }}>
          {/*gutter 是分割距离*/}
          <Form.Item
            name={'pid'}
            label={'上级菜单ID'}
            hasFeedback
            rules={[
              {
                required: true,
                message: '请输入后',
              },
            ]}
          >
            <Input placeholder="请输入" />
          </Form.Item>
          <Form.Item
            name={'name'}
            label={'菜单名'}
            hasFeedback
            rules={[
              {
                required: true,
                message: '请输入后',
              },
            ]}
          >
            <Input placeholder="请输入" />
          </Form.Item>
          <Form.Item
            name={'link'}
            label={'链接地址'}
            hasFeedback
            rules={[
              {
                required: true,
                message: '请输入后',
              },
            ]}
          >
            <Input placeholder="请输入" />
          </Form.Item>

          <Form.Item  label={'类型'} name={'is_show'} rules={[{ required: true }]}>
            <Select
              placeholder="请输入"
              // onChange={onGenderChange}
              allowClear
            >
              <Select.Option value={1}>显示</Select.Option>
              <Select.Option value={-1}>隐藏</Select.Option>
            </Select>
          </Form.Item>


          <Form.Item
            name={'id'}
            hidden
          >
            <Input placeholder="请输入" hidden />
          </Form.Item>
        </Form>
      }


    </Modal>
  </>
}

export default Auth
