import React, {useEffect, useState} from 'react';
import {FormComponentProps} from 'antd/lib/form';
import Form from 'antd/es/form';
import {
  Button,
  Cascader,
  Col,
  Drawer,
  Input,
  Row,
} from 'antd';
import {MetaDataCommon} from '../data';
import {FormItemConfig} from '@/utils/common';
import apis from '@/services';
import Classified from '@/pages/device/product/save/add/classified';
import encodeQueryParam from "@/utils/encodeParam";
import treeTool from 'tree-tool';
import AceEditor from "react-ace";

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

interface State {
  protocolSupports: any[];
  protocolTransports: any[];
  organizationList: any[];
  categoryLIst: any[];
  classifiedData: any;
  storagePolicy: string;
}

const Save: React.FC<Props> = props => {
  const initState: State = {
    protocolSupports: [],
    protocolTransports: [],
    organizationList: [],
    categoryLIst: [],
    classifiedData: {id: props.data.classifiedId || ''},
    storagePolicy: '',
  };

  const { getFieldDecorator, setFieldsValue } = props.form;
  // 消息协议
  const [protocolSupports, setProtocolSupports] = useState(initState.protocolSupports);
  // 消息协议
  const [organizationList, setOrganizationList] = useState(initState.organizationList);
  // 传输协议
  const [protocolTransports, setProtocolTransports] = useState(initState.protocolTransports);
  const [categoryLIst, setCategoryLIst] = useState(initState.categoryLIst);
  const [photoUrl, setPhotoUrl] = useState(props.data?.photoUrl);
  const [metaData, setMetaData] = useState(props.data?.metadata);
  const [classifiedVisible, setClassifiedVisible] = useState(false);
  const [classifiedData, setClassifiedData] = useState(initState.classifiedData);

  const [storagePolicy, setStoragePolicy] = useState<any[]>([]);
  const [checkStorage, setCheckStorage] = useState<any>(initState.storagePolicy);
  const onMessageProtocolChange = (value: string) => {
    // 获取链接协议
    apis.deviceProdcutCommon
      .protocolTransports(value)
      .then(e => {
        if (e.status === 200) {
          setProtocolTransports(e.result);
        }
      })
      .catch(() => {});
  };

  const setCategory = (list:any) =>{
    let idList: string[] = [];
    const pathList = treeTool.findPath(list, function (n: any) {
      return n.id == props.data.classifiedId
    }); // pathList所有父级data组成的
    if (pathList != null && pathList.length > 0) {
      idList = pathList.map((n: any) => n.id);// idList即为所求的上级所有ID
    }
    setFieldsValue({classifiedId: idList});
  };

  useEffect(() => {

    apis.metadataCommon
      .protocolSupport()
      .then(e => {
        if (e.status === 200) {
          setProtocolSupports(e.result);
        }
      })
      .catch(() => {});

    apis.metadataCommon
      .queryOrganization()
      .then((res: any) => {
        if (res.status === 200) {
          let orgList: any = [];
          res.result.map((item: any) => {
            orgList.push({ id: item.id, pId: item.parentId, value: item.id, title: item.name });
          });
          setOrganizationList(orgList);
        }
      })
      .catch(() => {});


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

    // if (systemVersion === 'pro') {
    apis.metadataCommon.storagePolicy().then(res => {
      if (res.status === 200) {
        setStoragePolicy(res.result);
      }
    });
    // }

    if (props.data && props.data.messageProtocol) {
      onMessageProtocolChange(props.data.messageProtocol);
    }
  }, []);

  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' }],
      },

      component: <Input placeholder="请输入物模型ID " disabled={!!props.data?.id} />,
    },
    {
      label: '物模型名称',
      key: 'name',
      options: {
        rules: [{ required: true, message: '请选择物模型名称' }],
        initialValue: props.data?.name,
      },
      styles: {
        xl: { span: 8 },
        lg: { span: 8 },
        md: { span: 12 },
        sm: { span: 24 },
      },
      component: <Input style={{ width: '100%' }} 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={categoryLIst}
          popupVisible={false}
          onChange={value => {
            if (value.length === 0) {
              setClassifiedData({});
            }
          }}
          onClick={() => {
            setClassifiedVisible(true);
          }}
          placeholder="点击选择品类"
        />
      ),
    },
    // {
    //   label: '物模型',
    //   key: 'metadata',
    //   options: {
    //     rules: [{required: true, message: '请输入物模型'}],
    //     initialValue: props.data?.metadata ,
    //   },
    //   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;

      props.save({
        ...fileValue,
        metadata: metaData,
        classifiedId: classifiedData.id,
      });
    });
  };

  return (
    <Drawer
      visible
      title={`${props.data?.id ? '编辑' : '新增'}物模型`}
      width={500}
      onClose={() => props.close()}
      closable
    >
      <Form labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
      <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>
            ))}
          </Row>
      </Form>

      <div
        style={{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
        }}
      >
        <Button
          onClick={() => {
            props.close();
          }}
          style={{ marginRight: 8 }}
        >
          关闭
        </Button>
        <Button
          onClick={() => {
            saveData();
          }}
          type="primary"
        >
          保存
        </Button>
      </div>
      {classifiedVisible && (
        <Classified
          choice={(item: any) => {
            const categoryId = item.categoryId;
            setFieldsValue({ classifiedId: categoryId });
            setClassifiedData(item);
            setClassifiedVisible(false);
          }}
          close={() => {
            setClassifiedVisible(false);
          }}
          data={classifiedData}
        />
      )}
    </Drawer>
  );
};

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