import React, { useState, useEffect, useReducer } from 'react';
import { Button, Tree, message } from 'antd';
import { roleTree, adminDataqueryAll } from '@/services/system';
import { doFetch } from '@/utils/doFetch';
import { useRequest } from 'ahooks';
const TreeNode = Tree.TreeNode;
const initState = {
  pcList: [],
  havepremIdList: [],
  haveParentIdList: [],
  appTree: [],
  appCheckedKeys: [],
  appHalfCheckedKeys: [],
  daauthTree: [],
  daauthCheckkedKeys: [],
  daauthHalfCheckedKeys: [],
};
function reducer(state, action) {
  let { type } = action,
    newState = {};
  switch (type) {
    case 'changePc':
      newState = {
        ...state,
        havepremIdList: [...action.checkedKeys],
        haveParentIdList: [...action.halfCheckedKeys],
      };
      break;
    case 'changeApp':
      newState = {
        ...state,
        appCheckedKeys: [...action.checkedKeys],
        appHalfCheckedKeys: [...action.halfCheckedKeys],
      };
      break;
    case 'changeDaauth':
      newState = {
        ...state,
        daauthCheckkedKeys: [...action.checkedKeys],
        daauthHalfCheckedKeys: [...action.halfCheckedKeys],
      };
      break;
    case 'reset':
      newState = {
        ...state,
        pcList: [...action.pcList],
        havepremIdList: [...action.havepremIdList],
        haveParentIdList: [...action.haveParentIdList],
        // appTree: [...action.appTree],
        // appCheckedKeys: [...action.appCheckedKeys],
        // appHalfCheckedKeys: [...action.appHalfCheckedKeys]
      };
      break;
    case 'daauth':
      newState = {
        ...state,
        daauthTree: action.nodeList ? [...action.nodeList] : [],
        daauthCheckkedKeys: action.havepremIdList ? [...action.havepremIdList] : [],
        daauthHalfCheckedKeys: action.haveParentIdList ? [...action.haveParentIdList] : [],
      };
      break;
  }

  return newState;
}

const Permissiontree = (props) => {
  const { id, close, treeType } = props,
    [state, dispatch] = useReducer(reducer, initState),
    {
      pcList,
      havepremIdList,
      haveParentIdList,
      appTree,
      appCheckedKeys,
      appHalfCheckedKeys,
      daauthCheckkedKeys,
      daauthHalfCheckedKeys,
      daauthTree,
    } = state;

  console.log('tree', props);
  useEffect(() => {
    resetData();
  }, []);
  const loop = (data) => {
      return data.map((item) => {
        if (item.children) {
          return (
            <TreeNode key={item.key} title={item.title}>
              {loop(item.children)}
            </TreeNode>
          );
        }
        return <TreeNode key={item.key} title={item.title} />;
      });
    },
    pcCheck = (checkedKeys, info) => {
      dispatch({ type: 'changePc', checkedKeys, halfCheckedKeys: info.halfCheckedKeys });
    },
    appCheck = (checkedKeys, info) => {
      dispatch({ type: 'changeApp', checkedKeys, halfCheckedKeys: info.halfCheckedKeys });
    },
    daauthCheck = (checkedKeys, info) => {
      dispatch({ type: 'changeDaauth', checkedKeys, halfCheckedKeys: info.halfCheckedKeys });
    },
    { run, loading } = useRequest(doFetch, {
      manual: true,
      onSuccess: (result, params) => {
        if (result.code == '0000') {
          message.success('权限配置成功！');
          close();
        }
      },
    });

  function resetData() {
    if (!id) {
      return;
    }
    if (treeType == 'auth') {
      console.log(1);
      roleTree({ roleId: id }).then((res) => {
        if (res.code == '0000') {
          let data = res?.data || {};
          const { pcList, havepremIdList, haveParentIdList } = data;
          dispatch({ type: 'reset', pcList, havepremIdList, haveParentIdList });
        }
      });
    } else {
      // adminDataqueryAll({ roleId: id }).then(res => {
      //     if (res.code == "0000") {
      //         let data = res?.data || {};
      //         const { nodeList, havepremIdList, haveParentIdList } = data;
      //         dispatch({ type: "daauth", nodeList, havepremIdList, haveParentIdList })
      //     }
      // })
    }
  }
  const saveData = () => {
    run({
      url: '/auth/sysRolePermission/save',
      params: {
        roleId: id,
        permissionIds: [...havepremIdList, ...haveParentIdList],
      },
    });
  };

  return (
    <div>
      <div style={{ width: '100%', display: 'flex', overflow: 'hidden', minHeight: 100 }}>
        {treeType == 'auth' ? (
          <>
            <div style={{ flex: 1, minHeight: 100 }}>
              <h3 style={{ marginBottom: 16 }}>请配置角色权限：</h3>
              <Tree
                checkable
                defaultExpandAll={false}
                checkedKeys={havepremIdList}
                onCheck={pcCheck}
              >
                {loop(pcList || [])}
              </Tree>
            </div>
            {/* <div style={{ flex: 1, minHeight: 100 }}>
                        <div style={{ marginBottom: 10 }}>app权限：</div>
                        <Tree
                            checkable
                            defaultExpandAll={false}
                            checkedKeys={appCheckedKeys}
                            onCheck={appCheck}
                        >
                            {loop(appTree || [])}
                        </Tree>
                    </div> */}
          </>
        ) : (
          <Tree
            checkable
            defaultExpandAll={false}
            checkedKeys={daauthCheckkedKeys}
            onCheck={daauthCheck}
          >
            {loop(daauthTree || [])}
          </Tree>
        )}
      </div>
      <Button
        loading={loading}
        type="primary"
        style={{ width: '100%', marginTop: 15 }}
        onClick={saveData}
      >
        提交
      </Button>
    </div>
  );
};

export default Permissiontree;
