import React, { useState, useEffect, useRef } from 'react';
import { history, Link } from 'umi';
import {
  Button,
  Popconfirm,
  Modal,
  Form,
  Input,
  message,
  Tree,
  Checkbox,
  Row,
  Col,
  Divider,
} from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { getRoleList, addRole, deleteRole, updateRole, getMenuList } from '@/services/role';
import { getPermissionList, addPermission, getRoleRermissionDetail } from '@/services/permission';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import moment from 'moment';
import PageTable from '@/components/PageTable';
import RoleCheckbox from '@/components/RoleCheckbox';

const formatterTime = (val) => {
  return val && val !== '-' ? moment(val).format('YYYY-MM-DD') : '-';
};
const FormItem = Form.Item;

export default (props) => {
  //列表
  const actionRef = useRef();
  // 角色表单
  const formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 14 } };
  const [form] = Form.useForm();
  const [editModal, setEditModal] = useState(false);
  const [loading, setLoading] = useState(false);
  const [roleId, setRoleId] = useState();
  const [roleMId, setRoleMId] = useState();

  // 授权弹窗
  const [showModal, setShowModal] = useState(false);
  const [treeList, setTreeList] = useState([]);
  const [permissionAllList, setPermissionAllList] = useState([]);
  const [primordialData, setPrimordialData] = useState([]);

  const [currenList, setCurrentList] = useState([]);
  const [title, setTitle] = useState('');
  //选中的权限列表
  const [rolePermissionList, setRolePermissionList] = useState([]);
  const [pLoading, setPLoading] = useState(false);
  let parentList = [];
  let pid = '';

  //列表编辑
  const handelEdit = (val) => {
    setRoleId(val.roleId);
    form.setFieldsValue(val);
    setEditModal(true);
  };
  //列表删除
  const handleDelete = (id) => {
    deleteRole(id)
      .then(() => {
        message.success('删除成功');
        actionRef.current.reload();
      })
      .catch((err) => {
        message.error(err);
      });
  };
  //列表角色授权
  const handelEmpower = (val) => {
    setRoleMId(val.roleId);
    setShowModal(true);
    getRoleRermissionDetail({ roleId: val.roleId })
      .then((res) => {
        setRolePermissionList(
          res.map((item) => {
            return item.permissionId;
          }),
        );
      })
      .catch((err) => {
        message.error(err);
      });
  };

  // 表单提交
  const Submit = (values) => {
    setLoading(true);
    if (roleId) {
      updateRole(roleId, values).then(() => {
        setLoading(false);
        message.success(`修改成功`);
        onCancel();
        actionRef.current.reload();
      });
    } else {
      addRole(values)
        .then(() => {
          setLoading(false);
          message.success(`保存成功`);
          onCancel();
          actionRef.current.reload();
        })
        .catch((err) => {
          setLoading(false);
          message.error(err.message || err);
        });
    }
  };
  //角色弹窗关闭
  const onCancel = () => {
    setRoleId();
    form.resetFields();
    setEditModal(false);
  };
  //授权弹窗关闭
  const onEmpowerCancel = () => {
    setRoleMId();
    setShowModal(false);
    setRolePermissionList([]);
    setCurrentList([]);
    parentList = [];
    pid = '';
  };
  //递归取出树结构中的所以项便于加入最终选中的菜单项
  const treeToArray = (tree) => {
    if (tree.children) {
      return [{ title: tree.title, key: tree.key }, ...tree.children];
    } else return { title: tree.title, key: tree.key };
  };
  // 选择左侧的菜单多选框
  const onCheck = (checkedKeys, info) => {
    //当前选中数组
    let list2;
    let list3 = [...rolePermissionList];
    //权限数据
    var list4 = list3.filter((item) => item.split(':').length == 2);
    if (info.checked) {
      if (info.node.children) {
        list2 = treeToArray(info.node).map((item) => {
          return item.key;
        });
        list2.forEach((item) => {
          if (list3.indexOf(item) === -1) {
            list3.push(item);
          }
        });
      } else {
        list2 = info.node.key;
        if (list3.indexOf(list2) === -1) {
          list3.push(list2);
        }
      }
    } else {
      setTitle();
      setCurrentList([]);
      //取消菜单
      if (info.node.children) {
        list2 = treeToArray(info.node).map((item) => {
          return item.key;
        });
        list2.forEach((item) => {
          if (list3.indexOf(item) !== -1) {
            list3.splice(list3.indexOf(item), 1);
            list4.map((v) => {
              if (v.split(':')[0] == item) {
                list3.splice(list3.indexOf(v), 1);
              }
            });
          }
        });
      } else {
        list2 = info.node.key;
        if (list3.indexOf(list2) !== -1) {
          list3.splice(list3.indexOf(list2), 1);
          list4.map((v) => {
            if (v.split(':')[0] == list2) {
              list3.splice(list3.indexOf(list2), 1);
            }
          });
        }
      }
    }
    if (list3.length < checkedKeys.length + list4.length) {
      // 说明父节点是因为子节点全部选中才选中实际上菜单数组中没有父节点的数据
      checkedKeys.forEach((item) => {
        if (list3.indexOf(item) === -1) {
          list3.push(item);
        }
      });
    } else if (list3.length > checkedKeys.length + list4.length) {
      // 说明父节点是因为子节点全部取消才取消实际上菜单数组中多了父节点的数据
      list3.forEach((item) => {
        if (checkedKeys.indexOf(item) === -1 && list4.indexOf(item) === -1) {
          list3.splice(list3.indexOf(item), 1);
        }
      });
    }
    setRolePermissionList(list3);
  };
  // 选择左侧菜单文字
  const onSelect = (checkedKeys, info) => {
    if (info.selected) {
      var list = permissionAllList.filter((item) => item.resourceId === info.node.key);
      setTitle(info.node.title);
      setCurrentList(list);
    } else {
      setTitle();
      setCurrentList([]);
    }
  };
  const setParnentList = (val) => {
    pid = primordialData.filter((item) => item.menuId === val)[0].menuPId;
    if (pid !== '-1') {
      parentList.push(pid);
      setParnentList(pid);
    }
  };
  const handelOk = () => {
    var list = [...rolePermissionList];
    if (list.length == 0) {
      message.info('授权内容不能为空');
      return;
    }
    setPLoading(true);
    //菜单数据
    var list4 = rolePermissionList.filter((item) => item.split(':').length !== 2);
    list4.forEach((item) => {
      setParnentList(item);
    });

    parentList = [...new Set(parentList)];
    parentList.forEach((item) => {
      if (list.indexOf(item) === -1) {
        list.push(item);
      }
    });
    list = list.map((item) => {
      return { permissionId: item };
    });
    addPermission(roleMId, list)
      .then(() => {
        message.success('授权成功');
        setPLoading(false);
        onEmpowerCancel();
      })
      .catch((err) => {
        message.error(err);
        setPLoading(false);
      });
  };

  // 将一维对象数组装换为树形数组
  const translateDataToTree = (data) => {
    //没有父节点的数据
    let parents = data.filter((value) => value.menuPId == '-1');

    //有父节点的数据
    let children = data.filter((value) => value.menuPId !== '-1');

    //定义转换方法的具体实现
    let translator = (parents, children) => {
      //遍历父节点数据
      parents.forEach((parent) => {
        //遍历子节点数据
        children.forEach((current, index) => {
          //此时找到父节点对应的一个子节点
          if (current.menuPId === parent.menuId) {
            //对子节点数据进行深复制，这里只支持部分类型的数据深复制，对深复制不了解的童靴可以先去了解下深复制
            let temp = JSON.parse(JSON.stringify(children));
            //让当前子节点从temp中移除，temp作为新的子节点数据，这里是为了让递归时，子节点的遍历次数更少，如果父子关系的层级越多，越有利
            temp.splice(index, 1);
            //让当前子节点作为唯一的父节点，去递归查找其对应的子节点
            translator([current], temp);
            //把找到子节点放入父节点的children属性中
            typeof parent.children !== 'undefined'
              ? parent.children.push(current)
              : (parent.children = [current]);
          }
        });
      });
    };

    //调用转换方法
    translator(parents, children);

    //返回最终的结果
    return parents;
  };
  useEffect(() => {
    getMenuList()
      .then((res) => {
        setPrimordialData(res);
        const list = translateDataToTree(res);
        const list2 = list.map((item) => {
          if (item.children?.length > 0) {
            return {
              title: item.name,
              key: item.menuId,
              children: item.children.map((v) => {
                return { title: v.name, key: v.menuId };
              }),
            };
          } else {
            return { title: item.name, key: item.menuId };
          }
        });
        setTreeList(list2);
      })
      .catch((err) => {
        message.error(err);
      });
    getPermissionList()
      .then((res) => {
        setPermissionAllList(res);
      })
      .catch((err) => {
        message.error(err);
      });
  }, []);
  useEffect(() => {
    if (roleId) {
    } else {
      form.resetFields();
    }
  }, [roleId]);

  const actions = () => [
    <Button key="add" type="primary" icon={<PlusOutlined />} onClick={() => setEditModal(true)}>
      新增
    </Button>,
  ];
  const columns = [
    {
      title: '角色名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '创建时间',
      dataIndex: 'createDate',
      key: 'createDate',
      render: formatterTime,
    },
    {
      title: '操作',
      valueType: 'option',
      render: (_, record) => [
        <a key={1} onClick={() => handelEdit(record)}>
          编辑
        </a>,
        <Popconfirm
          key={2}
          title="您是否确认删除 ?"
          onConfirm={() => handleDelete(record.roleId)}
          okText="确定"
          cancelText="取消"
        >
          <a href="#">删除</a>
        </Popconfirm>,
        <a key={3} onClick={() => handelEmpower(record)}>
          角色授权
        </a>,
      ],
    },
  ];

  return (
    <PageHeaderWrapper>
      <PageTable
        request={getRoleList}
        // expfunc={exportPersonList}
        columns={columns}
        actionRef={actionRef}
        rowKey="roleId"
        options={false}
        toolBarRender={actions}
        search={false}
      />
      <Modal
        forceRender
        title={roleId ? '角色编辑' : '角色新增'}
        visible={editModal}
        onCancel={onCancel}
        keyboard={false}
        maskClosable={false}
        destroyOnClose={true}
        footer={null}
      >
        <Form {...formItemLayout} onFinish={Submit} form={form}>
          <FormItem label="角色名" name="name" rules={[{ required: true, message: '请输入' }]}>
            <Input placeholder="请输入" />
          </FormItem>
          <FormItem label=" " colon={false}>
            <Button type="default" onClick={onCancel}>
              取消
            </Button>
            <Button
              type="primary"
              loading={loading}
              htmlType="Submit"
              style={{ marginLeft: '4em' }}
            >
              确认
            </Button>
          </FormItem>
        </Form>
      </Modal>
      <Modal
        title="角色授权"
        visible={showModal}
        onCancel={onEmpowerCancel}
        keyboard={false}
        maskClosable={false}
        destroyOnClose={true}
        onOk={handelOk}
        confirmLoading={pLoading}
      >
        <Row gutter={24}>
          <Col span={12}>
            <Divider orientation="center">菜单</Divider>
            <Tree
              height={500}
              checkable
              defaultExpandAll
              onSelect={onSelect}
              onCheck={onCheck}
              checkStrictly
              checkedKeys={rolePermissionList}
              treeData={treeList}
            />
          </Col>
          <Col span={12}>
            <RoleCheckbox
              value={rolePermissionList}
              title={title}
              currenList={currenList}
              onchange={setRolePermissionList}
            />
          </Col>
        </Row>
      </Modal>
    </PageHeaderWrapper>
  );
};
