import React from 'react';
import { Icon, Row, Col, Button, Pagination } from 'antd';
import {
  WeaLocaleProvider,
  WeaNewScroll,
  WeaTools,
  WeaDialog,
  WeaTab,
  WeaInput,
  WeaDatePicker
} from 'ecCom';
import { WeaMessageCenter } from 'comsMobx';
import '../style/search.css';

const SingleMessage = WeaMessageCenter.SingleMessage;
const getLabel = WeaLocaleProvider.getLabel;

export default class Entrance extends React.Component {
  constructor(props) {
    super(props);

    const params = this.getFrameParams();

    this.state = {
      syncComponent: () => null,
      msgList: [],
      refresh: false,
      loading: true,
      tabFlag: '0',
      tabData: [],
      tabSelectedKey: '0',
      msgid: '0',
      current: '0',
      maxtime: '0',
      mintime: '0',
      newGetMsgList: [],
      typeId: params.typeId,

      searchDialogVisible: false,
      searchParams: {
        searchValue: "",
        fromDate: "",
        toDate: "",
        pageSize: 20,
        page: 1
      },
      searchListDatas: [],
      searchListTotal: '',
      showHighLight: false,
      searchLoading: false,
      changePage: 1
    };

    this.searchListScroll = null;
    this.getMsgList = this.getMsgList.bind(this);
    this.getMsgTypeTabs = this.getMsgTypeTabs.bind(this);
  }

  componentDidMount() {
    let params = { id: this.state.typeId };

    this.getMsgTypeTabs(params);

    if (window.em) {
      em.ready(() => {
        em.pageVisible((visible) => {
          if (visible) {
            this.setState({ refresh: true }, () => {
              this.getMsgList(0, 0, 0,
                () => {
                  WeaTools.callApi('/api/msgcenter/homepage/setMsgRead', 'GET', params);
                }, true, true, true);
            });
          }
        });
      });
    } else {
      console && console.log('em未加载');
    }
  }

  getMsgTypeTabs(params) {
    const { tabData, typeId, current, msgid, mintime, tabSelectedKey } = this.state;
    let typeParams = { typeId };
    WeaTools.callApi('/api/msgcenter/homepage/GetMsgTypeTabs', 'GET', typeParams).then((res) => {
      if (res.datas.length) {
        let datas = JSON.parse(
          JSON.stringify(res.datas)
            .replace(/id/g, 'viewcondition')
            .replace(/tabName/g, 'title'),
        );
        this.setState({
          tabData: datas,
          tabFlag: '1',
          tabSelectedKey: datas[0].viewcondition,
        });
      }
    }).finally(() => {
      this.getMsgList(
        tabData.length ? tabSelectedKey : current,
        msgid,
        mintime,
        () => {
          this.scroll.refs.weaBaron.scrollToLast();
          WeaTools.callApi('/api/msgcenter/homepage/setMsgRead', 'GET', params);
        },
        false, false, true,
      );
    });
  }

  uniqueByKey = (arr,u_key) => {
    let map = new Map()
    arr.forEach(item => {
      if (!map.has(item[u_key])){
        map.set(item[u_key],item)
      }
    })
    return [...map.values()]
  }

  getMsgList(
    index,
    msgid1,
    mintime1,
    cb,
    scroll = false,
    isUpdateMaxTime = true,
    isInit = false,
  ) {
    let bizstate = '';
    // 有分页
    if (this.state.tabFlag === '1') {
      this.state.tabData.forEach((item) => {
        if (
          item.viewcondition === this.state.tabSelectedKey &&
          item.msgStateId
        ) {
          bizstate = item.msgStateId;
        }
      });
    }

    this.setState({ loading: true });
    let params = {
      id: index,
      pagesize: 20,
      msgid: msgid1,
      mintime: mintime1,
      bizstate,
      ismobile: 1,
    };

    if (this.state.typeId) {
      params.typeId = this.state.typeId;
    }

    params.selectState = '';
    if (this.state.tabData.length && params.bizstate) {
      const filterSelect = this.state.tabData.filter(item => item.msgStateId === params.bizstate);

      params.selectState = filterSelect[0] ? filterSelect[0].selectState : '';
    }

    WeaTools.callApi('/api/msgcenter/homepage/getMsgList', 'POST', params).then((res) => {
      if (res.data) {
        let msgList = [];
        let allKeyArr = [];

        if (isInit && res.data.length === 0) {
          if (this.state.tabFlag === '1') {
            this.state.tabData.forEach((item) => {
              if (!item.msgStateId) {
                allKeyArr.push(item.viewcondition);
              }
            });
            this.setState({ tabSelectedKey: allKeyArr[0] || this.state.tabData[0].viewcondition }, () => {
              this.getMsgList(this.state.tabSelectedKey, msgid1, mintime1, cb, scroll, isUpdateMaxTime);
            });
          }
          this.setState({ loading: false });
          return;
        }

        if (this.state.refresh) {
          msgList = res.data.length > 0 ? res.data : [];
        } else {
          msgList = [...res.data, ...this.state.msgList];
        }

        setTimeout(() => {
          this.setState({ loading: false });
        }, 300);
        this.setState({
          mintime: res.mintime,
          msgid: res.msgid,
          refresh: false,
          newGetMsgList: res.data,
          msgList: this.uniqueByKey(msgList, 'messageid')
        }, () => {
          if (scroll) {
            const msgNode = document.getElementsByClassName('wea-messageCenter-singleItem');
            let scrollHeight = 0;

            if (msgNode && msgNode.length > 0 && res.data.length > 0) {
              for (let i = 0; i < res.data.length; i++) {
                scrollHeight += msgNode[i].offsetHeight;
              }
            }

            // console.log(this.scroll.refs);
            window.scroll = this.scroll;
            window.scroll.refs.weaBaron.getScroller().scrollTop = scrollHeight;
            // this.scroll.refs.weaBaron.scroll(4000);
          }
        });

        if (isUpdateMaxTime) {
          this.setState({
            maxtime: res.maxtime,
          });
        }
        if (cb && typeof cb === 'function') {
          cb(res);
        }
        // this.getMsgCount(this.state.mintime);
      }
    });
  }

