import React, { Component } from 'react'
import {
  Card,
  Tooltip,
  message,
  Button,
  Tabs,
  Spin,
  Table,
  Tag,
  Collapse,
  Divider,
  Modal,
  Form,
  Select,
  InputNumber,
  Popover,
  Pagination,
  Anchor
} from 'antd'
import { request } from '../../../utils/request'
import Molstar from 'molstar-react'
import { Jsme } from 'jsme-react'
import qs from 'qs'
import './index.css'
const { Panel } = Collapse
const { TabPane } = Tabs
const { Option } = Select
const { Link } = Anchor

export default class SearchDetails extends Component {
  state = {
    name: '',
    dataOne: qs.parse(this.props.location.search.slice(1)),
    visible: false,
    pdbId: '6f6s',
    smile: 'c',
    DetailsData: {
      smiles: null,
      Structure: [],
      Bioassay: [],
      Target: [],
      Indication: []
    },
    panelList: {},
    loading: true,
    getStructureList: {
      ligand_up_list: [],
      ligand_list: [],
      chain: [],
      References: [],
    },
    listData: {
      pdb_code: '',
      ligand: '',
      resolution: 0,
    },
    fileData: {
      filestring: '',
      type: 'pdb',
    },

    targetsDetail: {
      Target: [],

      Structure: [],
    },
    Biological_propeties: {},
    Calculated_propeties: {},
    BioassaySearch: {
      page: 1,
      page_size: 10,
      dataid: qs.parse(this.props.location.search.slice(1)).dataid

    },
    TargetSearch: {
      page: 1,
      page_size: 10,
      dataid: qs.parse(this.props.location.search.slice(1)).dataid

    },
    IndicationSearch: {
      page: 1,
      page_size: 10,
      dataid: qs.parse(this.props.location.search.slice(1)).dataid

    },

    total_num: 0,
    total_num2: 0,
    total_num3: 0,
  }
  componentDidMount () {
    this.getDetails()

  }
  getDetails () {
    // this.setState({loading:true})
    this.setState({ loading: true })
    request
      .post('/gpcr/drug_detail', this.props.location.search.slice(1))
      .then((res) => {
        this.setState({ loading: false })
        if (res.data.code === 200) {

          let data = res.data.data
          console.log(data)
          this.setState({
            DetailsData: data,
          })
          this.setState({ Calculated_propeties: data.Calculated_propeties })
          this.setState({ Biological_propeties: data.biological_propeties })


          this.setState({ loading: false })

          let StructureList = data.Structure
          if (StructureList.length > 0) {
            this.getStructure(StructureList[0].pdb)
          }
          this.getBioassayList()
          this.getTargetList()
          this.getIndicationList()
        } else {
          message.error(res.data.msg)
        }
      })
      .catch((err) => {
        console.error(err)
      })
  }
  getStructure = (e) => {
    request
      .post(
        '/search_pdb_data',
        qs.stringify({
          pdb: e,
        })
      )
      .then((res) => {
        this.setState({ loading: false })
        if (res.data.code === 200) {
          this.setState({ getStructureList: res.data.data })
          let listData = this.state.listData
          listData.pdb_code = res.data.data.name
          this.setState({ listData })
        } else {
          message.error(res.data.msg)
        }
      })
      .catch((err) => {
        console.error(err)
      })
  }
  ChangeTabs = (e) => {
    console.log(e)
    let listData = this.state.listData
    listData.ligand = ''
    this.setState({
      listData: listData,
    })
    this.getStructure(e)
  }
  getPdid (e) {
    console.log(e)
    this.setState({ visible: true })
    this.setState({ pdbId: e })
  }
  getTag = (e) => {
    console.log(e)
    this.setState({ visible: true })
    this.setState({ pdbId: e })
  }
  getReferences = (e) => {
    window.open(`https://pubmed.ncbi.nlm.nih.gov/${e}`)
  }
  getList = () => {
    if (this.state.listData.ligand === '') {
      message.warning('输入查询条件')
      return
    }
    request
      .post('/search_pdb_ligand_resolution', qs.stringify(this.state.listData))
      .then((res) => {
        let fileData = JSON.parse(JSON.stringify(this.state.fileData))
        fileData.filestring = res.data
        this.setState({
          fileData,
        })
        this.setState({
          visible: true,
        })
        console.log(this.state.fileData)
        this.setState({ loading: false })
        // if (res.data.code===200) {
        //   this.setState({getStructureList:res.data.data})

        //   this.setState({
        //     visible:true
        //   })

        // }else{
        //   message.error(res.data.msg);
        // }
      })
      .catch((err) => {
        console.error(err)
      })
  }
  getResolutionData = (e) => {
    let listData = this.state.listData
    listData.resolution = e
    this.setState({
      listData,
    })
  }
  LigandChange = (e) => {
    let listData = this.state.listData
    listData.ligand = e
    this.setState({
      listData,
    })
  }

