// import {getMenuPage, login} from "@/services/ant-design-pro/api";
import {Button, Card, Col, Divider, Form, FormInstance, Input, message, Modal, Row, Space, 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 {addRule, delRule, getRuleList, saveMenu, saveRole, setRoleMember, setRoleMenu} from "@/services/role";
import MenuTree from "@/pages/Auth/MenuTree";
import MemberPage from "@/pages/Auth/MemberPage";

const editInfo = {
  info: undefined
}
const Auth = () => {

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


  const [status,setStatus] = useState(0) // edit 33213123123123123 add 0 menu 2 adPerson 3
  const [recordData,setRecord] = useState<any>()

  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 getRuleList(params)
      setDataSource(items)
      setTotal(total)
    })()
  }

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

    // 提交数据
    const fie = form.validateFields()
    fie.then(()=> {
      ( async ()=> {

        debugger

        // 设置权限保存
        let menu = undefined
        if (status === 2) {
          let rds = JSON.parse(localStorage.getItem('checkedKeysValue') || '[]')
          menu = {
            r_id: editInfo.info.id,
            m_ids: rds
          }
        }
        // 设置人员保存
        if (status === 3) {
          let rds = JSON.parse(localStorage.getItem('targetSelectedKeys') || '[]')
          menu = {
            r_ids: editInfo.info.id,
            union_ids: rds
          }
        }

        let msg = await (status === 0 ? addRule(form.getFieldsValue()) : status === 1 ? saveRole({role:{...form.getFieldsValue()}}): status === 2 ? setRoleMenu(menu) : status === 3 ? setRoleMember(menu):null)
        if (isEmptyObject(msg)) {
          success()
          setIsModalOpen(false);
          search()
        }
      })()
    })
  };

  const delHandle = (id:string) => {
    ( async ()=> {
      let msg = await delRule({id:id})
      if (isEmptyObject(msg)) {
        success()
        search()
      }
    })()
  }

  const handleCancel = () => {
    formRef.current?.resetFields();
    setIsModalOpen(false);
  };

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '角色名',
      dataIndex: 'role_name',
      key: 'role_name',
      width: 120,
    },
    {
      title: '角色标识',
      dataIndex: 'role_auth_id',
      key: 'role_auth_id',
      width: 120,
    },

    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a onClick={()=> {
            console.log(record,'+++++')
            // @ts-ignore
            editInfo.info = record
            showModal()
            setStatus(2)

          }}>设置权限</a>
          <a onClick={()=> {
            editInfo.info = record
            showModal()
            setStatus(1)


            form.setFieldsValue({ role_auth_id: record.role_auth_id, role_name: record.role_name,id:record.id });
          }}>编辑角色</a>
          <a onClick={()=> {
            showModal()
            setStatus(3)
            editInfo.info = record
            form.setFieldsValue({ role_auth_id: record.role_auth_id, role_name: record.role_name,id:record.id });
          }}>分配人员</a>
          <a onClick={() =>{
            delHandle(record.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={()=> {
                setStatus(0)
                showModal()
              }}>
                新增角色
              </Button>
            </Col>

          </Row>

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

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

    </PageContainer>

    {/*模拟态*/}
    <Modal afterOpenChange={()=> {

      // console.log(editInfo)


    }} destroyOnClose={true} title={status === 0 ? '新增' : status === 1 ? '编辑' : status === 2 ? '设置权限' : status === 3 ? '添加人员' : null} open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>

      {/*角色添加修改*/}
      <Divider />
      {
        status === 2 ? <MenuTree editInfo={editInfo.info} />: status === 3 ? <MemberPage editInfo={editInfo.info} /> :  <Form form={form} ref={formRef} name="advanced_search" size={"large"} labelCol={{ span: 4 }}
                                            wrapperCol={{ span: 24 }}
                                            style={{ maxWidth: 600 }}>
          {/*gutter 是分割距离*/}
          <Form.Item
            name={'role_name'}
            label={'角色名'}
            hasFeedback
            rules={[
              {
                required: true,
                message: '请输入后',
              },
            ]}
          >
            <Input placeholder="请输入" />
          </Form.Item>
          <Form.Item
            name={'role_auth_id'}
            label={'角色标识'}
            hasFeedback
            rules={[
              {
                required: true,
                message: '请输入后',
              },
            ]}
          >
            <Input placeholder="请输入" />
          </Form.Item>
          <Form.Item
            name={'id'}
            hidden
          >
            <Input placeholder="请输入" hidden />
          </Form.Item>
        </Form>
      }


    </Modal>
  </>
}

export default Auth
