import {ModalForm, ProForm} from '@ant-design/pro-components';
import {ProFormText, ProFormDependency} from '@ant-design/pro-components';
import {ProFormSelect} from '@ant-design/pro-components';
import {useIntl} from '@umijs/max';
import React, {useEffect} from 'react';
import {Form, message, Tabs, Tree, Select} from 'antd';
import {postMenuGetMenuTree} from "@/services/system/Menu";
import {postApiGetAllApisByGroup} from "@/services/system/Api";
import {postDepartmentGetDepartmentTree} from "@/services/system/Department";
import {putRoleUpdateRolePermission, postRoleGetRolePermission} from "@/services/system/Role";
import type { DataNode } from 'antd/es/tree';

export type SetPermissionFormProps = {
  updateModalOpen: boolean;
  handleModal: () => void;
  values: Partial<API.Role>;
  reload: any;
};


const { Option } = Select;
const children = [];
for (let i = 10; i < 36; i++) {
  children.push(<Option key={i.toString(36) + i}>{i.toString(36) + i}</Option>);
}
const SetPermissionForm: React.FC<SetPermissionFormProps> = (props) => {

  const [treeData, setTreeData] = React.useState<DataNode[]>([]);
  const [deptTreeData, setDeptTreeData] = React.useState<DataNode[]>([]);

  const [apitreeData, setApiTreeData] = React.useState<DataNode[]>([]);
  const [initApiData, setInitApiData] = React.useState<number[]>([]);
  const [initMenuData, setInitMenuData] = React.useState<number[]>([]);
  const [initDepartmentData, setInitDepartmentData] = React.useState<number[]>([]);
  const [dataScope, setDataScope] = React.useState<string>('1');
  const [hasInit, setHasInit] = React.useState<boolean>(false);

  const dataSourceItems = [
    {'label': '全部数据权限', 'value': '1'},
    {'label': '自定义数据权限', 'value': '2'},
    {'label': '本部门数据权限', 'value': '3'},
    {'label': '本部门及以下数据权限', 'value': '4'},
    {'label': '仅本人数据权限', 'value': '5'},

  ]
  const intl = useIntl();
  const [form] = Form.useForm<API.UpdateRolePermissionParams>();

  useEffect(()=>{
    setHasInit(false)
    if (props.updateModalOpen) {
      postMenuGetMenuTree().then((resp: API.Response)=>{
        setTreeData(resp.data.tree)
      }).catch(()=>{})
      postApiGetAllApisByGroup().then((resp: API.Response)=> {
        setApiTreeData(resp.data.apis)
      }).catch(()=>{})
      postDepartmentGetDepartmentTree().then((resp)=>{
        setDeptTreeData(resp.data.tree)
      }).catch(()=>{})
      postRoleGetRolePermission({id: props.values.id}).then((resp)=>{
        setInitApiData(resp.data.apiIds)
        setInitMenuData(resp.data.menuIds)
        setDataScope(resp.data.dataScope)
        setInitDepartmentData(resp.data.deptIds)
        setHasInit(true)
        console.log(initMenuData, initDepartmentData, initApiData)
      }).catch(()=>{})
    }

  }, [props.updateModalOpen])
  return (
    <ModalForm<API.UpdateRolePermissionParams>
      title={intl.formatMessage({
        id: 'common.modal.table.update.title',
        defaultMessage: '$$$',
      })}
      open={props.updateModalOpen}
      form={form}
      autoFocusFirstInput
      modalProps={{
        destroyOnClose: true,
        onCancel: () => props.handleModal(),
      }}
      submitTimeout={2000}
      onFinish={async (values) => {
        console.log(333333, values)
        putRoleUpdateRolePermission(values).then(() => {
          message.success(intl.formatMessage({id: 'common.success', defaultMessage: '$$$'}))
          props.reload()
        }).catch(() => {
          message.error(intl.formatMessage({id: 'common.failure', defaultMessage: '$$$'}))
        })

        props.handleModal();
        return true;
      }}
    >
      <ProFormText width="md" name="roleId" label="id" disabled={true} initialValue={props.values.id}/>
      {
        hasInit && (
          <Tabs
            defaultActiveKey={'menu'}
            tabBarExtraContent={
              <a
                style={{
                  display: 'flex',
                  gap: 4,
                }}
              >
              </a>
            }
            items={[
              {
                key: 'menu',
                label: intl.formatMessage({id: 'system.role.table.list.menu_permission', defaultMessage: '$$$'}),
                children:
                  <ProForm.Item label="菜单权限" shouldUpdate>
                    {(form) => {
                      return (
                        <ProForm.Item name="menuIds">
                          <Tree
                            checkable
                            defaultExpandAll={true}
                            defaultCheckedKeys={initMenuData}
                            autoExpandParent={true}
                            onCheck={(checkedKeys) => {
                              form.setFieldsValue({menuIds: checkedKeys})
                            }}
                            treeData={treeData}
                            // loadData={({treeNode}) => {
                            //   return treeData
                            // }}
                          />
                        </ProForm.Item>
                      );
                    }}
                  </ProForm.Item>

              },
              {
                key: 'api',
                label: intl.formatMessage({id: 'system.role.table.list.api_permission', defaultMessage: '$$$'}),
                children: <ProForm.Item label="api权限" shouldUpdate>
                  {(form) => {
                    return (
                      <ProForm.Item name="apiIds">
                        <Tree
                          checkable
                          defaultExpandAll={true}
                          defaultCheckedKeys={initApiData}
                          onCheck={(checkedKeys) => {
                            form.setFieldsValue({apiIds: checkedKeys})
                          }}
                          treeData={apitreeData}
                          // loadData={({treeNode}) => {
                          //   return treeData
                          // }}
                        />
                      </ProForm.Item>
                    );
                  }}
                </ProForm.Item>
              },
              {
                key: 'resource',
                label: intl.formatMessage({id: 'system.role.table.list.resource_permission', defaultMessage: '$$$'}),
                children:
                  <>
                    <ProFormSelect
                      name="dataScope"
                      placeholder={intl.formatMessage({id: 'common.please_select', defaultMessage: '$$$'})}
                      style={{ width: 150 }}
                      initialValue={dataScope}
                      options={dataSourceItems}
                    />
                    <ProFormDependency name={['dataScope']}>
                      {({ dataScope }) => {
                        if (dataScope === '2') {
                          return (
                            <ProForm.Item name="deptIds">
                              <Tree
                                checkable
                                defaultExpandAll={true}
                                defaultCheckedKeys={initDepartmentData}
                                onCheck={(checkedKeys: any) => {
                                  form.setFieldsValue({deptIds: checkedKeys})
                                }}
                                treeData={deptTreeData}
                              />
                            </ProForm.Item>
                          );
                        }
                      }}
                    </ProFormDependency>
                  </>

              },
            ]}
          />
        )
      }

    </ModalForm>)
}
export default SetPermissionForm;
