import React, { Component } from "react";
import qs from 'qs'
import {
  PageHeader ,
  Button,
  Row,
  Col,
  Upload,
  Input,
  Select,
  Form,
  Icon,
  message,
} from "antd";
import "./index.css";
import request from "../../../utils/request";
const { Option } = Select;
const { TextArea } = Input;

let id = 0;

@Form.create()
export default class StructureSearch extends Component {
  state = {
    list: [
      {
        name: "general search",
        state: true,
        searchType:1
      },
      {
        name: "cdr search",
        state: false,
        searchType:2
      },
      {
        name: "sequence search",
        state: false,
        searchType:3
      },
    ],
    targetsDetail: {
      name: "",
    },
    sum:0,

    LightChainSubclassList: [],
    AntigenTypeList: [],
    ExperimentalMethodList: [],
    HaveyChainSubclassList: [],
    LightChainTypeList:[],
    addList:[],
    generalSearchDTO: {
      pdbCode: "",
      lightChainType: "",
      rfactorCutoff: "",
      lightChainSubclass: "",
      resolutionCutoff: "",
      antigenType: "",
      antigenName: "",
      experimentalMethod: "",
      antigenUniportId: "",
      heavyChainSubclass: "",
      limit: 0,
      offset: 0,
      pageNumber: 1,
      pageSize: 10,
    },
    cdrSearchDTO: {
      cdr1: "",
      cdr2: "",
      cdr3: "",
      cdr4: "",
      cdr5: "",
      cdr6: "",
      cdrType1: "",
      cdrType2: "",
      cdrType3: "",
      cdrType4: "",
      cdrType5: "",
      cdrType6: "",
      limit: 0,
      offset: 0,
      pageNumber: 1,
      pageSize: 10,
    },
    sequenceSearchDTO: {
      fileName: "",
      identy: "",
      limit: 0,
      offset: 0,
      pageNumber: 1,
      pageSize: 10,
      sequence: ""
    },
    fileList:[],
    searchData:{
      searchType:1

    }
  };
  componentDidMount() {
    this.getSelectList1();
    this.getSelectList2();
    this.getSelectList3();
    this.getSelectList4();
    this.getSelectList5()
    this.getSelectList6()
    this.add()
  }
  getForm=()=>{

  }
  goList = () => {
    let data = this.state.searchData;
    if (this.state.searchData.searchType===1) {
      
      data.generalSearchDTO=this.state.generalSearchDTO
      this.props.history.push({
        pathname: "/home/SearchList",
        search: qs.stringify(data),
      });
      return

    }
    if (this.state.searchData.searchType===2) {
      this.handleSubmit()
      data.cdrSearchDTO=this.state.cdrSearchDTO
      this.props.history.push({
        pathname: "/home/SearchList",
        search: qs.stringify(data),
      });
      return

    }
    if (this.state.searchData.searchType===3) {
      data.sequenceSearchDTO=this.state.sequenceSearchDTO
      this.props.history.push({
        pathname: "/home/SearchList",
        search: qs.stringify(data),
      });
      return

    }
  
  };
  getSelectList1 = () => {
    request
      .post("/common/comboBox", {
        dictCode: "LIGHT-CHIAIN-SUBCLASS",
      })
      .then((res) => {
        console.log(res.data.result);
        if (res.data.code === 200) {
          this.setState({
            LightChainSubclassList: res.data.result,
          });
        } else {
          message.error(res.data.msg);
        }
      })
      .catch((err) => {
        console.error(err);
      });
  };
  getSelectList2 = () => {
    request
      .post("/common/comboBox", {
        dictCode: "ANTIGEN-TYPE",
      })
      .then((res) => {
        console.log(res.data.result);
        if (res.data.code === 200) {
          this.setState({
            AntigenTypeList: res.data.result,
          });
        } else {
          message.error(res.data.msg);
        }
      })
      .catch((err) => {
        console.error(err);
      });
  };
  getSelectList3 = () => {
    request
      .post("/common/comboBox", {
        dictCode: "EXPERIMENTAL-METHOD",
      })
      .then((res) => {
        console.log(res.data.result);
        if (res.data.code === 200) {
          this.setState({
            ExperimentalMethodList: res.data.result,
          });
        } else {
          message.error(res.data.msg);
        }
      })
      .catch((err) => {
        console.error(err);
      });
  };
  getSelectList4 = () => {
    request
      .post("/common/comboBox", {
        dictCode: "HEAVY-CHAIN-SUBCLASS",
      })
      .then((res) => {
        console.log(res.data.result);
        if (res.data.code === 200) {
          this.setState({
            HaveyChainSubclassList: res.data.result,
          });
        } else {
          message.error(res.data.msg);
        }
      })
      .catch((err) => {
        console.error(err);
      });
  };
  getSelectList5 = () => {
    request
      .post("/common/comboBox", {
        dictCode: "CDR_TYPE",
      })
      .then((res) => {
        console.log(res.data.result);
        if (res.data.code === 200) {
          this.setState({
            addList: res.data.result,
          });
        } else {
          message.error(res.data.msg);
        }
      })
      .catch((err) => {
        console.error(err);
      });
  };
  getSelectList6 = () => {
    request
      .post("/common/comboBox", {
        dictCode: "LIGHT-CHAIN-TYPE",
      })
      .then((res) => {
        console.log(res.data.result);
        if (res.data.code === 200) {
          this.setState({
            LightChainTypeList: res.data.result,
          });
        } else {
          message.error(res.data.msg);
        }
      })
      .catch((err) => {
        console.error(err);
      });
  };
  callback = (e) => {
    console.log(e);
    // let searchData = this.state.searchData;
    // searchData.name = e;
    // this.setState(() => ({ searchData: searchData }));
    // console.log(this.state.searchData);
  };
  getListOne = (e) => {
    console.log(1111);
    let newList = this.state.list;
    console.log(e);
    newList.forEach((item, index) => {
      item.state = false;
      if (e === index) {
        item.state = true;
        let searchData = this.state.searchData;
        searchData.searchType = item.searchType;
        this.setState(() => ({ searchData: searchData }));
      }
    });
    this.setState({
      list: newList,
    });
  };
  remove = (k) => {
    const { form } = this.props;
    // can use data-binding to get
    const keys = form.getFieldValue("keys");
    // We need at least one passenger
    if (keys.length === 1) {
      return;
    }
     
    this.setState({
      sum: keys.length-1
    })
     
    // can use data-binding to set
    form.setFieldsValue({
      keys: keys.filter((key) => key !== k),
    });
  };

