import React, { useState, useEffect } from 'react';
import { Form, Modal, Input, Select, Checkbox, notification, Card } from 'antd';

import { loadTableFields, addTables, addFields } from '@/services/tablemanager/tablemanager';
import styles from './index.less';
const CheckboxGroup = Checkbox.Group;
const { Option } = Select;
const AddModal = props => {
  const { callBackSubmit = () => {}, type, visible, tableList, formObj } = props;
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const { Item } = Form;
  const [plainOptions, setPlainOptions] = useState([]); // 复选框所有内容
  const [plainOptionsInside, setPlainOptionsInside] = useState([]); // 复选框所有内容
  const [checkedList, setCheckedList] = useState([]); // 选中的复选框内容
  const [indeterminate, setIndeterminate] = useState(true);
  const [checkAll, setCheckAll] = useState(false);
  const [indeterminate1, setIndeterminate1] = useState(false); // 内置分组
  const [checkAll1, setCheckAll1] = useState(false); // 内置分组

  const onChange = list => {
    setCheckedList(list);
    let data = [];
    if (plainOptionsInside.length > 0) {
      plainOptionsInside.map(i => {
        if (i.isCheck) {
          data.push(i);
        }
      });
    }

    let aa = data.length + list.length;
    let bb = plainOptionsInside.length + plainOptions.length;
    setIndeterminate(!!aa && aa < bb);
    setCheckAll(aa == bb);
  };

  const onCheckAllChange = e => {
    setCheckedList(e.target.checked ? plainOptions : []);
    setIndeterminate(false);
    setCheckAll(e.target.checked);
    let data = [...plainOptionsInside];
    data.map(i => {
      i.isCheck = e.target.checked;
    });
    setPlainOptionsInside(data);
    setIndeterminate1(false);
    setCheckAll1(e.target.checked);
  };

  const onCheckAllChange1 = e => {
    let data = [...plainOptionsInside];
    data.map(i => {
      i.isCheck = e.target.checked;
    });
    let list = [];
    data.map(j => {
      if (j.isCheck) {
        list.push(j);
      }
    });
    setPlainOptionsInside(data);
    setIndeterminate1(false);
    setCheckAll1(e.target.checked);
    let aa = list.length + checkedList.length;
    let bb = plainOptionsInside.length + plainOptions.length;
    setCheckAll(aa == bb);
    setIndeterminate(!!aa && aa < bb);
  };
  // 提交
  const onSubmit = () => {
    let fieldNames = [];
    (checkedList || []).map(item => {
      fieldNames.push({ fieldNames: item });
    });
    let list = [];
    if (plainOptionsInside.length > 0) {
      plainOptionsInside.map(i => {
        if (i.isCheck) {
          list.push(i.fieldName);
        }
      });
    }
    let datalist = checkedList.concat(list);
    form.validateFields().then(validate => {
      if (validate) {
        let obj = form.getFieldsValue();
        setLoading(true);
        let data = {};
        let url = JSON.stringify(formObj) == '{}' ? addTables : addFields;
        if (JSON.stringify(formObj) == '{}') {
          data = {
            tableName: obj.tableName,
            alias: obj.tableAlias || '',
            fieldNames: datalist.join(','),
          };
        } else {
          data = { tableName: formObj.tableName, fieldNames: datalist.join(',') };
        }
        url(data)
          .then(res => {
            setLoading(false);
            if (res.msg === 'Ok' || res.msg === '') {
              form.resetFields();
              callBackSubmit();
              notification.success({
                message: '提示',
                duration: 3,
                description: JSON.stringify(formObj) == '{}' ? '新增成功' : '表字段新增成功',
              });
            } else {
              notification.error({
                message: '提示',
                duration: 3,
                description: res.msg,
              });
            }
          })
          .catch(err => {
            notification.error({
              message: '提示',
              duration: 3,
              description: '新增失败',
            });
            setLoading(false);
          });
      }
    });
  };

  useEffect(() => {
    if (type != '' && JSON.stringify(formObj) == '{}') {
      renderField(tableList[0].text);
      form.setFieldsValue({
        tableName: tableList[0].text,
      });
    } else if (type != '' && JSON.stringify(formObj) != '{}') {
      renderField(formObj.tableName);
    }
  }, [visible]);

  const renderField = name => {
    loadTableFields({ tableName: name }).then(response => {
      if (response.data.root.length) {
        // eslint-disable-next-line one-var
        let arr = [];
        let newArr = [];
        let insideArr = [];
        response.data.root.map(item => {
          if (item.isDefaultField == true) {
            insideArr.push({ fieldName: item.fieldName, isCheck: item.isCheck });
          } else {
            newArr.push(item.fieldName);
            if (item.isCheck) {
              arr.push(item.fieldName);
            }
          }
        });
        let list = [];
        if (insideArr.length > 0) {
          insideArr.map(i => {
            if (i.isCheck) {
              list.push(i);
            }
          });
          setCheckAll1(list.length === insideArr.length);
          setIndeterminate1(!!list.length && list.length < insideArr.length);
        }

        let aa = arr.length + list.length;
        let bb = newArr.length + insideArr.length;
        setCheckAll(aa == bb);
        setIndeterminate(!!aa && aa < bb);
        setPlainOptions(newArr);
        setPlainOptionsInside(insideArr);
        setCheckedList(arr);
      } else {
        setCheckAll(false);
        setIndeterminate(false);
      }
    });
  };
  const layout = {
    layout: 'horizontal',
    labelCol: {
      span: 3,
    },
    wrapperCol: {
      span: 20,
    },
  };

  const handleChange = value => {
    renderField(value);
  };

  const onchenge = (e, item) => {
    let data = [...plainOptionsInside];
    data.map(i => {
      if (i.fieldName == item) {
        i.isCheck = e.target.checked;
      }
    });
    setPlainOptionsInside(data);
    let list = [];
    data.map(j => {
      if (j.isCheck) {
        list.push(j);
      }
    });
    setIndeterminate1(!!list.length && list.length < plainOptionsInside.length);
    setCheckAll1(list.length === plainOptionsInside.length);
    let aa = list.length + checkedList.length;
    let bb = plainOptionsInside.length + plainOptions.length;
    setIndeterminate(!!aa && aa < bb);
    setCheckAll(aa == bb);
  };

  return (
    <Modal
      title={JSON.stringify(formObj) == '{}' ? '附加表' : '附加字段'}
      bodyStyle={{ width: '100%', minHeight: '200px' }}
      style={{ top: '150px' }}
      width="700px"
      destroyOnClose
      maskClosable={false}
      cancelText="取消"
      okText="确认"
      {...props}
      onOk={() => onSubmit()}
      confirmLoading={loading}
      forceRender
      getContainer={false}
    >
      {visible && (
        <Form form={form} {...layout} style={{ marginBottom: '30px' }}>
          {JSON.stringify(formObj) == '{}' ? (
            <>
              <Item
                label="表名"
                name="tableName"
                rules={[{ required: true, message: '请选择表名' }]}
              >
                <Select onChange={handleChange} showSearch>
                  {tableList.length
                    ? tableList.map((item, index) => (
                        <Select.Option key={index} value={item.text}>
                          {item.text}
                        </Select.Option>
                      ))
                    : ''}
                </Select>
              </Item>
              <Item label="别名" name="tableAlias">
                <Input allowClear />
              </Item>
            </>
          ) : (
            <div className={styles.paneTitle}>{formObj.tableName}</div>
          )}
          <div className={styles.field}>
            <Card
              title="字段名"
              extra={
                <Checkbox
                  indeterminate={indeterminate}
                  onChange={onCheckAllChange}
                  checked={checkAll}
                >
                  {' '}
                </Checkbox>
              }
            >
              {plainOptions.length > 0 && (
                <CheckboxGroup options={plainOptions} value={checkedList} onChange={onChange} />
              )}
              {plainOptionsInside.length > 0 ? (
                <>
                  <div
                    style={{
                      position: 'relative',
                      top: '12px',
                      marginLeft: '16px',
                      backgroundColor: 'white',
                      width: '100px',
                      paddingLeft: '5px',
                    }}
                  >
                    <Checkbox
                      style={{ color: 'red' }}
                      indeterminate={indeterminate1}
                      onChange={onCheckAllChange1}
                      checked={checkAll1}
                    >
                      <strong>内置字段</strong>
                    </Checkbox>
                  </div>
                  <div
                    style={{
                      display: 'flex',
                      flexWrap: 'wrap',
                      border: '1px solid #d7d3d3',
                      borderRadius: '2px',
                      paddingTop: '20px',
                    }}
                  >
                    {plainOptionsInside.map(i => (
                      <div
                        style={{
                          width: '110px',
                          overflow: 'hidden',
                          paddingBottom: '10px',
                          marginLeft: '20px',
                          textOverflow: 'ellipsis',
                          whiteSpace: 'nowrap',
                        }}
                      >
                        <Checkbox
                          style={{ color: 'red' }}
                          checked={i.isCheck}
                          onChange={e => {
                            onchenge(e, i.fieldName);
                          }}
                        >
                          {i.fieldName}
                        </Checkbox>
                      </div>
                    ))}
                  </div>
                </>
              ) : (
                <></>
              )}
            </Card>
          </div>
        </Form>
      )}
    </Modal>
  );
};
export default AddModal;