  callback () { }
  getOne (e) {
    console.log(e)
    const { dataid } = e
    let data = {
      dataid,
    }

    this.props.history.push({
      pathname: '/home/TargetDetails',
      search: qs.stringify(data),
    })
  }
  getBioassayList = () => {
    console.log(this.state.dataOne)
    const { dataid } = this.state.dataOne
    this.setState({ loading: true })
    request.post('gpcr/drug_detail/bioassay', qs.stringify(this.state.BioassaySearch))
      .then(res => {
        this.setState({ loading: false })
        if (res) {
          console.log(res)
          let DetailsData = this.state.DetailsData
          DetailsData.Bioassay = res.data.data
          this.setState({ total_num2: res.data.total_num })
          this.setState({
            DetailsData: DetailsData
          })
        }



      })
      .catch(err => {
        console.error(err)
      })

  }
  getTargetList = () => {
    console.log(this.state.dataOne)
    const { dataid } = this.state.dataOne
    this.setState({ loading: true })
    request.post('gpcr/drug_detail/target', qs.stringify(this.state.TargetSearch))
      .then(res => {
        this.setState({ loading: false })
        if (res) {
          console.log(res)
          let DetailsData = this.state.DetailsData
          DetailsData.Target = res.data.data
          this.setState({ total_num: res.data.total_num })
          this.setState({
            DetailsData: DetailsData
          })
        }



      })
      .catch(err => {
        console.error(err)
      })

  }
  getIndicationList = () => {
    console.log(this.state.dataOne)
    const { dataid } = this.state.dataOne
    this.setState({ loading: true })
    request.post('gpcr/drug_detail/indication', qs.stringify(this.state.IndicationSearch))
      .then(res => {
        this.setState({ loading: false })
        if (res) {
          console.log(res)
          let DetailsData = this.state.DetailsData
          DetailsData.Indication = res.data.data
          this.setState({ total_num3: res.data.total_num })
          this.setState({
            DetailsData: DetailsData
          })
        }



      })
      .catch(err => {
        console.error(err)
      })

  }
  onShowSizeChange = (current, pageSize) => {
    let BioassaySearch = this.state.BioassaySearch
    BioassaySearch.page = current
    BioassaySearch.page_size = pageSize
    this.setState({
      BioassaySearch
    })
    this.getBioassayList()


  }
  onChange = (current, pageSize) => {

    let BioassaySearch = this.state.BioassaySearch
    BioassaySearch.page = current
    BioassaySearch.page_size = pageSize
    this.setState({
      BioassaySearch
    })

    this.getBioassayList()




  }
  onShowSizeChange2 = (current, pageSize) => {
    console.log(current, pageSize)
    let TargetSearch = this.state.TargetSearch
    TargetSearch.page = current
    TargetSearch.page_size = pageSize
    this.setState({
      TargetSearch
    })
    this.getTargetList()
  }
  onChange2 = (current, pageSize) => {
    console.log(current, pageSize)
    let TargetSearch = this.state.TargetSearch
    TargetSearch.page = current
    TargetSearch.page_size = pageSize
    this.setState({
      TargetSearch
    })
    this.getTargetList()
  }
  onShowSizeChange3 = (current, pageSize) => {
    console.log(current, pageSize)
    let IndicationSearch = this.state.IndicationSearch
    IndicationSearch.page = current
    IndicationSearch.page_size = pageSize
    this.setState({
      IndicationSearch
    })
    this.getIndicationList()
  }
  onChange3 = (current, pageSize) => {
    console.log(current, pageSize)
    let IndicationSearch = this.state.IndicationSearch
    IndicationSearch.page = current
    IndicationSearch.page_size = pageSize
    this.setState({
      IndicationSearch
    })
    this.getIndicationList()
  }
  handleAnchorClick = (e) => {
    e.preventDefault()
  }
  render () {
    const {
      visible,
      panelList,
      name,
      pdbId,
      DetailsData,
      getStructureList,
      targetsDetail,
      total_num,
      total_num2,
      total_num3,
      Calculated_propeties,
      Biological_propeties,
      smile
    } = this.state
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 12 },
    }
    const columns = [
      {
        title: 'Target name',
        dataIndex: 'Target name',
        key: 'Target name',
        render: (item, record) => (
          <Tag
            color="blue"
            onClick={() => {
              this.getOne(record)
            }}>
            {record.Target_name}
          </Tag>
        ),
      },
      {
        title: 'Class',
        dataIndex: 'Class',
        key: 'Class',
      },
      {
        title: 'Family',
        dataIndex: 'Family',
        key: 'Family',
      },

      {
        title: 'Uniport id',
        dataIndex: 'Uniport_id',
        key: 'Uniport_id',
      },
      {
        title: 'PDB',
        dataIndex: 'PDB',
        render: (PDB) => (
          <span>
            {PDB.map((item, index) => {
              return (
                <Tag
                  color="blue"
                  key={index}
                  onClick={() => {
                    this.getTag(item)
                  }}>
                  {item.toUpperCase()}
                </Tag>
              )
            })}
          </span>
        ),
      },
      {
        title: 'sequence',
        dataIndex: 'sequence',
        key: 'sequence',
        render: (sequence) => (
          <span>
            {
              <Tooltip placement="topLeft" title={sequence}>
                <Button>Sequence</Button>
              </Tooltip>
            }
          </span>
        ),
      },
    ]
    const columns2 = [
      {
        title: 'Indication',
        dataIndex: 'Indication',
        key: 'Indication',
      },
      {
        title: 'Target',
        dataIndex: 'Target',
        key: 'Target',
      },
      {
        title: 'Status',
        dataIndex: 'Status',
        key: 'Status',
      },
      {
        title: 'Clinical phase',
        dataIndex: 'Clinical_phase',
        key: 'Clinical_phase',
      },
      {
        title: 'Clinical status',
        dataIndex: 'Clinical_status',
        key: 'Clinical_status',
      },
      {
        title: 'Year of approval',
        dataIndex: 'Year_of_approval',
        key: 'Year_of_approval',
      },

      {
        title: 'Mechanism of Action',
        dataIndex: 'Mechanism_of_Action',
        key: 'Mechanism_of_Action',
      },

      {
        title: 'References',
        dataIndex: 'References',
        render: (References) => (
          <span>
            {References.map((item, index) => {
              return (
                <Tag
                  color="blue"
                  key={index}
                  onClick={() => {
                    this.getReferences(item)
                  }}>
                  {item.toUpperCase()}
                </Tag>
              )
            })}
          </span>
        ),
      },
    ]
    const columns3 = [
      {
        title: 'Target',
        dataIndex: 'Target',
        render: (item, record) => (
          <Tag
            color="blue"
            onClick={() => {
              this.getOne(record)
            }}>
            {record.Target_name}
          </Tag>
        ),
      },
      {
        title: 'Type',
        dataIndex: 'Type',
        key: 'Type',
      },
      {
        title: 'Action',
        dataIndex: 'Action',
        key: 'Action',
      },
      {
        title: 'Value',
        dataIndex: 'Value',
        key: 'Value',
      },
      {
        title: 'Parameter',
        dataIndex: 'Parameter',
        key: 'Parameter',
      },
      {
        title: 'Reference',
        dataIndex: 'Reference',
        key: 'Reference',
        render: (References) => (
          <span>
            {References &&
              References.map((item, index) => {
                return (
                  <Tag
                    color="blue"
                    key={index}
                    onClick={() => {
                      this.getReferences(item)
                    }}>
                    {item.toUpperCase()}
                  </Tag>
                )
              })}
          </span>
        ),
      },
      // {
      //   title: 'Year of approval',
      //   dataIndex: 'Year of approval',
      //   key: 'Year of approval',
      // },
      // {
      //   title: 'References',
      //   dataIndex: 'References',
      //   render: References => (
      //     <span>
      //       {References.map(item => {
      //         return (
      //           <Tag color="blue" key={item} onClick={()=>{this.getReferences(item)}} >
      //             {item.toUpperCase()}
      //           </Tag>
      //         );
      //       })}
      //     </span>
      //   ),
      // },
    ]
    const columnsChain = [
      {
        title: 'Chain_name',
        dataIndex: 'Chain_name',
        key: 'Chain_name',
      },
      {
        title: 'Chain_ID',
        dataIndex: 'Chain_ID',
        key: 'Chain_ID',
      },

      {
        title: 'code',
        dataIndex: 'code',
        key: 'code',
      },
      {
        title: 'code_type',
        dataIndex: 'code_type',
        key: 'code_type',
      },
      {
        title: 'res_start',
        dataIndex: 'res_start',
        key: 'res_start',
      },
      {
        title: 'res_end',
        dataIndex: 'res_end',
        key: 'res_end',
      },
    ]
    return (
      <div className="search-details-div">
        <Modal
          footer={null}
          closable={false}
          width={850}
          visible={visible}
          wrapClassName="vertical-center-modal"
          onCancel={() => this.setState({ visible: false })}>
          <div className="Molstar-div">
            <Molstar file={this.state.fileData} />
          </div>
        </Modal>
        <Spin tip="Loading..." size="large" spinning={this.state.loading}>
          <div className="Anchor-div">
            <Anchor onClick={this.handleAnchorClick}>
              <Link href="#card" title="Title" />
              <Link href="#Indication" title="Indication" />
              <Link href="#Target" title="Target" />
              <Link href="#BiologicalPropeties" title="Biological Propeties" />
              <Link href="#Bioassay" title="Bioassay" />
              <Link href="#CalculatedPropeties" title="Calculated Propeties" />
              <Link href="#Structure" title="Structure" />
            </Anchor>
          </div>
          <Card hoverable id='card'>
            <div>
              <div className="title-div">{name}</div>
              <div className="title-div-top">
                <div className="DataList-left">

                  <div>
                    <div className="title-div">{DetailsData.name}</div>
                    <div className="title-div-top">
                      <div className="DataList-left">
                        <div>
                          <div className="div-list">
                            <div className="list-one">
                              <div className="left-title">Synonyms</div>
                              <div />
                              {DetailsData.synonyms}
                            </div>
                            <div className="list-one">
                              <div className="left-title">Drug Type</div>
                              <div />
                              {DetailsData.datatype}
                            </div>
                            <div className="list-one">
                              <div className="left-title">Smiles</div>
                              <div />
                              {DetailsData.smiles}
                            </div>
                          </div>
                        </div>
                      </div>
                      <div className="Jsme-div">
                        {
                          DetailsData.smiles && <Jsme
                            height="300px"
                            width="300px"
                            options="depict,useopenchemlib"
                            smiles={DetailsData.smiles}
                          />
                        }

                      </div>
                    </div>
                  </div>

                </div>
              </div>
            </div>
          </Card>
          <Collapse
            defaultActiveKey={['1', '2', '3', '4', '5', '6']}
            onChange={this.callback}>
            <Panel header="Indication" id='Indication' key="6">
              <Table
                bordered
                rowKey="dataid"
                dataSource={DetailsData.Indication}
                pagination={false}
                columns={columns2}
              />
              <Pagination
                showSizeChanger
                onShowSizeChange={this.onShowSizeChange3}
                onChange={this.onChange3}
                total={total_num3}
              />
            </Panel>
            <Panel header="Target" key="1" id='Target'>
              <Table
                bordered
                rowKey="dataid"
                dataSource={DetailsData.Target}
                pagination={false}
                columns={columns}
              />
              <Pagination
                showSizeChanger
                onShowSizeChange={this.onShowSizeChange2}
                onChange={this.onChange2}
                total={total_num}
              />
            </Panel>
            <Panel header="Biological Propeties" id='BiologicalPropeties' key="5">
              <div className="Calcilated">
                <div className="div-list">
                  <div className="list-one">
                    <div>Absorption:</div>
                    <div />
                    {Biological_propeties.absorption}
                  </div>
                  <div className="list-one">
                    <div>Clearance:</div>
                    <div />
                    {Biological_propeties.clearance}
                  </div>
                  <div className="list-one">
                    <div>Distribution: </div>
                    <div />
                    {Biological_propeties.distribution}
                  </div>
                  <div className="list-one">
                    <div>Elimination:</div>
                    <div />
                    {Biological_propeties.elimination}
                  </div>
                  <div className="list-one">
                    <div>Half Life: </div>
                    <div />
                    {Biological_propeties.half_life}
                  </div>
                  <div className="list-one">
                    <div>metabolism: </div>
                    <div />
                    {Biological_propeties.metabolism}
                  </div>
                  <div className="list-one">
                    <div>Toxicity: </div>
                    <div />
                    {Biological_propeties.toxicity}
                  </div>
                </div>
              </div>
            </Panel>

            <Panel header="Bioassay" key="2" id='Bioassay'>
              <Table
                bordered
                rowKey="dataid"
                dataSource={DetailsData.Bioassay}
                pagination={false}
                columns={columns3}
              />
              <Pagination
                showSizeChanger
                onShowSizeChange={this.onShowSizeChange}
                onChange={this.onChange}
                total={total_num2}
              />
            </Panel>
            <Panel header="Calculated Propeties" key="3" id='CalculatedPropeties'>
              <div>
                <div className="Calcilated">
                  <div className="list-one2">
                    <div>Molecular weight:</div>
                    <div />
                    {Calculated_propeties.Molecular_weight}
                  </div>
                  <div className="list-one2">
                    <div>LogP:</div>
                    <div />
                    {Calculated_propeties.logP}
                  </div>
                  <div className="list-one2">
                    <div>Hydrogen bond donor: </div>
                    <div />
                    {Calculated_propeties.Hydrogen_bond_donor}
                  </div>
                  <div className="list-one2">
                    <div>Hydrogen bond acceptor:</div>
                    <div />
                    {Calculated_propeties.Hydrogen_bond_acceptor}
                  </div>
                  <div className="list-one2">
                    <div>Rotatable bond: </div>
                    <div />
                    {Calculated_propeties.Rotatable_bond}
                  </div>
                  <div className="list-one2">
                    <div>sp3 Carbon: </div>
                    <div />
                    {Calculated_propeties.Sp3_Carbon}
                  </div>
                </div>
              </div>
            </Panel>
            <Panel header="Structure" key="4" id='Structure'>
              <Tabs
                defaultActiveKey="0"
                // type="card"
                style={{ height: 1000 }}
                tabPosition='left'
                onChange={this.ChangeTabs}>
                {DetailsData.Structure.map((item, index) => {
                  return (
                    <TabPane

                      tab={item.pdb + ' (' + item.type + ')'}
                      key={index}>
                      <div className="TabPane-center">
                        <div className="Molstar-div2">
                          <Molstar pdbId={item.pdb} />
                        </div>
                        <div className="Structure-right">
                          <Form layout="horizontal">
                            <Form.Item label="详情" {...formItemLayout}>
                              <div>method: {getStructureList.method}</div>
                              <div>name: {getStructureList.name}</div>
                              <div>
                                pdb_datatime: {getStructureList.pdb_datatime}
                              </div>
                              <div>
                                resolution: {getStructureList.resolution}
                              </div>
                            </Form.Item>
                            <Form.Item label="配体列表" {...formItemLayout}>
                              {getStructureList.ligand_up_list &&
                                getStructureList.ligand_up_list.map(
                                  (item, index2) => {
                                    return (
                                      <Popover
                                        key={index2}
                                        content={
                                          <div key={index2}>
                                            <div
                                              style={{
                                                width: '100px',
                                                wordWrap: 'break-word',
                                                wordBreak: 'normal',
                                              }}>
                                              {item.comp_name}
                                            </div>

                                            <Jsme
                                              height="100px"
                                              width="100px"
                                              options="depict,useopenchemlib"
                                              smiles={item.smiles}
                                            />
                                          </div>
                                        }>
                                        {
                                          <Button
                                            type="primary"
                                            style={{ marginRight: '5px' }}>
                                            {item.name}
                                          </Button>
                                        }
                                      </Popover>
                                    )
                                  }
                                )}
                            </Form.Item>
                            <Form.Item label="配体选择" {...formItemLayout}>
                              <Select
                                style={{ width: 250 }}
                                value={this.state.listData.ligand}
                                size="large"
                                onChange={this.LigandChange}>
                                {getStructureList.ligand_list &&
                                  getStructureList.ligand_list.map(
                                    (item, index3) => {
                                      return (
                                        <Option key={index3} value={item}>
                                          {item}
                                        </Option>
                                      )
                                    }
                                  )}
                              </Select>
                            </Form.Item>
                            <Form.Item label="搜索半径" {...formItemLayout}>
                              <InputNumber
                                style={{ width: 250 }}
                                min={getStructureList.resolution}
                                max={10}
                                placeholder={'请输入大于resolutiond数字'}
                                step={0.1}
                                size="large"
                                onChange={this.getResolutionData}
                              />
                            </Form.Item>
                            <Form.Item label="References " {...formItemLayout}>
                              {getStructureList.References &&
                                getStructureList.References.map(
                                  (item, index4) => {
                                    return (
                                      <Button
                                        type="primary"
                                        onClick={() => {
                                          this.getReferences(item)
                                        }}
                                        key={index4}
                                        style={{ marginRight: '5px' }}>
                                        {item}
                                      </Button>
                                    )
                                  }
                                )}
                            </Form.Item>
                            <Form.Item label="Search" {...formItemLayout}>
                              <Button
                                type="primary"
                                style={{ marginLeft: 50, width: 150 }}
                                size="large"
                                loading={this.state.loading}
                                onClick={this.getList}>
                                Search
                              </Button>
                            </Form.Item>
                          </Form>
                        </div>
                      </div>
                      <Table
                        bordered
                        rowKey="item"
                        dataSource={getStructureList.chain}
                        pagination={false}
                        columns={columnsChain}
                      />
                    </TabPane>
                  )
                })}
              </Tabs>
            </Panel>
          </Collapse>
        </Spin>
      </div>
    )
  }
}
