import React, { useState, useEffect, useRef } from 'react';
import {
  Form,
  Input,
  Button,
  Row,
  Col,
  Select,
  Radio,
  Checkbox,
  checkedValue,
  message,
  notification,
  Switch,
  AutoComplete,
  Empty,
} from 'antd';
import {
  MinusCircleOutlined,
  PlusOutlined,
  DesktopOutlined,
  FolderFilled,
  FileOutlined,
} from '@ant-design/icons';
import { GetWebMenuInfo, getConfigContent } from '@/services/webConfig/api';

import classnames from 'classnames';
import styles from './addForm.less';
import PicturesWall from '@/components/Upload/index';
import EditeConfigWrapper from './editConfigFileWrapper';
import CheckList from './checkBox';
import ParmarModal from './ParmarModal';
import ParmarsModal from './ParmarsModal';
import TreeSelect from './TreeSelect';
// const { TreeNode } = TreeSelect;

const { Item } = Form;
const { Option } = Select;
const EditForm = props => {
  const {
    submitCallback,
    nodeType,
    info,
    infoAll,
    checkList,
    configFiles,
    valueCallback = () => {},
    productList,
    allProductList,
  } = props;
  const [form] = Form.useForm();
  const [otherForm] = Form.useForm();
  const [showParmarModal, setShowParmarModal] = useState(false);
  const [plainOptions, setPlainOptions] = useState([]); // 存储一级数据
  const [indeterminate, setIndeterminate] = useState([]);
  const [indeterminateAll, setIndeterminateAll] = useState(false);
  const [choo, setChoo] = useState(false); // 最外层复选框状态
  const [visibleChecked, setVisibleChecked] = useState(false);

  const [menuParmar, setMenuParmar] = useState([]);
  const [codeParmar, setCodeParmar] = useState([]);
  const [curretnMenu, setCurrentMenu] = useState({}); // 当前选中菜单数据
  const [configContent, setConfigContent] = useState(''); // 配置文件内容
  const treeSelectRef = useRef();
  const layout = {
    layout: 'horizontal',
    labelCol: { span: 2 },
    wrapperCol: { span: 21 },
  };

  // 回显表单
  useEffect(() => {
    console.log(info, 'info');
    console.log(infoAll, 'infoalll');
    if (!infoAll.code) {
      setMenuParmar([]);
    }
    setCodeParmar(infoAll.codeParam ? JSON.parse(infoAll.codeParam) : []);
    setConfigContent(infoAll.configContent);
    setCurrentMenu({});
    form.resetFields();
    otherForm.resetFields();
    setPlainOptions(info);
  }, [infoAll]);
  useEffect(() => {
    const targetForm = nodeType === 1 ? form : otherForm;
    let arr = Object.keys(targetForm.getFieldsValue());
    let obj = {};
    arr.map(i => {
      obj[i] = infoAll[i];
    });

    setVisibleChecked(infoAll.hideInMenu);
    targetForm.setFieldsValue({ ...obj, shortName: infoAll.menuShortName });
    if (info.length > 0) {
      let list = [];
      info.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 = [];
      info.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 == info.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);
    }
  }, [infoAll]);

  const submit = () => {
    const targetForm = nodeType === 1 ? form : otherForm;
    let obj = targetForm.getFieldsValue();

    let data = [];
    if (nodeType == 1) {
      plainOptions.map(item => {
        item.checkedList.forEach(i => {
          data.push(i);
        });
      });
      if (data.length > 0) {
        obj.relatedRoleList = data.toString();
      } else {
        obj.relatedRoleList = '';
      }

      let arr = obj.pageUrl.split('/'); // 用const声明常量
      if (!arr[0]) {
        arr.shift();
      }
      let allProList = JSON.parse(JSON.stringify(allProductList));
      allProList.push({ PackageName: 'civ_base' });
      const product = allProList.find(item => item.PackageName === arr[0]);
      console.log(product, 'product');
      if (product) {
        arr.shift();
        obj.pageUrl = arr.join('/');
      }

      obj.product = product?.PackageName || 'civweb4';
      console.log(productList, 'productList');
      let proList = JSON.parse(JSON.stringify(productList));
      proList.push({ PackageName: 'civ_base' });

      if (!proList.some(item => item.PackageName === obj.product) && obj.product !== 'civweb4') {
        message.error(`${obj.product}未授权，不能使用该功能`);
        return;
      }
    }
    obj.codeParam = JSON.stringify(curretnMenu.param);
    obj.code = curretnMenu.code;
    obj.configContent = configContent;
    submitCallback(obj);
  };

  const onFinish = () => {
    submit();
  };
  // 添加功能路劲参数
  const addParama = () => {
    if (!form.getFieldValue('pageUrl')) {
      notification.error({ message: '提示', duration: 3, description: '请先填写功能路径' });
      return;
    }
    setShowParmarModal(true);
  };
  const radioChange = e => {};
  // 一级复选框改变事件
  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);
  };
  // 全选复选框改变事件
  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 change = e => {
    setVisibleChecked(e);
  };

  const menuChange = val => {
    if (!val) {
      return;
    }

    setCodeParmar([]);
    // form.resetFields();
    console.log(form, 'form');
    form.setFieldsValue({
      menuName: val?.function,
      shortName: val?.shortName,
      imageUrl: val?.icon,
      configName: val?.configName,
      pageUrl: val?.pageUrl,
    });
    setConfigContent(val.configContent);
    setCurrentMenu(val);
    setMenuParmar(val?.param);
  };
  // 编辑完配置文件后回调
  const wrapperFinish = val => {
    setConfigContent(val);
  };
  // 选择配置文件获取到配置文件内容
  const selectConfig = val => {
    console.log(val);
    getConfigContent(val)
      .then(res => {
        if (res.code === 0) {
          setConfigContent(res.data);
        }
      })
      .catch(e => {
        console.error(e);
      });
  };
  return (
    <div style={{ marginTop: '10px' }}>
      {nodeType === 1 && (
        <Form form={form} name="editGroup" onFinish={onFinish}>
          <Item
            label="菜单名称"
            name="menuName"
            rules={[
              {
                required: true,
                message: '请输入菜单名称',
              },
            ]}
          >
            <Input placeholder="请输入菜单名称" style={{ width: '100%' }} />
          </Item>
          <Item label="菜单别名" name="shortName" style={{ marginLeft: '11px' }}>
            <Input placeholder="请输入菜单别名" style={{ width: '100%' }} />
          </Item>
          {/* <Item label="产品类型" name="product" style={{ marginLeft: '11px' }}>
            <Select placeholder="请选择产品类型" allowClear style={{ width: '100%' }}>
              {productList &&
                productList.length > 0 &&
                productList.map(item => (
                  <Option value={item.PackageName} key={item.PackageName}>
                    {`${item.ProductName}（${item.PackageName}）`}
                  </Option>
                ))}
            </Select>
          </Item> */}
          <Item
            label="菜单图标"
            name="imageUrl"
            rules={[
              {
                required: true,
                message: '请选择菜单图标',
              },
            ]}
          >
            <PicturesWall picType="menuNew" />
          </Item>
          <Item
            label="菜单隐藏"
            name="hideInMenu"
            initialValue={false}
            style={{ marginLeft: '11px' }}
          >
            <Switch
              checkedChildren="是"
              unCheckedChildren="否"
              checked={visibleChecked}
              onChange={change}
            />
            {/* <Radio.Group onChange={radioChange}>
              <Radio value={false}>否</Radio>
              <Radio value>是</Radio>
            </Radio.Group> */}
          </Item>
          <Item
            name="pageUrl"
            label="功能路径"
            rules={[
              {
                required: true,
                message: '请输入功能路径',
              },
            ]}
          >
            <div style={{ display: 'flex' }}>
              <Item name="pageUrl" style={{ marginBottom: 0, width: '100%' }}>
                <TreeSelect
                  ref={treeSelectRef}
                  menuChange={val => menuChange(val)}
                  code={infoAll?.code}
                  codeParam={infoAll?.codeParam}
                  initCurrentMenu={value => {
                    console.log(value, 'value');
                    setCurrentMenu(value);
                    setMenuParmar(value.param);
                  }}
                />
              </Item>
              <Button onClick={addParama}>参数管理</Button>
            </div>
          </Item>
          <Item label="配置文件" name="configName" style={{ marginLeft: '11px' }}>
            <EditeConfigWrapper
              id={infoAll.menuID}
              configContent={configContent}
              onFinish={wrapperFinish}
            >
              <Select
                allowClear
                showSearch
                onSelect={selectConfig}
                filterOption={(input, option) =>
                  option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }
              >
                {configFiles.map(c => (
                  <Select.Option key={c.text} value={c.value} style={{ width: '100%' }}>
                    {c.text}
                  </Select.Option>
                ))}
              </Select>
            </EditeConfigWrapper>
          </Item>
          <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 }} style={{ marginTop: '20px' }}>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Item>
        </Form>
      )}

      {nodeType === 2 && (
        <Form form={otherForm} name="editMenu" onFinish={onFinish}>
          <Item
            label="菜单组名称"
            name="menuName"
            rules={[
              {
                required: true,
                message: '请输入菜单组名称',
              },
            ]}
          >
            <Input style={{ width: '100%' }} />
          </Item>
          <Item label="菜单组别名" name="shortName" style={{ marginLeft: '11px' }}>
            <Input placeholder="请输入菜单组别名" style={{ width: '100%' }} />
          </Item>
          <Item
            label="菜单组图标"
            name="imageUrl"
            rules={[
              {
                required: true,
                message: '请选择菜单组图标',
              },
            ]}
          >
            <PicturesWall picType="menuNew" />
          </Item>
          <Item style={{ marginTop: '40px', marginLeft: '45%' }}>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Item>
        </Form>
      )}
      {/* <ParmarModal
        pageUrl={form.getFieldValue('pageUrl')}
        handleCancel={() => setShowParmarModal(false)}
        visible={showParmarModal}
        parmarCallBack={url => {
          form.setFieldsValue({ pageUrl: url });
          setShowParmarModal(false);
        }}
      /> */}
      <ParmarsModal
        menuParmar={menuParmar}
        codeParam={codeParmar}
        pageUrl={form.getFieldValue('pageUrl')}
        handleCancel={() => setShowParmarModal(false)}
        visible={showParmarModal}
        parmarCallBack={(url, params) => {
          form.setFieldsValue({ pageUrl: url });
          setCurrentMenu({ ...curretnMenu, param: params });
          setCodeParmar(params);
          setShowParmarModal(false);
        }}
      />
    </div>
  );
};
export default EditForm;