  getFrameParams() {
    let url = window.location.href;
    try {
      if (window.frameElement) {
        url = window.frameElement.src;
      }
    } catch (error) {

    }
    let urlParams = url.slice(url.indexOf('?') + 1).split('&');
    let params = [];
    urlParams.forEach((element) => {
      let datas = element.split('=');
      params[datas[0]] = datas[1];
    });
    let host = url.slice(0, url.indexOf('/spa/'));
    params.host = host;
    return params;
  }

  updateSyncCom(com) {
    this.setState(
      {
        syncComponent: com,
      },
      () => {
        this.forceUpdate();
      },
    );
  }

  getSearchMsgList = (pageSet = false) => {
    const { searchParams, typeId: id, changePage } = this.state;

    this.setState({
      searchLoading: true,
      searchParams: {
        ...searchParams,
        page: pageSet ? changePage : 1,
      },
      changePage: pageSet ? changePage : 1,
    });

    WeaTools.callApi("/api/msgcenter/homepage/getSearchMsgList", "POST", { ...searchParams, id, page: pageSet ? changePage : 1 }).then(res => {
      if (res.status) {
        this.setState({
          searchListDatas: res.data,
          searchListTotal: res.count,
          showHighLight: true
        }, () => {
          this.setState({ searchLoading: false });
          setTimeout(() => {
            this.searchListScroll &&
            this.searchListScroll.refs.weaBaron.scrollToLast()
          }, 100);
        });
      }
    });
  };

  renderDialog = () => {
    const { searchDialogVisible, searchParams, searchListDatas, searchListTotal, showHighLight, searchLoading } = this.state;
    const cls = "wea-messageCenter-search-dialog";
    return (
      <WeaDialog
        title={getLabel("529406", "查找消息")}
        className={cls}
        visible={searchDialogVisible}
        style={{ width: 830, zIndex: 999999 }}
        onCancel={() => this.setState({ searchDialogVisible: false })}
        hasScroll
      >
        <div className={`${cls}-content`}>
          <div className={`${cls}-content-search`}>
            <Row style={{ textAlign: 'center', lineHeight: '37px' }}>
              <Col span={5}>
                <WeaInput
                  id="searchInput"
                  placeholder={getLabel(83788, "请输入关键字搜索")}
                  value={searchParams.title}
                  onEnter={this.getSearchMsgList}
                  onChange={value => {
                    this.setState({
                      searchParams: { ...searchParams, title: value },
                      showHighLight: false,
                      changePage: 1
                    });
                  }}
                />
              </Col>
              <Col span={15} style={{ marginLeft: "20px" }}>
                <Row>
                  <Col span={12}>
                    <WeaDatePicker
                      value={searchParams.fromDate}
                      placeholder={getLabel("529408", "请选择开始日期")}
                      viewAttr={2}
                      onChange={value =>
                        this.setState({
                          searchParams: { ...searchParams, fromDate: value },
                          changePage: 1
                        })
                      }
                    />
                  </Col>
                  <Col span={12}>
                    <WeaDatePicker
                      value={searchParams.toDate}
                      placeholder={getLabel("529409", "请选择结束日期")}
                      viewAttr={2}
                      onChange={value =>
                        this.setState({
                          searchParams: { ...searchParams, toDate: value },
                          changePage: 1
                        })
                      }
                    />
                  </Col>
                </Row>
              </Col>
              <Col span={1} style={{ marginLeft: "30px" }}>
                <Button type="primary" onClick={this.getSearchMsgList} style={{ marginBottom: "3px" }}>
                  {getLabel("388113", "搜索")}
                </Button>
              </Col>
            </Row>
          </div>
          {
            searchLoading ? (
              <Icon type="loading" />
            ) : (
              Array.isArray(searchListDatas) && searchListDatas.length > 0 ? (
                <React.Fragment>
                  <WeaNewScroll
                    ref={e => {
                      this.searchListScroll = e;
                    }}
                    height={430}
                  >
                    <div className={`${cls}-content-list`}>
                      {searchListDatas.map(data => {
                        return (
                          <SingleMessage
                            {...data}
                            showHighLight={showHighLight}
                            imgSrc={data.showimage || ""}
                            name={data.name || ""}
                            time={data.time || ""}
                            link={data.link || ""}
                            title={data.title || ""}
                            context={data.context || ""}
                            searchValue={searchParams.title}
                          />
                        );
                      })}
                    </div>
                  </WeaNewScroll>
                  <Pagination
                    total={searchListTotal}
                    showQuickJumper
                    showSizeChanger
                    pageSizeOptions={["20", "30", "40", "50"]}
                    showTotal={total => `${getLabel("83698", "共")}${searchListTotal}${getLabel(
                      "128218",
                      "条"
                    )}`}
                    pageSize={searchParams.pageSize}
                    current={searchParams.page}
                    defaultCurrent={searchParams.page}
                    onShowSizeChange={(page, pageSize) =>
                      this.setState(
                        { searchParams: { ...searchParams, page, pageSize }, changePage: page },
                        () => this.getSearchMsgList()
                      )
                    }
                    onChange={v =>
                      this.setState(
                        { searchParams: { ...searchParams, page: v }, changePage: v },
                        () => this.getSearchMsgList(true)
                      )
                    }
                  />
                </React.Fragment>
              ) : (
                <div className={`${cls}-content-nodata`}>{getLabel("529411", "暂无匹配消息数据")}</div>
              )
            )
          }
        </div>
      </WeaDialog>
    );
  };

