import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Row, Col, notification, Checkbox } from 'antd';
import classnames from 'classnames';
import styles from './addForm.less';
import PicturesWall from '@/components/Upload/index';
import ParmarModal from './ParmarModal';
import CheckList from './checkBox';

const { Item } = Form;
const EditForm = props => {
  const { submitCallback, nodeType, info, inf, checkList, valueCallback = () => {} } = props;
  // 处理pageUrl回显
  if (info.product) {
    // if(info.product === 'flutter') {
    //   info.pageUrl = info.product + '/' + info.pageUrl;
    // } else {
    //   info.pageUrl = info.product + info.pageUrl;
    // }
  } else {
    if (!info.pageUrl?.includes('/')) {
      info.pageUrl = 'flutter/' + info.pageUrl;
    } else {
      if (info.pageUrl?.split('/')[0] !== '') {
        info.pageUrl = 'MobileGCK/' + info.pageUrl;
      } else {
        info.pageUrl = 'MobileGCK' + info.pageUrl;
      }
    }
  }
  const [form] = Form.useForm();
  const [otherForm] = Form.useForm();
  const [showParmarModal, setShowParmarModal] = useState(false);
  const [choo, setChoo] = useState(false); // 最外层复选框状态
  const [indeterminate, setIndeterminate] = useState([]);
  const [plainOptions, setPlainOptions] = useState([]); // 存储一级数据
  const [indeterminateAll, setIndeterminateAll] = useState(false);
  const layout = {
    layout: 'horizontal',
    labelCol: { span: 2, offset: 0 },
    wrapperCol: { span: 21 },
  };
  // 回显表单
  useEffect(() => {
    form.resetFields();
    otherForm.resetFields();
    setPlainOptions(inf);
  }, [info]);
  useEffect(() => {
    if (nodeType === 1 || nodeType === 2) {
      let arr = Object.keys(form.getFieldsValue());
      let obj = {};
      arr.map(i => {
        obj[i] = info[i];
      });
      form.setFieldsValue({ ...obj, shortName: info.menuShortName });
    }
    if (nodeType === 3 || nodeType === 4) {
      let arr = Object.keys(otherForm.getFieldsValue());
      let obj = {};
      arr.map(i => {
        obj[i] = info[i];
      });
      otherForm.setFieldsValue({ ...obj, shortName: info.menuShortName });
    }
    if (inf.length > 0) {
      let list = [];
      inf.map(item => {
        list.push(item);
      });
      let chooseData = [];
      let listData = [];
      list.forEach((item, index) => {
        chooseData.push(
          !!list[index].checkedList.size && list[index].checkedList.size < list[index].list.length,
        );
        item.list.map(i => {
          listData.push(i.related);
        });
      });
      let data = new Set();
      let datalist = [];
      inf.map(item => {
        if (item.isChecked == true) {
          data.add(item.groupName);
        }
      });
      list.map((k, i) => {
        k.list.map(p => {
          datalist.push(p.related);
        });
      });
      if (data.size == inf.length) {
        setChoo(true);
      } else {
        setChoo(false);
      }
      if (datalist.indexOf(true) == -1) {
        setIndeterminateAll(false);
      } else if (datalist.indexOf(false) == -1) {
        setIndeterminateAll(false);
      } else {
        setIndeterminateAll(true);
      }
      setIndeterminate(chooseData);
    }
  }, [info]);

  const submit = () => {
    if (nodeType === 1 || nodeType === 2) {
      let obj = form.getFieldsValue();
      submitCallback(obj);
    }
    if (nodeType === 3 || nodeType === 4) {
      let obj = otherForm.getFieldsValue();
      let data = [];
      plainOptions.map(item => {
        item.checkedList.forEach(i => {
          data.push(i);
        });
      });
      if (data.length > 0) {
        obj.relatedRoleList = data.toString();
      } else {
        obj.relatedRoleList = '';
      }
      submitCallback(obj);
    }
  };
  const onFinish = () => {
    submit();
  };
  // 添加功能路劲参数
  const addParama = () => {
    if (!otherForm.getFieldValue('pageUrl')) {
      notification.error({ message: '提示', duration: 3, description: '请先填写功能路径' });
      return;
    }
    setShowParmarModal(true);
  };

  // 全选复选框改变事件
  const checkAll = () => {
    let list = [];
    plainOptions.map(item => {
      list.push(item);
    });
    if (choo == false) {
      indeterminate.forEach((i, j) => {
        if (i == true) {
          indeterminate[j] = false;
        }
      });
      setChoo(true);
      list.map((item, index) => {
        item.isChecked = true;
        item.list.map(i => {
          i.related = true;
          list[index].checkedList.add(i.relatedRoleCode);
        });
      });
    } else {
      setChoo(false);
      list.map((item, index) => {
        item.isChecked = false;
        item.list.map(i => {
          i.related = false;
          list[index].checkedList.delete(i.relatedRoleCode);
        });
      });
    }
    setIndeterminateAll(false);
    setPlainOptions(list);
  };

  // 一级复选框改变事件
  const selectChange = (e, index, value) => {
    let list = [];
    plainOptions.map(item => {
      list.push(item);
    });
    list[index].isChecked = e.target.checked;
    if (e.target.checked) {
      checkList.add(list[index].groupName);
      list[index].list.map(i => {
        i.related = true;
        list[index].checkedList.add(i.relatedRoleCode);
      });
    } else {
      checkList.delete(list[index].groupName);
      list[index].list.map(i => {
        i.related = false;
        list[index].checkedList.delete(i.relatedRoleCode);
      });
    }
    const indeterminateArr = [...indeterminate];
    indeterminateArr[index] = false;
    setIndeterminate(indeterminateArr);
    let flag = [];
    let data = [];
    list.map(item => {
      if (item.isChecked == false) {
        flag.push(item);
      }
    });
    list.map((k, i) => {
      k.list.map(p => {
        data.push(p.related);
      });
    });
    if (data.indexOf(true) == -1) {
      setIndeterminateAll(false);
    } else if (data.indexOf(false) == -1) {
      setIndeterminateAll(false);
    } else {
      setIndeterminateAll(true);
    }
    if (flag.length > 0) {
      setChoo(false);
    } else {
      setChoo(true);
    }
    setPlainOptions(list);
  };

  // 二级复选框改变事件
  const handleChecked = (e, index, value, i) => {
    let list = [];
    plainOptions.map(item => {
      list.push(item);
    });
    list[index].list[i].related = e.target.checked;
    if (e.target.checked) {
      list[index].checkedList.add(list[index].list[i].relatedRoleCode);
    } else {
      list[index].checkedList.delete(list[index].list[i].relatedRoleCode);
    }
    const indeterminateArr = [...indeterminate];
    indeterminateArr[index] =
      !!list[index].checkedList.size && list[index].checkedList.size < list[index].list.length;
    setIndeterminate(indeterminateArr);
    if (
      list[index].checkedList.size == 0 ||
      list[index].checkedList.size < list[index].list.length
    ) {
      list[index].isChecked = false;
    }
    if (list[index].checkedList.size == list[index].list.length) {
      list[index].isChecked = true;
    }
    let flag = [];
    let data = [];
    list.map(item => {
      if (item.isChecked == false) {
        flag.push(item);
      }
    });
    list.map((k, i) => {
      k.list.map(p => {
        data.push(p.related);
      });
      // data.push(list[i].isChecked);
    });
    if (data.indexOf(true) == -1) {
      setIndeterminateAll(false);
    } else if (data.indexOf(false) == -1) {
      setIndeterminateAll(false);
    } else {
      setIndeterminateAll(true);
    }
    if (flag.length > 0) {
      setChoo(false);
    } else {
      setChoo(true);
    }
    setPlainOptions(list);
  };
  return (
    <div className={classnames({ [styles.divbox]: true })}>
      {(nodeType === 1 || nodeType === 2) && (
        <Form form={form} name="editGroup" onFinish={onFinish} {...layout}>
          <Item
            label="菜单组名称"
            name="menuName"
            rules={[
              {
                required: true,
                message: '请输入菜单组名称',
              },
            ]}
          >
            <Input placeholder="请输入菜单组名称" style={{ width: '100%' }} />
          </Item>
          <Item label="菜单组别名" name="shortName">
            <Input placeholder="请输入菜单组别名" style={{ width: '100%' }} />
          </Item>
          {nodeType === 1 && (
            <Item
              label="选中图标"
              name="imageUrl"
              rules={[
                {
                  required: true,
                  message: '请选择在线图标',
                },
              ]}
            >
              <PicturesWall picType="androidMenu" style={{ width: '100%' }} />
            </Item>
          )}
          {nodeType === 1 && (
            <Item
              label="未选中图标"
              name="offlineImgUrl"
              rules={[
                {
                  required: true,
                  message: '请选择离线图标',
                },
              ]}
            >
              <PicturesWall picType="androidMenu" style={{ width: '100%' }} />
            </Item>
          )}

          {nodeType === 2 && (
            <Item
              label="菜单组图标"
              name="imageUrl"
              rules={[
                {
                  required: true,
                  message: '请选择菜单组图标',
                },
              ]}
            >
              <PicturesWall picType="androidMenu" style={{ width: '100%' }} />
            </Item>
          )}
          <Item label="功能参数" name="funParam">
            <Input style={{ width: '100%' }} />
          </Item>
          <Item wrapperCol={{ offset: 10 }} style={{ marginTop: '40px' }}>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Item>
        </Form>
      )}

      {(nodeType === 3 || nodeType === 4) && (
        <Form form={otherForm} name="editMenu" onFinish={onFinish} {...layout}>
          <Item
            label="菜单名称"
            name="menuName"
            rules={[
              {
                required: true,
                message: '请输入菜单名称',
              },
            ]}
          >
            <Input style={{ width: '100%' }} />
          </Item>
          <Item label="菜单别名" name="shortName">
            <Input style={{ width: '100%' }} />
          </Item>
          {nodeType === 3 && (
            <Item
              label="选中图标"
              name="imageUrl"
              rules={[
                {
                  required: true,
                  message: '请选择在线图标',
                },
              ]}
            >
              <PicturesWall picType="androidMenu" style={{ width: '100%' }} />
            </Item>
          )}
          {nodeType === 3 && (
            <Item
              label="未选中图标"
              name="offlineImgUrl"
              rules={[
                {
                  required: true,
                  message: '请选择离线图标',
                },
              ]}
            >
              <PicturesWall picType="androidMenu" style={{ width: '100%' }} />
            </Item>
          )}
          {nodeType === 4 && (
            <Item
              label="菜单图标"
              name="imageUrl"
              rules={[
                {
                  required: true,
                  message: '请选择菜单图标',
                },
              ]}
            >
              <PicturesWall picType="androidMenu" style={{ width: '100%' }} />
            </Item>
          )}
          <Item
            name="pageUrl"
            label="功能路径"
            rules={[
              {
                required: true,
                message: '请输入功能路径',
              },
            ]}
          >
            <div style={{ display: 'flex' }}>
              <Item name="pageUrl" style={{ marginBottom: 0, width: '100%' }}>
                <Input placeholder="请输入功能路径" style={{ width: '100%' }} />
              </Item>
              <Button onClick={addParama}>参数管理</Button>
            </div>
          </Item>
          <Item label="功能参数" name="funParam">
            <Input style={{ width: '100%' }} />
          </Item>
          {/* <CheckList
            info={info.data ? info.data : {}}
            nodeType={nodeType}
            valueCallback={valueCallback}
            style={{ width: '100%' }}
          /> */}
          <div className={styles.boe}>
            <div
              style={{ width: '95%', marginLeft: '2%', marginTop: '10px', marginBottom: '20px' }}
            >
              <div style={{ marginTop: '-23px', backgroundColor: 'white', width: '92px' }}>
                <Checkbox
                  onChange={checkAll}
                  checked={choo}
                  nodeType={nodeType}
                  indeterminate={indeterminateAll}
                >
                  <span style={{ fontWeight: 'bold', fontSize: '15px' }}>关联角色</span>
                </Checkbox>
              </div>
              {plainOptions && plainOptions.length > 0 ? (
                plainOptions.map((item, index) => (
                  <div
                    className={classnames({
                      [styles.divBox]: item.groupName.length > 0,
                    })}
                  >
                    <div style={{ marginTop: '-12px' }}>
                      {item.groupName.length == 0 ? (
                        <span style={{ marginLeft: '15px', marginTop: '0px' }} />
                      ) : (
                        <Checkbox
                          onChange={e => {
                            selectChange(e, index, item);
                          }}
                          checked={item.isChecked}
                          indeterminate={indeterminate[index]}
                        >
                          <span style={{ fontWeight: 'bold', fontSize: '15px' }}>
                            {item.groupName}
                          </span>
                        </Checkbox>
                      )}
                    </div>
                    <div style={{ marginLeft: '0px', marginTop: '5px' }}>
                      {item.groupName.length == 0 ? (
                        <>
                          <Row>
                            {item.list.map((val, i) => (
                              <Col span={4} style={{ marginBottom: '10px' }}>
                                <Checkbox
                                  onChange={e => {
                                    handleChecked(e, index, item, i);
                                  }}
                                  checked={val.related}
                                >
                                  {val.relatedRoleName}
                                </Checkbox>
                              </Col>
                            ))}
                          </Row>
                        </>
                      ) : (
                        <>
                          <Row>
                            {item.list.map((val, i) => (
                              <Col span={4}>
                                <Checkbox
                                  onChange={e => {
                                    handleChecked(e, index, item, i);
                                  }}
                                  checked={val.related}
                                >
                                  {val.relatedRoleName}
                                </Checkbox>
                              </Col>
                            ))}
                          </Row>
                        </>
                      )}
                    </div>
                  </div>
                ))
              ) : (
                <span />
              )}
            </div>
          </div>

          <Item wrapperCol={{ offset: 10 }}>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Item>
        </Form>
      )}
      <ParmarModal
        pageUrl={otherForm.getFieldValue('pageUrl')}
        handleCancel={() => setShowParmarModal(false)}
        visible={showParmarModal}
        parmarCallBack={url => {
          otherForm.setFieldsValue({ pageUrl: url });
          setShowParmarModal(false);
        }}
      />
    </div>
  );
};
export default EditForm;
