import React, { useState, useRef, useEffect } from 'react';
import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { Modal, Card, Tree, Button, message, Popconfirm} from 'antd';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType, TableDropdown } from '@ant-design/pro-table';
import Enumerable from 'linq'
import CreateForm from './components/CreateForm';
import { Page, add, edit, removeRole, setMenu, GetMenu, GetRoleMenu, SetDataRole } from './service';
import { useAccess } from 'umi';
import MenuForm from './components/MenuForm';
import OrgForm from './components/OrgForm';
import {randomString} from '../../comm'
/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields) => {
  const hide = message.loading('正在添加');
  //let addbol=false;
  try {
    const addbol=add({ ...fields }).then((r) => {
      if (!r.data) {
        message.error('添加失败,'+r.errors);
      }else{
        message.success('添加成功');
      }
      return r.data;
    });
    hide();
    return addbol;
  } catch (error) {
    console.log(error);
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields) => {
  const hide = message.loading('正在更新');
  try {
    await edit({ ...fields });
    hide();

    message.success('更新成功');
    return true;
  } catch (error) {
    hide();
    message.error('更新失败请重试！');
    return false;
  }
};


const cancel = (e) => {
};
/**
 * 分配菜单
 * @param fields
 */
const handleMenu = async (fields) => {
  const hide = message.loading('正在分配菜单');
  try {
    await setMenu({ ...fields });
    hide();

    message.success('分配菜单成功');
    return true;
  } catch (error) {
    hide();
    message.error('分配菜单失败请重试！');
    return false;
  }
};

/**
 * 正在分配数据权限
 * @param fields
 */
const handleGrantData = async (fields) => {
  const hide = message.loading('正在分配数据权限');
  try {
    await SetDataRole({ ...fields });
    hide();
    message.success('分配数据权限成功');
    return true;
  } catch (error) {
    hide();
    message.error('分配数据权限失败请重试！');
    return false;
  }
};
const Prefix = "Role";
const roleManager = () => {
  const [handlModalVisible, handleModalVisible] = useState();
  const [updateMenuModalVisible, handleUpdateMenuModalVisible] = useState();
  const [updateOrgModalVisible, handleUpdateOrgModalVisible] = useState();
  const [stepFormValues, setStepFormValues] = useState({});
  const [formValues, setformValues] = useState({});
  const actionRef = useRef();
  const [row, setRow] = useState();
  const [selectedRowsState, setSelectedRows] = useState();
  const [selectData, setSelectData] = useState([]);
  const [treeData, setTreeData] = useState();
/**
 *  删除节点
 * @param selectedRows
 */
 const handleRemove = async (record) => {
  const hide = message.loading('正在删除');
  if (!record) return true;
  try {
    await removeRole([record.id]).then(r => {
      if(r.succeeded){
        message.success("删除成功");
        actionRef.current.reloadAndRest();
      }else{
        message.error(r.data);
      }
    })
    hide();
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};
  const Btn = (record) => {
    var arr = [];
    arr.push(<a
      disabled={record.code == 'sys_manager_role'}
      style={{ pointerEvents: record.code == 'sys_manager_role' ? 'none' : 'auto' }}
      onClick={() => {
        handleModalVisible(true);
        setformValues(record);
      }}
    >
      更新
    </a>);
    arr.push(
      <Popconfirm
      title="确认删除吗？"
      onConfirm={() => {handleRemove(record)}}
      onCancel={cancel}
      okText="确定"
      cancelText="取消"
    >
    <a
      disabled={record.code == 'sys_manager_role'}
      style={{ pointerEvents: record.code == 'sys_manager_role' ? 'none' : 'auto' }}
      // onClick={() => {
      //   handleRemove(record);
      //   // removeRole([record.id]).then(r => {
      //   //   message.success(r);
      //   //   actionRef.current.reloadAndRest();
      //   // })
      // }}
    >
      删除
    </a>
    </Popconfirm>);
    arr.push(<a
      disabled={record.code == 'sys_manager_role'}
      style={{ pointerEvents: record.code == 'sys_manager_role' ? 'none' : 'auto' }}
      onClick={() => {
        GetRoleMenu(record.id).then(r => {
          setRow(r.data);
          handleUpdateMenuModalVisible(true);
        })
        setStepFormValues(record);
      }}
    >
      授权菜单
    </a>);
    // arr.push(<a
    //   disabled={record.code == 'sys_manager_role'}
    //   style={{ pointerEvents: record.code == 'sys_manager_role' ? 'none' : 'auto' }}
    //   onClick={() => {
    //     handleUpdateOrgModalVisible(true);
    //     setStepFormValues(record);
    //   }}
    // >
    //   授权数据
    // </a>);
    return arr;
  }

  useEffect(() => {
    var parm={getType:'ALL',type:0}
    GetMenu(parm).then((r) => {
      if(r.data){
        setTreeData(r.data);
      }
     
    });
  }, []);

  const columns = [
    {
      title: 'id',
      dataIndex: 'id',
      hideInTable: true,
      hideInSearch: true,
    },
    // {
    //   title: '角色编码',
    //   dataIndex: 'code',
    // },
    {
      title: '角色名称',
      dataIndex: 'name',
      ellipsis: true,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '创建时间',
      search: false,
      dataIndex: 'createAt',
      sorter: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      width: 350,
      render: (_, record) => Btn(record)
    },
  ];

  return <>
    <PageContainer host header={{
      title: '',
      breadcrumb: {},
    }}>
      <ProTable
        headerTitle="角色列表"
        actionRef={actionRef}
        rowKey="id"
        pagination={{ defaultPageSize: 10 }}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => {
          return <Button
            type="primary"
            key="create"
            onClick={() => {
              var values={code:randomString(4)}
              //setStepFormValues(values);
              setformValues({})
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>
        }}
        request={async (params) => {
          let UserData = [];
          var total = 0;
         
          await Page(params).then((r) => {
            UserData = r.data.data;
            total = r.data.total;
          });
          return {
            data: UserData,
            success: true,
            total: total,
          };
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
      />
      {/* {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择 <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a> 项&nbsp;&nbsp;
            </div>
          }
        >
           {(Enumerable.from(localStorage.getItem("permissions").split(',')).contains(Prefix+"Delete")||localStorage.getItem("adminType")==1)?( <Button
            type="primary"
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>):''}
        </FooterToolbar>
      )} */}
      <CreateForm
        onFinish={async (value) => {
          var success = false;
          if (value.id) {
            success = await handleUpdate(value);
          } else {
            success = await handleAdd(value);
          }
          console.log("success")
          console.log(success)
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reloadAndRest();
            }
          }
        }}
        onCancel={() => {
          handleModalVisible(false);
          setStepFormValues({});
        }}
        modalVisible={handlModalVisible}
        values={formValues || {}}
      />
      {stepFormValues && Object.keys(stepFormValues).length ? (
        <MenuForm
          onSubmit={async (value) => {
            const values = {
              sysRoleId: stepFormValues.id,
              sysMenuId: value,
            };

            const success = await handleMenu(values);
            if (success) {
              handleUpdateMenuModalVisible(false);
              setStepFormValues({});
              if (actionRef.current) {
                actionRef.current.reloadAndRest();
              }
            }
          }}
          onCancel={() => {
            handleUpdateMenuModalVisible(false);
            setStepFormValues({});
          }}
          modalVisible={updateMenuModalVisible}
          values={row || {}}
          treeData={treeData}
        />

      ) : null}
      {stepFormValues && Object.keys(stepFormValues).length ? (
        <OrgForm
          onFinish={async (value) => {
            const values = {
              sysRoleId: stepFormValues.id,
              dataScopeType: value.dataScopeType,
              sysOrgId: value.sysOrgId,
            };
            const success = await handleGrantData(values);
            if (success) {
              handleUpdateOrgModalVisible(false);
              setStepFormValues({});
              if (actionRef.current) {
                actionRef.current.reloadAndRest();
              }
            }
          }}
          onCancel={() => {
            handleUpdateOrgModalVisible(false);
            setStepFormValues({});
          }}
          updateModalVisible={updateOrgModalVisible}
          values={stepFormValues}
        />
      ) : null}
    </PageContainer>
    
  </>;
};

export default roleManager;
