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

import { createTable, loadTableFields, addFields } from '@/services/tablemanager/tablemanager';

import styles from './index.less';
const { Option } = Select;
const CheckboxGroup = Checkbox.Group;
const editor = props => {
  const { callBackSubmit = () => {}, type, visible } = props;
  const [reminder, setReminder] = useState(
    ' 事件表会默认创建如下字段：事件编号、事件状态、事件名称上报站点、处理站点、上报人名称、上报人部分、上报时间、现场图片、现场录音、坐标位置、更新时间、更新状态、是否置顶',
  );
  const [loading, setLoading] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();
  const { Item } = Form;
  const [checkedList, setCheckedList] = useState([]); // 选中的复选框内容
  const [plainOptions, setPlainOptions] = useState([]); // 复选框所有内容
  const [indeterminate, setIndeterminate] = useState(true);
  const [isVisible, setIsVisible] = useState(true);
  const [checkAll, setCheckAll] = useState(false);
  const [chartName, setChartName] = useState(''); // 附加表名称

  const onChange = list => {
    setCheckedList(list);
    setIndeterminate(!!list.length && list.length < plainOptions.length);
    setCheckAll(list.length === plainOptions.length);
  };

  const onCheckAllChange = e => {
    setCheckedList(e.target.checked ? plainOptions : []);
    setIndeterminate(false);
    setCheckAll(e.target.checked);
  };

  // 提交
  const onSubmit = () => {
    form.validateFields().then(validate => {
      if (validate) {
        setLoading(true);
        let obj = form.getFieldsValue();
        obj.tableName = `${obj.tableType.substr(0, obj.tableType.length - 1)}_${obj.tableName}`;
        createTable({
          ...obj,
        })
          .then(res => {
            setLoading(false);
            if (res.msg === 'Ok') {
              notification.success({
                message: '提示',
                duration: 1,
                description: '建表成功',
              });
              setIsVisible(false);
              setChartName(res.data.tableInfo.Name);
              loadTableFields({ tableName: res.data.tableInfo.Name }).then(response => {
                if (response.data.root.length) {
                  let arr = [];
                  let newArr = [];
                  response.data.root.map(item => {
                    newArr.push(item.fieldName);
                    if (item.isCheck) {
                      arr.push(item.fieldName);
                    }
                  });
                  setPlainOptions(newArr);
                  setCheckedList(arr);
                }
                setIsModalVisible(true);
              });
            } else {
              form.resetFields();
              callBackSubmit();
              notification.error({
                message: '提示',
                duration: 3,
                description: res.msg,
              });
            }
          })
          .catch(err => {
            console.log('err', err);
            notification.error({
              message: '提示',
              duration: 3,
              description: '新增失败',
            });
            setLoading(false);
          });
      }
    });
  };
  useEffect(() => {
    if (type != '') {
      form.setFieldsValue({ tableType: '事件表' });
    }
  }, [visible]);
  const handleOk = () => {
    if (chartName != '') {
      addFields({
        tableName: chartName,
        fieldNames: checkedList.join(','),
      })
        .then(res => {
          if (res.msg === 'Ok' || res.msg === '') {
            notification.success({
              message: '提示',
              duration: 1,
              description: '附加字段添加成功',
            });
            setIsModalVisible(false);
            form.resetFields();
            callBackSubmit();
          } else {
            notification.error({
              message: '提示',
              duration: 3,
              description: res.msg,
            });
          }
        })
        .catch(err => {
          console.log('err', err);
        });
    } else {
      notification.success({
        message: '提示',
        duration: 1,
        description: '表名称没添加',
      });
    }
  };
  const handleCancel = () => {
    setIsModalVisible(false);
  };
  const changeChart = value => {
    let str = '';
    switch (value) {
      case '事件表':
        str =
          ' 事件表默认创建如下字段：事件编号、事件状态、事件名称、上报站点、处理站点、上报人名称、上报人部分、上报时间、现场图片、现场录音、坐标位置、更新时间、更新状态、是否置顶';
        break;
      case '工单表':
        str = '工单表默认创建如下字段：工单编号';
        break;
      case '台账表':
        str = '台账表默认创建如下字段：所属站点、录入时间、是否删除';
        break;
      case '设备表':
        str =
          '设备表默认创建如下字段：编码、父设备编码、GIS编号、设备名称、所属站点、坐标位置、风貌图、视频缩略图、第三方编码、录入时间、是否删除';
        break;
      case '反馈表':
        str = '反馈表默认创建如下字段：编码、设备编码、录入时间、是否删除';
        break;
      default:
        str =
          ' 事件表默认创建如下字段：事件编号、事件状态、事件名称、上报站点、处理站点、上报人名称、上报人部分、上报时间、现场图片、现场录音、坐标位置、更新时间、更新状态、是否置顶';
    }
    setReminder(str);
  };
  const layout = {
    layout: 'horizontal',
    labelCol: {
      span: 4,
    },
    wrapperCol: {
      span: 19,
    },
  };

  return (
    <>
      <Modal
        title="建表"
        bodyStyle={{ width: '100%', minHeight: '100px' }}
        style={{ top: '150px' }}
        width="700px"
        destroyOnClose
        maskClosable={false}
        cancelText="取消"
        okText="确认"
        visible={isVisible}
        {...props}
        onOk={() => onSubmit()}
        confirmLoading={loading}
        forceRender
        getContainer={false}
      >
        <Form form={form} {...layout}>
          <Item label="【特别提示】">
            <span>
              此处仅建立基础表和必要字段，额外字段需通过其他方式进行添加，比如使用Navicat工具等。
            </span>
          </Item>
          <Item
            label="建表类型"
            name="tableType"
            rules={[{ required: true, message: '请输入表名' }]}
          >
            <Select onChange={changeChart}>
              <Select.Option value="事件表">事件表</Select.Option>
              <Select.Option value="工单表">工单表</Select.Option>
              <Select.Option value="台账表">台账表</Select.Option>
              <Select.Option value="设备表">设备表</Select.Option>
              <Select.Option value="反馈表">反馈表</Select.Option>
            </Select>
          </Item>
          <Item
            label="表名"
            name="tableName"
            rules={[{ required: true, message: '请以"模块_表名"的个数输入' }]}
          >
            <Input placeholder='请以"模块_表名"的个数输入' allowClear />
          </Item>
          <Item label="别名" name="alias">
            <Input placeholder="请输入别名,通常用作该表的备注" allowClear />
          </Item>
          <Item label=" " colon={false}>
            <span> ●{reminder}</span>
          </Item>
        </Form>
      </Modal>
      <Modal title="附加字段" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
        <Checkbox indeterminate={indeterminate} onChange={onCheckAllChange} checked={checkAll}>
          选择所有
        </Checkbox>
        <Divider />
        <div className={styles.field}>
          <Row>
            {plainOptions.length ? (
              <CheckboxGroup options={plainOptions} value={checkedList} onChange={onChange} />
            ) : (
              ''
            )}
          </Row>
        </div>
      </Modal>
    </>
  );
};
export default editor;
