import React, { useState, useEffect } from 'react';
import { Checkbox, Input, Card, Form, Button, Row, Col, Spin, message } from 'antd';
import { connect } from 'dva';
import XForm, { FieldTypes } from '@/components/XForm';
import AuthButton from '@/components/AuthButton';
import request from '@/utils/request';
import router from 'umi/router';
import apis from '@/services/apis';

const { TextArea } = Input;

/**
 *
 *
 * @param {*} props
 * @returns
 */
const Poster = props => {
  const userMenus = props.user.currentUser.menus;
  const userBtns = props.user.currentUser.buttons;
  console.log(userMenus);
  // 获取当前所有菜单
  const [data, setData] = useState({ data: [] });
  const [buttonData, setButtonData] = useState([]);

  // 展示要显示的菜单和按钮----（编辑）
  const [dataMenuId, setDataMenuId] = useState([]);
  const [dataButtonId, setDataButtonId] = useState([]);

  const [loading, setLoading] = useState(false);

  useEffect(() => {
    // 新增和编辑用一个页面
    if (props.location.query) {
      const { id } = props.location.query;
      if (id) {
        buttonAndMenuList('', id);
      }
    }
    // menuList({ pageNum: 1, pageSize: 100 })
    buttonList({ pageNum: 1, pageSize: 100 });
  }, []);
  // 当前所有的菜单
  function menuList(params) {
    request({ ...apis.role.menuList, params: { ...params } })
      .then(data => {
        setData(data);
      })
      .catch(err => {
        console.log(err);
        message.info(err.msg || err.message);
      });
  }

  // 所有按钮
  function buttonList(params) {
    request({ ...apis.role.buttonList, params: { ...params } })
      .then(data => {
        setButtonData(data);
      })
      .catch(err => {
        console.log(err);
      });
  }

  // 根据角色id查询当前的菜单及其按钮
  function buttonAndMenuList(params, ids) {
    setLoading(true);
    request({ ...apis.role.buttonAndMenuList, urlData: { id: ids }, params: { ...params } })
      .then(data => {
        setLoading(false);
        props.form.setFieldsValue({ roleName: data.roleName });
        console.log(data);
        setData(data);

        // 获取所有的权限Id
        if (data.sysMenuList) {
          setDataMenuId(data.sysMenuList.map(item => item && item.menuId));
          // setDataButtonId((data.sysMenuList.map(item => item.sysButtonInMenu && item.sysButtonInMenu.map(btn => btn.btnId).join(',')).filter(f => f !== '').join(',').split(',')).map(a => parseInt(a) ) )
          setDataButtonId(data.sysButtonInMenu.map(item => item && item.btnId));
        }
      })
      .catch(err => {
        console.log(err);
        message.info(err.msg || err.message);
      });
  }

  // const [menus, setMenus] = useState([]);
  // 判断menus是否有值
  const [menus, setMenus] = useState([]);
  const [but, setBut] = useState([]);

  const addMenus = m => setMenus([...menus, m]);
  const delMenus = m => setMenus(menus.filter(x => x.menuId !== m.menuId));

  const handleMenuChange = m => e => {
    // 如果是根菜单, 把子菜单挑出来
    const isMenuRoot = m.parentCode === '-1';
    const subMenus = isMenuRoot ? userMenus.filter(x => x.parentCode == m.menuId) : [];
    // 把子菜单与当前对象, 同时作为当前操作对象
    const currentMenus = [m, ...subMenus];
    // 先把选中列表中, 当前操作对象去掉
    const leftCheckedMenusIds = dataMenuId.filter(x => !currentMenus.some(it => it.menuId == x));

    // 当前选中菜单
    const currentCheckedMenus = e.target.checked ? currentMenus : [];

    // 计算所有选中菜单
    let checkedMenus = [
      ...currentCheckedMenus,
      ...userMenus.filter(x => leftCheckedMenusIds.some(it => it == x.menuId)),
    ];

    // 如果子菜单全部取消选择, 那么根菜单也取消选择
    // 如果子菜单有一个选中, 那么根菜单也选中
    if (!isMenuRoot) {
      const children = checkedMenus.filter(
        x => x.menuRoot === m.menuRoot && x.menuId !== m.menuRoot,
      );
      if (!children || children.length < 1) {
        checkedMenus = checkedMenus.filter(x => x.menuId !== m.menuRoot);
      } else {
        const hasRootMenu = checkedMenus.some(x => x.menuId === m.menuRoot);

        if (!hasRootMenu) {
          const rootMenu = userMenus.filter(x => x.menuId === m.menuRoot)[0];
          if (rootMenu) {
            checkedMenus.push(rootMenu);
          }
        }
      }
    }

    // 只要菜单选中, 所属按钮全部选中
    // 菜单取消选择, 所有按钮全部取消选择
    const currentMenuBtns = currentMenus.reduce(
      (acc, it) => [...acc, ...userBtns.filter(x => x.menuId === it.menuId)],
      [],
    );
    const currentCheckedMenuBtns = currentCheckedMenus.reduce(
      (acc, it) => [...acc, ...userBtns.filter(x => x.menuId === it.menuId)],
      [],
    );
    const checkedBtns = dataButtonId
      .filter(x => !currentMenuBtns.some(it => it.btnId === x))
      .map(x => userBtns.filter(it => x == it.btnId)[0])
      .concat(...currentCheckedMenuBtns);

    setMenus(checkedMenus);
    setDataMenuId(checkedMenus.map(x => x.menuId));
    setDataButtonId(checkedBtns.map(x => x.btnId));
    setBut(checkedBtns);
  };

  // 判断menus是否有值
  const addBut = m => setBut([...but, m]);
  const delBut = m => setBut(but.filter(x => x.menuId !== m.menuId));
  const handleButChange = m => e => {
    // 如果有一个按钮选中, 那么对应的菜单也需要选中
    // 如果没有一个兄弟节点选中, 不做任何处理
    if (e.target.checked) {
      const parentMenuId = dataMenuId.filter(x => x === m.menuId)[0];

      if (!parentMenuId) {
        const parentMenu = userMenus.filter(x => x.menuId === m.menuId)[0];
        const parentMenuRoot = userMenus.filter(x => x.menuId === parentMenu.menuRoot)[0];

        const checkedMenus = menus.concat(parentMenu).concat(parentMenuRoot);
        setMenus(checkedMenus);
        setDataMenuId(checkedMenus.map(x => x.menuId));
      }
    }

    if (e.target.checked) {
      setDataButtonId(dataButtonId.concat(m.btnId));
      addBut(m);
    } else {
      setDataButtonId(dataButtonId.filter(item => item !== m.btnId));
      delBut(m);
    }
  };
  const gridStyle1 = {
    width: '20%',
    textAlign: 'left',
    height: '72px',
    padding: '24px',
  };
  const gridStyle2 = {
    width: '80%',
    textAlign: 'left',
    height: '72px',
  };

  function toRoleList() {
    router.go('-1');
  }

  function updateAuthMenu(data) {
    setLoading(true);
    request({ ...apis.role.updateAuthMenu, data: { ...data } })
      .then(data => {
        setLoading(false);
        toRoleList();
      })
      .catch(err => {
        console.log(err);
      });
  }

  function handleSubmit(e) {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      if (values.roleName === undefined || values.roleName === '') {
        message.error('请输入角色名称');
        return;
      }

      if (props.location.query.id !== undefined) {
        console.log('menus', menus);

        const sumitMenu = userMenus.filter(item => dataMenuId.includes(item.menuId));
        const sumitBtn = buttonData.filter(item => dataButtonId.includes(item.btnId));
        updateAuthMenu({
          sysMenu: sumitMenu,
          name: values.roleName,
          id: props.location.query.id,
          sysButton: sumitBtn,
        });
      } else {
        updateAuthMenu({
          sysMenu: menus,
          name: values.roleName,
          id: props.location.query.id,
          sysButton: but,
        });
      }
    });
  }
  const { getFieldDecorator } = props.form;

  return (
    <Card>
      <div>
        <Spin spinning={loading} size="large">
          <Form labelCol={{ span: 6 }} wrapperCol={{ span: 12 }} onSubmit={handleSubmit}>
            <Form.Item label="角色名称">
              {getFieldDecorator('roleName', {
                rules: [{ required: true, message: '请输入角色名称' }],
              })(<Input />)}
            </Form.Item>
            {userMenus.map(
              item =>
                item.parentCode === '-1' && (
                  <Row>
                    <Col span={6}></Col>
                    <Col span={18}>
                      <Card
                        title={
                          <Checkbox
                            checked={dataMenuId.includes(item.menuId)}
                            onChange={handleMenuChange(item)}
                          >
                            {item.name}
                          </Checkbox>
                        }
                        bordered
                        style={{
                          width: '100%',
                          alignItems: 'center',
                          margin: '10px 0',
                          boxShadow: '3px 3px 10px  rgba(0,0,0,0.15)',
                          borderRadius: '8px',
                        }}
                      >
                        {userMenus.map(
                          menu =>
                            item.menuId === menu.menuRoot &&
                            item.menuId !== menu.menuId && (
                              <>
                                <Card.Grid style={gridStyle1}>
                                  <Checkbox
                                    checked={dataMenuId.includes(menu.menuId)}
                                    onChange={handleMenuChange(menu)}
                                  >
                                    {menu.name}
                                  </Checkbox>
                                </Card.Grid>
                                <Card.Grid style={gridStyle2}>
                                  {buttonData.length > 0 &&
                                    buttonData.map(btn => (
                                      <>
                                        {btn.menuId === menu.menuId && (
                                          <Checkbox
                                            checked={dataButtonId.includes(btn.btnId)}
                                            onChange={handleButChange(btn)}
                                          >
                                            {btn.name}
                                          </Checkbox>
                                        )}
                                      </>
                                    ))}
                                </Card.Grid>
                              </>
                            ),
                        )}
                      </Card>
                    </Col>
                  </Row>
                ),
            )}
            <Form.Item wrapperCol={{ span: 15, offset: 7 }} style={{ marginTop: '10px' }}>
              <AuthButton name="role.submit" noRight={null}>
                <Button type="primary" htmlType="submit">
                  保存
                </Button>
              </AuthButton>
              <Button onClick={toRoleList} style={{ marginLeft: '20px' }}>
                取消
              </Button>
            </Form.Item>
          </Form>
        </Spin>
      </div>
    </Card>
  );
};
const WrappedNormalLoginForm = Form.create({ name: 'Poster' })(Poster);
export default connect(({ user }) => ({ user }))(WrappedNormalLoginForm);
