import React, { forwardRef, useImperativeHandle, useState, useEffect } from 'react';
import { Input, Checkbox, Button, Tree, notification, Spin } from 'antd';
import { Form } from '@ant-design/compatible';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { getUserPermissions } from '@/services/user';
import { addResource, getRoleDetail, modifyRole } from '../../service';

import UUID from '@/utils/uuid';

import style from './index.less';

import { APP_CODE, TENANT_ID } from '@/utils/constants';
// mock
const { TextArea } = Input;
const { TreeNode } = Tree;

/**
 * 权限表单/权限展示
 * @param {*} props
 * @param {boolean} props.submittable 是否可提交（即：是否展示操作）
 * @param {number} props.id 判断是否是新增
 * @param {boolean} props.readyonly 是否全部为只读(查看操作)
 */
const RoleInfo = props => {
  const {
    id,
    submittable = true,
    readyonly = false,
    defaultExpandAll = true,
    height,
    labelCol = { span: 4 },
    wrapperCol = { span: 12 },
  } = props;
  const { getFieldDecorator, getFieldValue, validateFields, setFieldsValue } = props.form;

  // 可选的权限数据
  const [permissionsData, setPermissionsData] = useState([]);
  // 当前选中的权限-仅提交时使用
  const [selectedPermissions, setSelectedPermissions] = useState([]);
  const [detailInfo, setDetailInfo] = useState({});
  const [loading, setLoading] = useState(false);

  // 表单布局
  const formLayout = {
    labelCol,
    wrapperCol,
  };
  const btnLayout = {
    wrapperCol: { offset: 4, span: 12 },
  };

  // 表单验证
  const formRules = {
    name: [{ required: true, message: '请设置角色名称' }],
    description: [{ required: true, message: '请填写角色描述' }],
    selected: [{ type: 'array', required: true, message: '请选择权限' }],
  };

  const treeProps = {
    defaultExpandAll,
  };

  // 表单验证辅助函数
  const rulesHandler = field => ({
    rules: formRules[field] || [],
  });

  //  提交数据
  const onSubmit = () => {
    validateFields(async (err, fieldsValue) => {
      console.log('fieldsValue :>>', fieldsValue);
      if (err) {
        return;
      }
      // 提交
      const params = {
        tenantId: TENANT_ID,
        code: UUID.createUUID(),
        app: {
          appCode: APP_CODE,
          selected: selectedPermissions,
        },
        ...fieldsValue,
      };
      if (id) {
        params.id = id;
      }
      // 删除提交时无用的字段
      delete params.selected;

      console.log('params :>>', params);
      const res = await addResource(params);
      console.log(res);
      if (res.code !== 2000) {
        notification.warning({
          message: `${res.msg}:${res.detail}`,
        });
        return;
      }
      notification.success({
        message: '提交成功',
      });
      setTimeout(() => {
        window.history.back();
      }, 1000);
    });
  };

  // 选择权限回调
  const onPermissionsCheck = checkedKeys => {
    if (readyonly) {
      return;
    }
    setSelectedPermissions(checkedKeys);
    setFieldsValue({
      selected: checkedKeys,
    });
  };

  // 初始化权限数据
  // TODO:分离接口
  const initPermissions = (res, roleId) => {
    if (res.code !== 2000) {
      notification.warning({
        message: res.msg,
      });
    }
    let resource = [];
    let selected = [];
    if (roleId) {
      const { resource: resourceData, selected: selectedData } = res.data;
      resource = resourceData;
      selected = selectedData;
    } else {
      resource = res.data;
    }

    setPermissionsData(resource);
    setSelectedPermissions(selected);
    setFieldsValue({
      selected,
    });
  };

  // 初始化当前角色数据
  const initRoleData = res => {
    if (res.code !== 2000) {
      notification.warning({ message: res.detail });
      return;
    }
    console.log(res.data);
    const { name, description } = res.data;
    setFieldsValue({
      name,
      description,
    });
    setDetailInfo({
      name,
      description,
    });
  };

  const initData = async () => {
    const roleId = id || null;
    setLoading(true);
    const permissionsRes = await getUserPermissions(roleId);
    if (id) {
      const roleDetailRes = await getRoleDetail({ id });
      initRoleData(roleDetailRes);
    }
    setLoading(false);
    initPermissions(permissionsRes, roleId);
  };

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

  const renderTreeNodes = data =>
    data.map(item => {
      if (item.childNodes) {
        return (
          <TreeNode title={item.node.name} key={item.node.id} dataRef={item}>
            {renderTreeNodes(item.childNodes)}
          </TreeNode>
        );
      }
      return <TreeNode key={item.node.id} {...item} />;
    });

  return (
    <div className={style['info-box']}>
      <Spin spinning={loading}>
        <Form className={style['info-box--form']} {...formLayout}>
          <Form.Item label="角色名称">
            {readyonly
              ? detailInfo.name
              : getFieldDecorator('name', rulesHandler('name'))(
                  <Input maxLength={10} placeholder="10个字以内" />,
                )}
          </Form.Item>
          <Form.Item label="角色描述">
            {readyonly
              ? detailInfo.description || '-'
              : getFieldDecorator('description', rulesHandler('description'))(
                  <TextArea maxLength={30} placeholder="30个字以内"></TextArea>,
                )}
          </Form.Item>
          <Form.Item label="权限">
            {getFieldDecorator('selected', rulesHandler('selected'))(
              <div className={style.tree} style={{ height }}>
                {permissionsData.length ? (
                  <Tree
                    checkable
                    selectable={false}
                    defaultExpandAll
                    onCheck={onPermissionsCheck}
                    checkedKeys={selectedPermissions}
                  >
                    {renderTreeNodes(permissionsData)}
                  </Tree>
                ) : (
                  ''
                )}
              </div>,
            )}
          </Form.Item>

          {submittable ? (
            <Form.Item {...btnLayout}>
              <Button type="default" onClick={() => window.history.back()}>
                返回
              </Button>
              <Button className={style['submit-button']} type="primary" onClick={onSubmit}>
                提交
              </Button>
            </Form.Item>
          ) : (
            ''
          )}
        </Form>
      </Spin>
    </div>
  );
};

export const RoleInfoComponent = Form.create({})(RoleInfo);

const PageWapperComponent = props => {
  const { id } = props.location?.query;
  const [title, setTitle] = useState('新增角色');

  useEffect(() => {
    if (id) {
      setTitle('编辑角色');
    }
  }, []);

  const roleInfo = {
    id,
  };

  return (
    <PageHeaderWrapper title={title}>
      <RoleInfoComponent {...roleInfo} />
    </PageHeaderWrapper>
  );
};

export default PageWapperComponent;
