import React, { useState,useEffect } from 'react';
import { CloseOutlined} from '@ant-design/icons';
import { Modal, Form, Input, Button, Select,Radio,InputNumber, message,Space  } from 'antd';
import unitoption from '../unit'

const CreateForm = (props) => {
  const { Option, OptGroup } = Select;
  const [display,setdisplay]=useState('block');
  const [arttue,setarttue]=useState(0);
  const [disabled, setDisabled] = useState(false);
  const [disanumbled, setdisanumbled] = useState('block');
  const [disaenumbled, setdisaenumbled] = useState('none');
  const [displaybool,setdisplaybool]=useState('none');
  const [displaylength,setdisplaylength]=useState('none');
  const [displaytxtjson,setdisplaytxtjson]=useState('none');
  const [minnumber, setminnumber] = useState(0);
  const [maxnumber, setmaxnumber] = useState(1);
  const [ReadWrite, setReadWrite] = useState(0);
  const [form] = Form.useForm();
  const [boolLabel0,setboolLabel0]= useState('');
  const [boolLabel1,setboolLabel1]= useState('');
  const { TextArea } = Input;
  const options = [
    { value: `digit`, label: `int32(整型)`},
    {value:'text',label: `text(字符串)`},
    {value:'textareaary',label: `textarea(字符串数组)`},
      { value: `select`, label: `enum(枚举)`},
        // { value: `money`, label: `金额输入`},
      { value: `textarea`, label: `text(文本域)`},
        // { value: `date`, label: `日期`},
        // { value: `dateTime`, label: `日期时间`},
        // { value: `radio`, label: `单选框`},
        // { value: `radioButton`, label: `按钮单选框`},
     
      { value: `switch`, label: `bool(布尔型)`},
    ]
    useEffect(() => {
      
      if(props?.values?.id){
        console.log(JSON.parse(props?.values?.enumValue))
        setDisabled(true);
        setarttue(props?.values?.type)
        if(props?.values?.type==1){
          setdisplay("none")
          setdisanumbled('none')
        }else if(props?.values?.type==0){
          setdisplay("block")
        }
        onChangedataType(props?.values?.dataType)
        var enumvaluelist=[];
        enumvaluelist=JSON.parse(props?.values?.enumValue);
        form.setFieldsValue({
          id: props?.values?.id,
          type: props?.values?.type,
          //deviceVersionKey: props?.values?.deviceVersionKey,
          name: props?.values?.name,
          dataType: props?.values?.dataType,
          dataRange: props?.values?.dataRange,
          stepSize: props?.values?.stepSize,
          unit: props?.values?.unit,
          foreignKeyRe: props?.values?.foreignKeyRe,
          enumvaluelist:enumvaluelist,
          description:props?.values?.description,
          readWrite:props?.values?.readWrite,
          dataLength:props?.values?.dataLength,
          boolLabel:props?.values?.boolLabel,
          dataJson:props?.values?.dataJson
        });
        if(props?.values?.boolLabel){
          var boolLabel=props?.values?.boolLabel.split(':')
          setboolLabel0(boolLabel[0]);
          setboolLabel1(boolLabel[1]);
        }else{
          setboolLabel0("");
          setboolLabel1("");
        }
        if(props?.values?.dataRange){
          var num=props?.values?.dataRange.split('-')
          setminnumber(num[0]);
          setmaxnumber(num[1]);
        }else{
          setminnumber(0);
          setmaxnumber(1);
        }
       
      }else{
        
        console.log("xinjian")
        setDisabled(false);
        setdisplay("block")
        setminnumber(0);
        setmaxnumber(1)
        form.resetFields();
        setarttue(0)
        onChangedataType("digit")
        form.setFieldsValue({
          type: 0,
          dataType:'digit'
        });
      }
    },[props?.values])
const onchagetype=(e)=>{
  console.log(e)
  setarttue(e.target.value)
  form.setFieldsValue({
    type: e.target.value
  });
  if(e.target.value==1){
    setdisplay("none")
    setdisplaylength('none')
    setdisplaybool('none')
    setdisaenumbled('none')
    setdisanumbled('none')
  }else if(e.target.value==0){
    setdisplay("block")
    form.setFieldsValue({
      dataType: "digit"
    });
    setdisanumbled("block")
  }
}
const onChangemix=(value)=>{
  setminnumber(value)
}
const onChangemax=(value)=>{
  if(minnumber>value){
    message.error("最大值不能小于最小值")
  }else{
    setmaxnumber(value)
    form.setFieldsValue({
      dataRange: minnumber+"-"+value
    });
  }
}
const onChangedataType=(value)=>{
  console.log(value)
  if(value=="digit"){
    setdisanumbled('block')
    setdisaenumbled('none')
    setdisplaybool('none')
    setdisplaylength('none')
  }else if(value=="select"){
    setdisaenumbled('block')
    setdisanumbled('none')
    setdisplaybool('none')
    setdisplaylength('none')
    setdisplaytxtjson('none')
  }else if(value=="switch"){
    setdisplaybool('block')
    setdisaenumbled('none')
    setdisanumbled('none')
    setdisplaylength('none')
    setdisplaytxtjson('none')
  }else if(value=="text"){
    setdisplaybool('none')
    setdisaenumbled('none')
    setdisanumbled('none')
    setdisplaylength('block')
    setdisplaytxtjson('none')
  }else if(value=="textareaary"){
    setdisplaybool('none')
    setdisaenumbled('none')
    setdisanumbled('none')
    setdisplaylength('none')
    setdisplaytxtjson('block')
  }
  else{
    setdisplaylength('none')
    setdisplaybool('none')
    setdisaenumbled('none')
    setdisanumbled('none')
    setdisplaytxtjson('none')
  }
}
const onChangewrite=(e)=>{
  setReadWrite(e.target.value)
}
const onChangeboolLabel0=(e)=>{
  setboolLabel0(e.target.value)
}
const onChangeboolLabel1=(e)=>{
  setboolLabel1(e.target.value)
 
}
  return (
    <Modal
      title={props?.values?.id ? '编辑' : '新建'}
      width={640}
      visible={props?.createModalVisible}
      bodyStyle={{ padding: '32px 40px 8px' }}
      footer={null}
      onCancel={() => { 
        props?.onCancel();
      }}
      destroyOnClose
      maskClosable={false}
    >
      <Form
        layout="vertical"
        preserve={false}
        form={form}
        // initialValues={props?.values}
        onFinish={()=>{
          if(boolLabel0.length>0 && boolLabel1.length>0){
            form.setFieldsValue({
              boolLabel: boolLabel0+":"+boolLabel1
            });
          }
         
          console.log(form.getFieldsValue())
          props?.onFinish(form.getFieldsValue())
        }}
      >
        <Form.Item name="id" hidden={true}>
          <Input />
        </Form.Item>
        {/* <Form.Item label={'产品版本'} name="deviceVersionKey" rules={[{ required: true }]}>
          <Select>
            {props.DeviceVesionData.map((item, index) => {
              return (
                <Select.Option index={index} value={item.id} key={item.id}>
                  {item.vesion}
                </Select.Option>
              );
            })}
          </Select>
        </Form.Item> */}
        <Form.Item name="type" label="功能类型">
          <Radio.Group name="type" defaultValue={0} value={arttue} onChange={onchagetype} disabled={disabled}>
            <Radio.Button value={0}>属性</Radio.Button>
            <Radio.Button value={1}>服务</Radio.Button>
          </Radio.Group>
        </Form.Item>
        
        <Form.Item name="name" label="功能名称" rules={[{ required: true, max: 64, whitespace: true }]}>
          <Input placeholder="请输入功能名称" />
        </Form.Item>
        <Form.Item style={{display:display}} label={'数据类型'}  name="dataType" rules={[{ required: false }]}>
          <Select onChange={onChangedataType} defaultValue="digit">
            {options.map((item, index) => {
              return (
                <Select.Option index={index} value={item.value} key={item.value}>
                  {item.label}
                </Select.Option>
              );
            })}
          </Select>
        </Form.Item>
        <Form.Item style={{display:disaenumbled}} label={'枚举项'} name="enumValue" rules={[{ required: false }]}>
          <Form.List name='enumvaluelist'>
                    {(subFields, subOpt) => (
                      <div style={{ display: 'flex', flexDirection: 'column', rowGap: 16 }}>
                        {subFields.map((subField) => (
                          <Space key={subField.key}>
                            <Form.Item  name={[subField.name, 'enumvalue']}>
                              <Input placeholder="参数值" />
                            </Form.Item>
                            <Form.Item  name={[subField.name, 'enumlabel']}>
                              <Input placeholder="参数描述" />
                            </Form.Item>
                            <CloseOutlined
                              onClick={() => {
                                subOpt.remove(subField.name);
                              }}
                            />
                          </Space>
                        ))}
                        <Button type="dashed" onClick={() =>{
                          console.log(JSON.stringify(form.getFieldsValue(), null, 2))
                          console.log(subFields)
                          console.log(subOpt)
                          subOpt.add()
                          }} block>
                          + 添加枚举
                        </Button>
                      </div>
                    )}
                  </Form.List>
        </Form.Item>
        <Form.Item style={{display:disanumbled}} label={'取值范围'} name="dataRange" rules={[{ required: false }]}>
          <InputNumber placeholder="最小值" style={{width:'49%'}} value={minnumber} onChange={onChangemix}/>~<InputNumber value={maxnumber} placeholder="最大值" onChange={onChangemax} style={{width:'49%'}} />
        </Form.Item>
        <Form.Item style={{display:disanumbled}} label="步长" name="stepSize"  rules={[{ required: false }]}>
          <InputNumber placeholder="请输入步长" style={{width:'100%'}}/>
        </Form.Item>
        <Form.Item style={{display:disanumbled}} label={'单位'} name="unit" rules={[{ required: false }]}>
          <Select allowClear showSearch optionFilterProp="Name" filterOption={(input, option) => (option?.label ?? '').includes(input)}
          filterSort={(optionA, optionB) =>
            (optionA?.label ?? '').localeCompare((optionB?.label ?? ''))
          } options={unitoption}/>
        </Form.Item>
        <Form.Item style={{display:displaybool}}  name="boolLabel" label="布尔值" rules={[{ required: false }]}>
          0 -<Input placeholder="如：关" defaultValue={boolLabel0} onChange={onChangeboolLabel0} style={{width:'46%'}} />
          1 -<Input placeholder="如：开" defaultValue={boolLabel1} onChange={onChangeboolLabel1} style={{width:'46%'}}/>
        </Form.Item>
        <Form.Item style={{display:displaylength}}  name="dataLength" label="数据长度" rules={[{ required: false }]}>
          <Input placeholder="10240" defaultValue="10240" addonAfter="字节" />
       
        </Form.Item>
        <Form.Item style={{display:displaytxtjson}}  name="dataJson" label="数组字符串" rules={[{ required: false }]}>
          <TextArea
            placeholder="数据格式：[data1:{value1:'1'},{value2:'2'},data2:{value1:'1'},{value2:'2'}]"
            autoSize={{minRows: 10,maxRows: 100}}/>
        </Form.Item>
        <Form.Item style={{display:display}}  name="readWrite" label="读写类型" rules={[{ required: false }]}>
          <Radio.Group onChange={onChangewrite} name="radiogroup" defaultValue={0} value={ReadWrite}>
            <Radio value={0}>读写</Radio>
            {/* <Radio value={1}>只读</Radio> */}
          </Radio.Group>
        </Form.Item>
        <Form.Item  name="description" label="描述" rules={[{ required: false }]}>
          <TextArea showCount maxLength={100}  style={{height: 120, resize: 'none'}} placeholder="请输入描述"  />
       
        </Form.Item>
        <Form.Item>
        <Button  htmlType="button" style={{float:'right',left:10}} onClick={props.onCancel} >
                        取消
                    </Button>
                    <Button type="primary" htmlType="submit" style={{float:'right'}} >
                        保存
                    </Button>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default CreateForm;