  add = () => {
    const { form } = this.props;
    // can use data-binding to get
    const keys = form.getFieldValue("keys");
    console.log(keys);
    const nextKeys = keys.concat(id++);
    // can use data-binding to set
    // important! notify form to detect changes
    form.setFieldsValue({
      keys: nextKeys,
    });
    this.setState
    ({
      sum:keys.length+1
    })
   
  };

  handleSubmit = (e) => {
    // console.log(e);
    // e.preventDefault();
    this.props.form.validateFields((err, values) => {
      console.log(values);
      const { keys, names,names2  } = values;
      // console.log('Received values of form: ', values);
      // console.log('Merged values:', keys.map(key => names[key]));
      // let names=keys.map(key => names[key])
      console.log(names);
      console.log(names2);
      for (let index = 0; index < names.length; index++) {
        var element = names[index];
        if (element == undefined) {
          names[index] = "";
        }
      }
      let newArr = names.filter((i) => i && i.trim());
      for (let index = 0; index < names2.length; index++) {
        var element = names2[index];
        if (element == undefined) {
          names2[index] = "";
        }
      }
      let newArr2 = names2.filter((i) => i && i.trim());
      console.log(newArr2);
      let cdrSearchDTO=this.state.cdrSearchDTO
      cdrSearchDTO.cdr1=newArr[0]===undefined?'':newArr[0]
      cdrSearchDTO.cdr2=newArr[1]===undefined?'':newArr[1]
      cdrSearchDTO.cdr3=newArr[2]===undefined?'':newArr[2]
      cdrSearchDTO.cdr4=newArr[3]===undefined?'':newArr[3]
      cdrSearchDTO.cdr5=newArr[4]===undefined?'':newArr[4]
      cdrSearchDTO.cdr6=newArr[5]===undefined?'':newArr[5]
      cdrSearchDTO.cdrType1=newArr2[0]===undefined?'':newArr2[0]
      cdrSearchDTO.cdrType2=newArr2[1]===undefined?'':newArr2[1]
      cdrSearchDTO.cdrType3=newArr2[2]===undefined?'':newArr2[2]
      cdrSearchDTO.cdrType4=newArr2[3]===undefined?'':newArr2[3]
      cdrSearchDTO.cdrType5=newArr2[4]===undefined?'':newArr2[4]
      cdrSearchDTO.cdrType6=newArr2[5]===undefined?'':newArr2[5]
      // cdrSearchDTO.cdr1=newArr[0]
      // cdrSearchDTO.cdr2=newArr[1]
      // cdrSearchDTO.cdr3=newArr[2]
      // cdrSearchDTO.cdr4=newArr[3]
      // cdrSearchDTO.cdr5=newArr[4]
      // cdrSearchDTO.cdr6=newArr[5]
      // cdrSearchDTO.cdrType1=newArr2[0]
      // cdrSearchDTO.cdrType2=newArr2[1]
      // cdrSearchDTO.cdrType3=newArr2[2]
      // cdrSearchDTO.cdrType4=newArr2[3]
      // cdrSearchDTO.cdrType5=newArr2[4]
      // cdrSearchDTO.cdrType6=newArr2[5]

      

   
      this.setState(() => ({ cdrSearchDTO: cdrSearchDTO }));
      console.log(this.state.cdrSearchDTO);

      
    });
  };
  getValue = (e) => {
    const { value } = e.target;
    let generalSearchDTO = this.state.generalSearchDTO;
    generalSearchDTO.pdbCode = value;
    this.setState(() => ({ generalSearchDTO: generalSearchDTO }));
  };
  getValue2 = (e) => {
    const { value } = e.target;
    let generalSearchDTO = this.state.generalSearchDTO;
    generalSearchDTO.lightChainType = value;
    this.setState(() => ({ generalSearchDTO: generalSearchDTO }));
  };
  getValue3 = (e) => {
    const { value } = e.target;
    let generalSearchDTO = this.state.generalSearchDTO;
    generalSearchDTO.rfactorCutoff = value;
    this.setState(() => ({ generalSearchDTO: generalSearchDTO }));
  };
  getValue4 = (e) => {
    const { value } = e.target;
    let generalSearchDTO = this.state.generalSearchDTO;
    generalSearchDTO.resolutionCutoff = value;
    this.setState(() => ({ generalSearchDTO: generalSearchDTO }));
  };
  getValue5 = (e) => {
    const { value } = e.target;
    let generalSearchDTO = this.state.generalSearchDTO;
    generalSearchDTO.antigenName = value;
    this.setState(() => ({ generalSearchDTO: generalSearchDTO }));
  };
  getValue6 = (e) => {
    const { value } = e.target;
    let generalSearchDTO = this.state.generalSearchDTO;
    generalSearchDTO.antigenUniportId = value;
    this.setState(() => ({ generalSearchDTO: generalSearchDTO }));
  };
  getValue7 = (e) => {
    const { value } = e.target;
    let sequenceSearchDTO = this.state.sequenceSearchDTO;
    sequenceSearchDTO.sequence = value;
    this.setState(() => ({ sequenceSearchDTO: sequenceSearchDTO }));
  };
  getValue8 = (e) => {
    const { value } = e.target;
    let sequenceSearchDTO = this.state.sequenceSearchDTO;
    sequenceSearchDTO.identy = value;
    this.setState(() => ({ sequenceSearchDTO: sequenceSearchDTO }));
  };
  SelectValue = (e) => {
    console.log(e);
    let generalSearchDTO = this.state.generalSearchDTO;
    generalSearchDTO.lightChainSubclass = e;
    this.setState(() => ({ generalSearchDTO: generalSearchDTO }));
  };
  SelectValue2 = (e) => {
    console.log(e);
    let generalSearchDTO = this.state.generalSearchDTO;
    generalSearchDTO.antigenType = e;
    this.setState(() => ({ generalSearchDTO: generalSearchDTO }));
  };
  SelectValue3 = (e) => {
    console.log(e);
    let generalSearchDTO = this.state.generalSearchDTO;
    generalSearchDTO.experimentalMethod = e;
    this.setState(() => ({ generalSearchDTO: generalSearchDTO }));
  };
  SelectValue4 = (e) => {
    console.log(e);
    let generalSearchDTO = this.state.generalSearchDTO;
    generalSearchDTO.heavyChainSubclass = e;
    this.setState(() => ({ generalSearchDTO: generalSearchDTO }));
  };
  SelectValue5 = (e) => {
    console.log(e);
    let generalSearchDTO = this.state.generalSearchDTO;
    generalSearchDTO.lightChainType = e;
    this.setState(() => ({ generalSearchDTO: generalSearchDTO }));
  };
  handleChange=(info)=> {
    // console.log(info);
    let fileList = [...info.fileList];
    fileList = fileList.slice(-1);

    fileList = fileList.map(file => {
      if (file.response) {
        // Component will show file.url as link
        file.url = file.response.url;
      }
      return file;
    });
       if (fileList.length>0) {
        if (fileList[0].response&&fileList[0].response.code===200) {
          let sequenceSearchDTO=this.state.sequenceSearchDTO
          sequenceSearchDTO.fileName=fileList[0].response.result
         
        }
       }else{
        let sequenceSearchDTO=this.state.sequenceSearchDTO
        sequenceSearchDTO.fileName=''

       }

    this.setState({ fileList });
    // console.log(this.state.fileList);
  

    // if (info.file.status === 'done') {
    //   console.log(info.file.response.result);
    //   message.success(`上传成功`);
    // }if (info.file.status === 'error'){
    //   message.error(`上传失败`);
    // }
}
  

