import React, {useEffect, useState} from 'react';
import {FormComponentProps} from 'antd/lib/form';
import Form from 'antd/es/form';
import {
  Avatar,
  Button,
  Card,
  Cascader,
  Col,
  Icon,
  Input,
  message,
  Radio,
  Row,
  Select,
  Spin,
  Tooltip,
  TreeSelect,
  Upload,
} from 'antd';
import {MetaDataCommon} from '../../data';
import {FormItemConfig} from '@/utils/common';
import apis from '@/services';
import styles from '@/pages/device/product/save/add/index.less';
import {PageHeaderWrapper} from '@ant-design/pro-layout';
import Classified from '@/pages/device/product/save/add/classified';
import {router} from 'umi';
import encodeQueryParam from "@/utils/encodeParam";
import AceEditor from "react-ace";

interface Props extends FormComponentProps {
  data?: Partial<MetaDataCommon>;
  close: Function;
  save: (data: Partial<MetaDataCommon>) => void;
}

interface State {
  configForm: any[];
  configName: string;
  classified: any[];
  classifiedData: any;
  defaultMetadata: string;
}

const Save: React.FC<Props> = props => {
  const initState: State = {
    configName: '',
    configForm: [],
    classified: [],
    classifiedData: {},
    defaultMetadata: '{"events":[],"properties":[],"functions":[],"tags":[]}',
  };
  const systemVersion = localStorage.getItem('system-version');

  const {getFieldDecorator, setFieldsValue} = props.form;
  const [classified, setClassified] = useState(initState.classified);
  const [classifiedData, setClassifiedData] = useState(initState.classifiedData);

  //默认物模型
  const [defaultMetadata, setDefaultMetadata] = useState(initState.defaultMetadata);

  const [classifiedVisible, setClassifiedVisible] = useState(false);

  useEffect(() => {

    apis.deviceProdcutCommon
      .deviceCategoryTree(encodeQueryParam({paging: false, sorts: {field: 'id', order: 'desc'}}))
      .then((response: any) => {
        if (response.status === 200) {
          setClassified(response.result);
        }
      })
      .catch(() => {
      });

      setDefaultMetadata('{"events":[],"properties":[],"functions":[],"tags":[]}')
  }, []);

  const basicForm: FormItemConfig[] = [
    {
      label: '物模型ID',
      key: 'id',
      styles: {
        lg: {span: 8},
        md: {span: 12},
        sm: {span: 24},
      },
      options: {
        initialValue: props.data?.id,
        rules: [
          {required: true, message: '请输入物模型ID'},
          {max: 64, message: '物模型ID不超过64个字符'},
          {
            pattern: new RegExp(/^[0-9a-zA-Z_\-]+$/, 'g'),
            message: '物模型ID只能由数字、字母、下划线、中划线组成',
          },
        ],
      },
      component: <Input placeholder="请输入物模型ID " disabled={!!props.data?.id}/>,
    },
    {
      label: '物模型名称',
      key: 'name',
      options: {
        rules: [
          {required: true, message: '请输入物模型名称'},
          {max: 200, message: '物模型名称不超过200个字符'},
        ],
        initialValue: props.data?.name,
      },
      styles: {
        xl: {span: 8},
        lg: {span: 8},
        md: {span: 12},
        sm: {span: 24},
      },
      component: <Input style={{width: '100%'}} maxLength={200} placeholder="请输入"/>,
    },
    {
      label: '所属品类',
      key: 'classifiedId',
      options: {
        rules: [{required: true, message: '请选择所属品类'}],
      },
      styles: {
        xl: {span: 8},
        lg: {span: 8},
        md: {span: 12},
        sm: {span: 24},
      },
      component: (
        <Cascader
          fieldNames={{label: 'name', value: 'id', children: 'children'}}
          options={classified}
          popupVisible={false}
          onChange={value => {
            if (value.length === 0) {
              setClassifiedData({});
            }
          }}
          onClick={() => {
            setClassifiedVisible(true);
          }}
          placeholder="点击选择品类"
        />
      ),
    },
    // {
    //   label: '物模型',
    //   key: 'metadata',
    //   options: {
    //     rules: [{required: true, message: '请输入物模型'}],
    //     initialValue: defaultMetadata ,
    //   },
    //   component: (
    //     <AceEditor
    //           mode='json'
    //           theme="eclipse"
    //           name="app_code_editor"
    //           fontSize={14}
    //           // value={defaultMetadata}
    //           // onChange={value => {
    //           //   setDefaultMetadata(value);
    //           // }}
    //           showPrintMargin
    //           showGutter
    //           wrapEnabled
    //           highlightActiveLine  //突出活动线
    //           enableSnippets  //启用代码段
    //           style={{ width: '100%', height: 400 }}
    //           setOptions={{
    //             enableBasicAutocompletion: true,   //启用基本自动完成功能
    //             enableLiveAutocompletion: true,   //启用实时自动完成功能 （比如：智能代码提示）
    //             enableSnippets: true,  //启用代码段
    //             showLineNumbers: true,
    //             tabSize: 2,
    //           }}
    //         />
    //   )
    // }
  ];

  const saveData = () => {
    const {form} = props;
    form.validateFields((err, fileValue) => {
      if (err) return;

      apis.metadataCommon
        .saveMetaDataCommon({
          ...fileValue,
          classifiedId: classifiedData.id,
          classifiedName: classifiedData.name,
          metadata: defaultMetadata
        })
        .then((response: any) => {
          if (response.status === 200) {
            message.success('保存成功');
            router.push(`/device/metadata/save/${response.result.id}`);
          }
        })
        .catch(() => {
        });
    });
  };

  return (
    <PageHeaderWrapper>
      <Card title="基本信息" bordered={false}>
        <div className={styles.right}>
          <Spin spinning={false}>
            <div className={styles.baseView}>
              <div className={styles.left}>
                <Form labelCol={{span: 5}} wrapperCol={{span: 16}}>
                  <Row gutter={16}>
                    {basicForm.map(item => (
                      <Col key={item.key}>
                        <Form.Item label={item.label}>
                          {getFieldDecorator(item.key, item.options)(item.component)}
                        </Form.Item>
                      </Col>
                    ))}
                    {/* {(systemVersion === 'pro' ? basicForm : basicForm.filter(i => i.key !== 'storePolicy')).map(item => (
                      <Col key={item.key}>
                        <Form.Item label={item.label}>
                          {getFieldDecorator(item.key, item.options)(item.component)}
                        </Form.Item>
                      </Col>
                    ))} */}
                  </Row>
                </Form>
              </div>
            </div>
            <div
              style={{
                position: 'absolute',
                right: 0,
                bottom: 0,
                height: 32,
                lineHeight: 4,
                width: '100%',
                borderTop: '1px solid #e9e9e9',
                paddingRight: 16,
                background: '#fff',
                textAlign: 'right',
              }}
            >
              <Button
                onClick={() => {
                  router.push(`/device/metadata`);
                }}
                style={{marginRight: 8}}
              >
                返回
              </Button>
              <Button
                onClick={() => {
                  saveData();
                }}
                type="primary"
              >
                保存
              </Button>
            </div>
          </Spin>
        </div>
      </Card>
      {classifiedVisible && (
        <Classified
          choice={(item: any) => {
            const categoryId = item.categoryId;
            setFieldsValue({classifiedId: categoryId});
            setClassifiedData(item);
            setClassifiedVisible(false);
          }}
          close={() => {
            setClassifiedVisible(false);
          }}
          data={classifiedData}
        />
      )}
    </PageHeaderWrapper>
  );
};

export default Form.create<Props>()(Save);
