import React, { Component } from "react";
import {
  Card,
  Tooltip,
  Pagination,
  message,
  Popover,
  Button,
  Tabs,
  Spin,
  Table,
  Tag,
  Input,
  Collapse,
  Modal,
  Form,
  Select,
  InputNumber,
  Typography,
} 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 { Title } = Typography;

export default class LigandDetails extends Component {
  state = {
    name: "",
    Structure: [],
    dataOne: qs.parse(this.props.location.search.slice(1)),
    visible: false,
    visible2: false,
    pdbId: "6f6s",
    DetailsData: {
      PubChemCID: 5462310,
      MolecularWeight: 12.011,
      smiles: "cccc",
    },
    panelList: {
      Bioassay: [],
    },
    statusMutation: 0,
    OLDMutationList: [],
    CalculatedPropeties: {},
    pharmacological_properties: {},
    targetsDetail: {
      Structure: [],
      Sequence: [],
      Products: [],
      Target: [],
      Condition: [],
    },
    loading: true,
    getStructureList: {
      ligand_up_list: [],
      ligand_list: [],
      chain: [],
      References: [],
    },
    listData: {
      pdb_code: "",
      ligand: "",
      resolution: 0,
    },
    fileData: {
      filestring: "",
      type: "pdb",
    },
    ProductsSearch: {
      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,
    },
    conditionSearch: {
      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();
  }
  onShowSizeChange = (current, pageSize) => {
    let ProductsSearch = this.state.ProductsSearch;
    ProductsSearch.page = current;
    ProductsSearch.page_size = pageSize;
    this.setState({
      ProductsSearch,
    });
    this.getProductsList();
  };
  onChange = (current, pageSize) => {
    let ProductsSearch = this.state.ProductsSearch;
    ProductsSearch.page = current;
    ProductsSearch.page_size = pageSize;
    this.setState({
      ProductsSearch,
    });

    this.getProductsList();
  };
  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 conditionSearch = this.state.conditionSearch;
    conditionSearch.page = current;
    conditionSearch.page_size = pageSize;
    this.setState({
      conditionSearch,
    });
    this.getConditionList();
  };
  onChange3 = (current, pageSize) => {
    console.log(current, pageSize);
    let conditionSearch = this.state.conditionSearch;
    conditionSearch.page = current;
    conditionSearch.page_size = pageSize;
    this.setState({
      conditionSearch,
    });

    this.getConditionList();
  };
  getProductsList = () => {
    console.log(this.state.dataOne);
    const { dataid } = this.state.dataOne;
    this.setState({ loading: true });
    request
      .post(
        "/drugbank/drug_detail/product",
        qs.stringify(this.state.ProductsSearch)
      )
      .then((res) => {
        this.setState({ loading: false });
        if (res) {
          console.log(res);
          let targetsDetail = this.state.targetsDetail;
          targetsDetail.Products = res.data.data;
          this.setState({ total_num2: res.data.total_num });
          this.setState({
            targetsDetail: targetsDetail,
          });
        }
      })
      .catch((err) => {
        console.error(err);
      });
  };
  getTargetList = () => {
    console.log(this.state.dataOne);
    const { dataid } = this.state.dataOne;
    this.setState({ loading: true });
    request
      .post(
        "/drugbank/drug_detail/target",
        qs.stringify(this.state.TargetSearch)
      )
      .then((res) => {
        this.setState({ loading: false });
        if (res) {
          console.log(res);
          let targetsDetail = this.state.targetsDetail;
          targetsDetail.Target = res.data.data;
          this.setState({ total_num: res.data.total_num });
          this.setState({
            targetsDetail: targetsDetail,
          });
        }
      })
      .catch((err) => {
        console.error(err);
      });
  };
  getConditionList = () => {
    this.setState({ loading: true });
    request
      .post(
        "/kinase/drug_detail/condition",
        qs.stringify(this.state.conditionSearch)
      )
      .then((res) => {
        this.setState({ loading: false });
        if (res) {
          console.log(res);
          let targetsDetail = this.state.targetsDetail;
          let newSmilesList = res.data.data;
          newSmilesList.forEach((element) => {
            element.TargetState = true;
          });
          targetsDetail.Condition = newSmilesList;
          this.setState({ total_num3: res.data.total_num });
          this.setState({
            targetsDetail: targetsDetail,
          });
        }
      })
      .catch((err) => {
        console.error(err);
      });
  };
  getDetails() {
    // this.setState({loading:true})
    this.setState({ loading: true });
    request
      .post("/drugbank/drug_detail", this.props.location.search.slice(1))
      .then((res) => {
        this.setState({ loading: false });
        if (res.data.code === 200) {
          console.log(res);

          let data = res.data.data;
          this.setState({ targetsDetail: data });
          this.setState({ CalculatedPropeties: data.Calculated_propeties });
          this.setState({
            pharmacological_properties: data.pharmacological_properties,
          });

          this.setState({ OLDMutationList: data.Mutation });

          this.setState({ loading: false });
          this.getProductsList();
          this.getTargetList();
          // this.getConditionList();
          let StructureList = data.Structure;
          if (StructureList.length > 0) {
            this.getStructure(StructureList[0].pdb);
          }
        } else {
          message.error(res.data.msg);
        }
      })
      .catch((err) => {
        console.error(err);
      });
  }
  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 });
  };
  getReferences2 = (e) => {
    window.open(`https://pubmed.ncbi.nlm.nih.gov/${e}`);
  };
  getIndiCation = (e) => {
    window.open(`https://clinicaltrials.gov/ct2/show/${e}`);
  };
  onChangeRadio = (e) => {
    let OLDMutationList = this.state.targetsDetail.Mutation;
    this.setState({
      OLDMutationList: OLDMutationList,
    });
    let value = e.target.value;
    this.setState({
      statusMutation: value,
    });
    if (value === 0) {
      OLDMutationList = this.state.targetsDetail.Mutation;
      this.setState({
        OLDMutationList: OLDMutationList,
      });
    }
    if (value === 1) {
      let MutationList1 = OLDMutationList.filter((item) => {
        return item.status === 1;
      });

      this.setState({
        OLDMutationList: MutationList1,
      });
    }
    if (value === 2) {
      let MutationList2 = OLDMutationList.filter((item) => {
        return item.status === 2;
      });

      this.setState({
        OLDMutationList: MutationList2,
      });
    }
  };
  getDrug = (e) => {
    console.log(e);
    let data = {
      dataid: e,
    };
    this.props.history.push({
      pathname: "/drugbank/SearchDetails",
      search: qs.stringify(data),
    });
  };
  getOne(e) {
    console.log(e);
    const { dataid } = e;
    let data = {
      dataid,
    };

    this.props.history.push({
      pathname: "/drugbank/TargetDetails",
      search: qs.stringify(data),
    });
  }

  callback() {}
  childTargetClassChange = () => {};
  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) => {
    let listData = this.state.listData;
    listData.ligand = "";
    this.setState({
      listData: listData,
    });
    this.getStructure(e);
  };
  getReferences = (e) => {
    var str = e;
    var n = str.search(/CHEMBL/i);
    if (n === -1) {
      window.open(`https://www.doi.org/${e}`);
    } else {
      window.open(`https://www.ebi.ac.uk/chembl/document_report_card/${e}`);
    }
  };
  getList = () => {
    let fileData = this.state.fileData;
    fileData.filestring = "";
    this.setState({
      fileData: fileData,
    });
    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: fileData,
        });

        this.setState({
          visible2: true,
        });

        this.setState({ loading: false });
        console.log(this.state.fileData);
      })
      .catch((err) => {
        console.error(err);
      });
  };
  getResolutionData = (e) => {
    console.log(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,
    });
  };
  TargetButton = (e, index) => {
    console.log(e.TargetState);
    let newsmilesList = this.state.targetsDetail.Condition;

    newsmilesList.forEach((element) => {
      if (element.dataid === e.dataid) {
        element.TargetState = false;
      }
    });
    let targetsDetail = this.state.targetsDetail;
    targetsDetail.Condition = newsmilesList;

    this.setState({
      targetsDetail: targetsDetail,
    });
  };
  TargetButton2 = (e, index) => {
    console.log(e.TargetState);
    let newsmilesList = this.state.targetsDetail.Condition;

    newsmilesList.forEach((element) => {
      if (element.dataid === e.dataid) {
        element.TargetState = true;
      }
    });
    let targetsDetail = this.state.targetsDetail;
    targetsDetail.Condition = newsmilesList;

    this.setState({
      targetsDetail: targetsDetail,
    });
  };
  render() {
    const {
      visible,
      visible2,
      total_num,
      total_num2,
      total_num3,
      getStructureList,
      targetsDetail,
      CalculatedPropeties,
      pharmacological_properties,
    } = this.state;
    const columnsProducts = [
      {
        title: "Brand name",
        dataIndex: "brand_name",
        key: "brand_name",
      },
      {
        title: "Labeller",
        dataIndex: "labeller",
        key: "labeller",
      },
      {
        title: "Route",
        dataIndex: "route",
        key: "route",
      },
      {
        title: "Marketing start",
        dataIndex: "marketing_start",
        key: "marketing_start",
      },
      {
        title: "Marketing end",
        dataIndex: "marketing_end",
        key: "marketing_end",
      },
      {
        title: "Country/Ragion",
        dataIndex: "country",
        key: "country",
      },
    ];
    const columns = [
      {
        title: "Target",
        dataIndex: "target_name",
        key: "target_name",
        render: (item, record) => (
          <Tag
            color="blue"
            onClick={() => {
              this.getOne(record);
            }}
          >
            {record["target_name"]}
          </Tag>
        ),
      },
      {
        title: "Uniport id",
        dataIndex: "uniport_id",
        key: "uniport_id",
      },
      {
        title: "action",
        dataIndex: "action",
        key: "action",
      },
      {
        title: "PDB",
        dataIndex: "pdb",
        render: (PDB) => (
          <span>
            {PDB.map((item) => {
              return (
                <Tag
                  color="blue"
                  key={item}
                  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>
        ),
      },
      {
        title: "Reference",
        dataIndex: "reference",
        key: "reference",
        render: (reference, record) => (
          <span>
          {" "}
          {reference.map((item) => {
            return (
              <Tag
                color="blue"
                key={item}
                onClick={() => {
                  this.getReferences2(item);
                }}
              >
                {" "}
                {item}{" "}
              </Tag>
            );
          })}{" "}
        </span>
        ),
      },
    ];
    const columnsCondition = [
      {
        title: "Indication Name",
        dataIndex: "condition",
        key: "condition",
      },
      {
        title: "Synonyms",
        dataIndex: "synonyms",
        key: "synonyms",
        width: 500,
        render: (synonyms, record) => (
          <span>
            {record.TargetState &&
              synonyms.slice(0, 5).map((item, index) => {
                return (
                  <Tag style={{ marginBottom: "1px" }} key={item}>
                    {item.toUpperCase()}
                  </Tag>
                );
              })}
            {!record.TargetState &&
              synonyms.map((item, index) => {
                return (
                  <Tag style={{ marginBottom: "1px" }} key={item}>
                    {item.toUpperCase()}
                  </Tag>
                );
              })}
            {
              <Button
                type="primary"
                className={
                  synonyms.length > 5 && record.TargetState ? "" : "isShowDiv"
                }
                style={{ marginBottom: "5px", marginLeft: "5px" }}
                onClick={() => this.TargetButton(record)}
              >
                查看更多
              </Button>
            }
            {
              <Button
                type="primary"
                className={!record.TargetState ? "" : "isShowDiv"}
                style={{ marginBottom: "5px", marginLeft: "5px" }}
                onClick={() => this.TargetButton2(record)}
              >
                收起
              </Button>
            }
          </span>
        ),
      },
      {
        title: "Clinical phase",
        dataIndex: "phase",
        key: "phase",
      },
      {
        title: "Clinical status",
        dataIndex: "status",
        key: "status",
      },
      {
        title: "Purpose",
        dataIndex: "purpose",
        key: "purpose",
      },
      {
        title: "Description",
        dataIndex: "count",
        key: "count",
        render: (count, record) => (
          <span>
            {count.map((item, index) => {
              return (
                <div style={{ marginBottom: "1px" }} key={index}>
                  {item.title}{" "}
                  <a
                    onClick={() => {
                      this.getIndiCation(item.nct_number);
                    }}
                  >
                    ({item.nct_number})
                  </a>{" "}
                  ,
                </div>
              );
            })}
          </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",
      },
    ];
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 12 },
    };
    return (
      <div className="LigandDetails-div">
        <Modal
          footer={null}
          closable={false}
          width={550}
          visible={visible}
          wrapClassName="vertical-center-modal"
          onCancel={() => this.setState({ visible: false })}
        >
          <div className="Molstar-div">
            <Molstar pdbId={this.state.pdbId} />
          </div>
        </Modal>
        <Modal
          footer={null}
          closable={false}
          width={550}
          visible={visible2}
          wrapClassName="vertical-center-modal"
          onCancel={() => this.setState({ visible2: false })}
        >
          <div className="Molstar-div">
            <Molstar file={this.state.fileData} />
          </div>
        </Modal>
        <Spin tip="Loading..." size="large" spinning={this.state.loading}>
          <Card hoverable>
            <div>
              <div className="title-div">{targetsDetail.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 />
                        {targetsDetail.synonyms}
                      </div>
                      <div className="list-one">
                        <div className="left-title">Drug type</div>
                        <div />
                        {targetsDetail.drug_type}
                      </div>
                      <div className="list-one">
                        <div className="left-title">If_approved</div>
                        <div />
                        {targetsDetail.if_approved}
                      </div>
                      <div className="list-one">
                        <div className="left-title">Description</div>
                        <div />
                        {targetsDetail.description}
                      </div>
                    </div>
                  </div>
                </div>
                <div className="Jsme-div">
                  {targetsDetail.smiles && (
                    <Jsme
                      height="300px"
                      width="300px"
                      options="depict,useopenchemlib"
                      smiles={targetsDetail.smiles}
                    />
                  )}
                </div>
              </div>
            </div>
          </Card>
          {/* {PanelList} */}
          <Collapse
            defaultActiveKey={["1", "2", "3", "4", "5", "6"]}
            onChange={this.callback}
          >
            <Panel header="Target" key="1">
              <Table
                bordered
                rowKey="item"
                dataSource={targetsDetail.Target}
                pagination={false}
                columns={columns}
              />
              <Pagination
                showSizeChanger
                onShowSizeChange={this.onShowSizeChange2}
                onChange={this.onChange2}
                total={total_num}
              />
            </Panel>
            <Panel header="Pharmacological properties" key="5">
              <div className="Calcilated">
                <div className="div-list">
                  <div className="list-one">
                    <div>Absorption:</div>
                    <div />
                    {pharmacological_properties.absorption}
                  </div>
                  <div className="list-one">
                    <div>Clearance:</div>
                    <div />
                    {pharmacological_properties.clearance}
                  </div>
                  <div className="list-one">
                    <div>Distribution: </div>
                    <div />
                    {pharmacological_properties.distribution}
                  </div>
                  <div className="list-one">
                    <div>Elimination:</div>
                    <div />
                    {pharmacological_properties.elimination}
                  </div>
                  <div className="list-one">
                    <div>Half Life: </div>
                    <div />
                    {pharmacological_properties.half_life}
                  </div>
                  <div className="list-one">
                    <div>metabolism: </div>
                    <div />
                    {pharmacological_properties.metabolism}
                  </div>
                  <div className="list-one">
                    <div>Toxicity: </div>
                    <div />
                    {pharmacological_properties.toxicity}
                  </div>
                </div>
              </div>
            </Panel>

            <Panel header="Products" key="2">
              <Table
                bordered
                rowKey="item"
                dataSource={targetsDetail.Products}
                pagination={false}
                columns={columnsProducts}
              />
              <Pagination
                showSizeChanger
                onShowSizeChange={this.onShowSizeChange}
                onChange={this.onChange}
                total={total_num2}
              />
            </Panel>
            <Panel header="Calculated propeties" key="3">
              <div>
                <div className="Calcilated">
                  {Object.entries(CalculatedPropeties).map((item, index) => {
                    return (
                      <div className="list-one2" key={index}>
                        <div>{item[0]}:</div>
                        <div />
                        {item[1]}
                      </div>
                    );
                  })}
                </div>
              </div>
            </Panel>

            {}
            <Panel header="Structure" key="4">
              <Tabs
                defaultActiveKey="0"
                type="card"
                tabPosition="left"
                onChange={this.ChangeTabs}
              >
                {targetsDetail.Structure.map((item, index) => {
                  return (
                    <TabPane tab={item.pdb} key={item.pdb}>
                      <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, index) => {
                                    return (
                                      <Popover
                                        content={
                                          <div>
                                            <div
                                              key={index}
                                              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, index) => {
                                      return (
                                        <Option key={index} 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, index) => {
                                    return (
                                      <Button
                                        type="primary"
                                        onClick={() => {
                                          this.getReferences2(item);
                                        }}
                                        key={index}
                                        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}
                                disabled={
                                  getStructureList.ligand_list.length === 0
                                }
                                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>
    );
  }
}