  render() {
    const {
      list,
      LightChainSubclassList,
      AntigenTypeList,
      ExperimentalMethodList,
      HaveyChainSubclassList,
      addList,
      sum,
      LightChainTypeList
    } = this.state;
    
    const props = {
      name: 'file',
      action: 'http://52.83.230.236:8084/yszh-antibody/common/uploadFile',
      onChange: this.handleChange,
      headers: {
        authorization: 'authorization-text',
        accessToken:window.localStorage.getItem('token')
      },}
    const formItemLayout2 = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 },
      },
    };
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const formItemLayoutWithOutLabel = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 20, offset: 4 },
      },
    };
    getFieldDecorator("keys", { initialValue: [] });
    const keys = getFieldValue("keys");
    const formItems = keys.map((k, index) => (
      <Form.Item
        {...(index === 0 ? formItemLayout2 : formItemLayoutWithOutLabel)}
        label={index === 0 ? "AlignSequence: " : ""}
        required={false}
        key={k}
      >
        <div style={{ display: "flex ", alignItems: "center " }}>
          {getFieldDecorator(`names[${k}]`)(
            <Input
              placeholder="请输入"
              style={{ width: "200px", marginRight: 8 }}
            />
          )}
          <div>
            <Form.Item style={{ margin:'0px'}}>
              {getFieldDecorator(`names2[${k}]`)(
                <Select style={{ width: "100px" }}>
                 {addList.map((item, index) => {
                            return (
                              <Option key={index} value={item.dictVal}>
                                {item.dictVal}
                              </Option>
                            );
                          })}
                </Select>
              )}
              {keys.length > 1 ? (
                <Icon
                  className="dynamic-delete-button"
                  type="minus-circle-o"
                  onClick={() => this.remove(k)}
                  style={{ marginLeft:'10px'}}
                />
              ) : null}
            </Form.Item>
          </div>
        </div>
      </Form.Item>
    ));
    return (
      <div>
          <PageHeader
    style={{
      border: '1px solid rgb(235, 237, 240)',
    }}
    onBack={()=>this.props.history.go(-1)}
    title="返回"
   
  />
        <div className="StructureSearch-div">
          <div className="left-div">
            {list.map((item, index) => {
              return (
                <Button
                  type={item.state ? "primary" : ""}
                  size="large"
                  shape="round"
                  onClick={() => this.getListOne(index)}
                  key={index}
                >
                  {item.name}
                </Button>
              );
            })}
          </div>
          <div className="right-div">
            {list[0].state && (
              <div className="generalsearch-div">
                <Row>
                  <Col span={12} style={{ marginBottom: 30 }}>
                    <div className="right-div-one">
                      <div className="title-div">PDBID:</div>
                      <div>
                        <Input
                          placeholder="请输入"
                          style={{ width: 200 }}
                          onChange={this.getValue}
                          value={this.state.generalSearchDTO.pdbCode}
                        />
                      </div>
                    </div>
                  </Col>
                  <Col span={12}>
                    <div className="right-div-one">
                      <div className="title-div">Light chain type:</div>
                      <div>
                         <Select
                          showSearch
                          style={{ width: 200 }}
                          placeholder="请选择"
                          value={this.state.generalSearchDTO.lightChainType}
                          onChange={this.SelectValue5}
                        >
                          {LightChainTypeList.map((item, index) => {
                            return (
                              <Option key={index} value={item.dictVal}>
                                {item.dictVal}
                              </Option>
                            );
                          })}
                        </Select>
                      </div>
                    </div>
                  </Col>
                </Row>
                <Row>
                  <Col span={12} style={{ marginBottom: 30 }}>
                    <div className="right-div-one">
                      <div className="title-div">R-factor cutoff:</div>
                      <div>
                        <Input
                          placeholder="请输入"
                          value={this.state.generalSearchDTO.rfactorCutoff}
                          onChange={this.getValue3}
                          style={{ width: 200 }}
                        />
                      </div>
                    </div>
                  </Col>
                  <Col span={12}>
                    <div className="right-div-one">
                      <div className="title-div">Light chain subclass:</div>
                      <div>
                        <Select
                          showSearch
                          style={{ width: 200 }}
                          placeholder="请选择"
                          value={this.state.generalSearchDTO.lightChainSubclass}
                          onChange={this.SelectValue}
                        >
                          {LightChainSubclassList.map((item, index) => {
                            return (
                              <Option key={index} value={item.dictVal}>
                                {item.dictVal}
                              </Option>
                            );
                          })}
                        </Select>
                      </div>
                    </div>
                  </Col>
                </Row>
                <Row>
                  <Col span={12} style={{ marginBottom: 30 }}>
                    <div className="right-div-one">
                      <div className="title-div">Resolution cutoff:</div>
                      <div>
                        <Input
                          placeholder="请输入"
                          value={this.state.generalSearchDTO.resolutionCutoff}
                          onChange={this.getValue4}
                          style={{ width: 200 }}
                        />
                      </div>
                    </div>
                  </Col>
                  <Col span={12}>
                    <div className="right-div-one">
                      <div className="title-div">Antigen type:</div>
                      <div>
                        <Select
                          showSearch
                          style={{ width: 200 }}
                          placeholder="请选择"
                          value={this.state.generalSearchDTO.antigenType}
                          onChange={this.SelectValue2}
                        >
                          {AntigenTypeList.map((item, index) => {
                            return (
                              <Option key={index} value={item.dictVal}>
                                {item.dictVal}
                              </Option>
                            );
                          })}
                        </Select>
                      </div>
                    </div>
                  </Col>
                </Row>
                <Row>
                  <Col span={12} style={{ marginBottom: 30 }}>
                    <div className="right-div-one">
                      <div className="title-div">Antigen name :</div>
                      <div>
                        <Input
                          placeholder="请输入"
                          value={this.state.generalSearchDTO.antigenName}
                          onChange={this.getValue5}
                          style={{ width: 200 }}
                        />
                      </div>
                    </div>
                  </Col>
                  <Col span={12}>
                    <div className="right-div-one">
                      <div className="title-div">Experimental method:</div>
                      <div>
                        <Select
                          showSearch
                          style={{ width: 200 }}
                          placeholder="请选择"
                          value={this.state.generalSearchDTO.experimentalMethod}
                          onChange={this.SelectValue3}
                        >
                          {ExperimentalMethodList.map((item, index) => {
                            return (
                              <Option key={index} value={item.dictVal}>
                                {item.dictVal}
                              </Option>
                            );
                          })}
                        </Select>
                      </div>
                    </div>
                  </Col>
                </Row>
                <Row>
                  <Col span={12}>
                    <div className="right-div-one">
                      <div className="title-div">antigent Uniport id:</div>
                      <div>
                        <Input
                          placeholder="请输入"
                          value={this.state.generalSearchDTO.antigenUniportId}
                          onChange={this.getValue6}
                          style={{ width: 200 }}
                        />
                      </div>
                    </div>
                  </Col>
                  <Col span={12}>
                    <div className="right-div-one">
                      <div className="title-div">Havey chain subclass:</div>
                      <div>
                        <Select
                          showSearch
                          style={{ width: 200 }}
                          placeholder="请选择"
                          value={this.state.generalSearchDTO.heavyChainSubclass}
                          onChange={this.SelectValue4}
                        >
                          {HaveyChainSubclassList.map((item, index) => {
                            return (
                              <Option key={index} value={item.dictVal}>
                                {item.dictVal}
                              </Option>
                            );
                          })}
                        </Select>
                      </div>
                    </div>
                  </Col>
                </Row>
              </div>
            )}
            {list[1].state && (
              <div className="form-div">
                <Form onSubmit={evt => this.handleSubmit(evt)}  className="login-form">
                  {formItems}
                  <Form.Item {...formItemLayoutWithOutLabel}>

                  {
                    sum<6&&(
                      <Button
                      type="dashed"
                      onClick={this.add}
                      style={{ width: "60%" }}
                    >
                      <Icon type="plus" /> Add field
                    </Button>

                    )

                  }
                  
                  </Form.Item>
                </Form>
              </div>
            )}

            {list[2].state && (
              <div className="sequencesearch-div">
                <div className="bottom-div">
                  <div>sequence:</div>
                  <div className="sequence-center">
                    <div className="TextArea-div">
                      <TextArea rows={14}   value={this.state.sequenceSearchDTO.sequence}
                          onChange={this.getValue7}/>
                    </div>
                    <div>
                      <Form layout="inline">
                        <Form.Item label="denty:">
                          <Input  value={this.state.sequenceSearchDTO.identy}
                          onChange={this.getValue8} />
                        </Form.Item>
                        <Form.Item label="上传文件">
                          <Upload {...props} fileList={this.state.fileList}>
                            <Button>
                              <Icon type="upload" /> 选择文件
                            </Button>
                          </Upload>
                        </Form.Item>
                      </Form>
                    </div>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
        <div className="bottom-butn">
          <Button
            onClick={this.goList}
            type="primary"
            size="large"
            shape="round"
          >
            search
          </Button>
        </div>
      </div>
    );
  }
}