  render() {
    return (
      <WeaLocaleProvider>
        <this.state.syncComponent />
        <div className='wea-message-entrance has-tab'>
          <div
            // style={{
            //   display: this.state.tabFlag === '1' ? 'block' : 'none',
            // }}
            className="sticky-top-tab"
          >
            <WeaTab
              datas={this.state.tabData}
              keyParam="viewcondition" // 主键
              countParam="groupid" // 数量
              selectedKey={this.state.tabSelectedKey}
              onChange={(v) => {
                this.setState({ tabSelectedKey: v, refresh: true }, () => {
                  this.getMsgList(this.state.current, 0, 0, null, true);
                });
              }}
              buttons={[
                <i
                  className="icon-coms-search wea-messageCenter-list-search"
                  title={getLabel("529406", "查找消息")}
                  onClick={() =>
                    this.setState({
                        searchDialogVisible: true,
                        searchParams: {
                          title: '',
                          fromDate: "",
                          toDate: "",
                          pageSize: 20,
                          page: 1
                        },
                        changePage: 1
                    }, () => {
                      this.getSearchMsgList()
                      setTimeout(() => {
                        const doms = document.getElementsByClassName('wea-messageCenter-search-dialog')
                        if(doms[0]) {
                          doms[0].style.zIndex = '999999 !important'
                        }
                      }, 1000)
                    })
                  }
                />
              ]}
            />
          </div>
          <WeaNewScroll
            ref={e => (this.scroll = e)}
            height={'100%'}
          >
            {this.state.msgList.length === 0 && !this.state.loading ? (
              <div className="wea-messageCenter-nomsg">
                <div className="nomsg-container">
                  <span style={{ fontSize: 80 }}>
                    <i className="icon-coms-blank" />
                  </span>
                  <br />
                  {getLabel(502494, '暂无消息')}
                </div>
              </div>
            ) : (
                <div className="click-look-more">
                  <span>
                    {this.state.loading ? (
                      <Icon type="loading" />
                    ) : (
                        <React.Fragment>
                          {this.state.newGetMsgList.length > 2 ? (
                            <span
                              onClick={() => {
                                this.getMsgList(
                                  this.state.current,
                                  this.state.msgid,
                                  this.state.mintime,
                                  null,
                                  true,
                                  false,
                                );
                              }}
                            >
                              <Icon type="clock-circle-o" />
                              <a href="javascript:void(0);"> {getLabel(384653, '点击加载更多')} </a>
                            </span>
                          ) : (
                              <span className="no-more">{getLabel(390064, '没有更多啦')}</span>
                            )}
                        </React.Fragment>
                      )}
                  </span>
                </div>
              )}
            {this.state.msgList.length > 0 &&
              this.state.msgList.map(data => (
                  <SingleMessage
                    {...data}
                    imgSrc={data.showimage || ''}
                    name={data.name || ''}
                    time={data.time || ''}
                    link={data.link || ''}
                    title={data.title || ''}
                    context={data.context || ''}
                    updateSyncCom={com => this.updateSyncCom(com)}
                  />
                ))}
          </WeaNewScroll>
        </div>
        {this.renderDialog()}
      </WeaLocaleProvider>
    );
  }
}

