import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
import { Badge, Button, Checkbox, Menu, Pagination } from 'antd';
import DelModal from '../../../Component/ModalFun';
import NoneData from '../../../Nodata.js';
import { noticeSourceType } from '../../../common/static';
import './Index.scss';
import '../manager/Index.scss'

function MyNotice(props) {
  let { current_user, resetUserInfo, location, mygetHelmetapi, history}= props;
  //消息悬停框选择tab
  let popover = location && location.query && location.query.noticeType;
  let pageSize = 15;
  const [noticeType, setNoticeType] = useState(popover==="atme"?"2":"0");//消息类别tab栏选择
  const [selectedNum, setSelectedNum] = useState(0);//@我批量删除选择消息条数
  const [isBatchDelete, setIsBatchDelete] = useState(false);//@我是否批量删除
  const [batchDeleteCheckedAll, setBatchDeleteCheckAll] = useState(false);//@我批量删除--全选

  const [noticeUnreadCount, setNoticeUnreadCount] = useState();//未读系统通知数量
  // const [letterUnreadCount, setLetterUnreadCount] = useState(0);//未读私信数量
  const [atUnreadCount, setAtUnreadCount] = useState();//未读@我数量
  const [messageList, setMessageList] = useState([]);
  const [messTotalCount, setMessTotalCount] = useState();//消息总数
  const [currentPage, setCurrentPage] = useState(1);//当前页数
  const [onlyUnread, setOnlyUnread] = useState();

  //登录情况下，通过地址访问，直接跳转：/settings/profile
  //未登录情况下，通过地址访问，直接跳转：/explore
  useEffect(()=>{
    let notice = mygetHelmetapi && mygetHelmetapi.common && mygetHelmetapi.common.notice;
    let login = current_user && current_user.login;
    if(!login){
      history.push(`/explore`);
    }else if(!notice){
      history.push(`/settings/profile`);
    }
  },[mygetHelmetapi])

  useEffect(()=>{
    popover==="atme" ? setNoticeType("2"):setNoticeType("0");
  },[popover])

  useEffect(()=>{
    resetUserInfo();
  },[noticeUnreadCount,atUnreadCount])

  useEffect(() => {
    getMessageList();
  }, [noticeType, onlyUnread, currentPage, current_user])

  function getMessageList() {
    const params = {
      type: noticeType === "0" ? "notification" : noticeType === "2" ? "atme" : "",
      status: onlyUnread ? onlyUnread : "",
      limit: pageSize,
      page: currentPage,
    };
    current_user && axios.get(`/users/${current_user.login}/messages.json`, {
      params: params,
    }).then((response) => {
      if(response && response.data){
        setNoticeUnreadCount(response.data.unread_notification);
        setAtUnreadCount(response.data.unread_atme);
        setMessageList(response.data.messages);
        setMessTotalCount(response.data.total_count);
      }
    });
  }

  function readNotice(id){
    if(id && current_user){
      const params = {
        type: noticeType === "0" ? "notification" : noticeType === "2" ? "atme" : "",
        ids:id,
      };
      axios.post(`/users/${current_user.login}/messages/read.json`,params).then((response)=>{
        if(response.status === 200){
          getMessageList();
          //已读当前页码最后一条数据时跳转到前一页
          let totlaPage = Math.ceil((messTotalCount-1)/pageSize);
          setCurrentPage(currentPage>=totlaPage? totlaPage : currentPage);
        }
      });
    }
  }

  function handleClick(e) {
    setNoticeType(e.key);
    setCurrentPage(1);
    setOnlyUnread();
    if (e.key != "2") {
      setIsBatchDelete(false);
    }
  }

  function onChange(e) {
    var checkboxNum = 0;
    let messageListNew=messageList.slice();
    messageListNew.map((item)=>{
      if(item.id===e.target.value){
        item.checkedBatch = e.target.checked;
      }
      item.checkedBatch?checkboxNum++:"";
    });
    setMessageList(messageListNew);
    setSelectedNum(checkboxNum);
    setBatchDeleteCheckAll(checkboxNum === messageList.length);
  }


  function onChangeAll(e) {
    setBatchDeleteCheckAll(e.target.checked);
    setSelectedNum(e.target.checked?messageList.length:0);
    let messageListNew=messageList.slice();
    messageListNew.map((item)=>{
      item.checkedBatch = e.target.checked;
    });
    setMessageList(messageListNew);
  }

  function deleteNotice(id) {
    const ids = [];
    if(!id){
      messageList.map(item=>{
        item.checkedBatch && ids.push(item.id);
      });
    }
    DelModal({
      title: noticeType === "1" ? '删除私信用户' : id ? '删除消息' : '批量删除',
      contentTitle: noticeType === "1" ? '您确定要删除与 xxx 的聊天吗？' : id ? '您确定要删除这条@我消息吗？' : '您确定要删除选中的' + selectedNum + '条消息吗？',
      content: noticeType === "1" ? '此操作将删除与xxx的聊天框和xxx的所有聊天记录，请进行确认以防数据的丢失' : id ? '此操作将删除这条消息，请进行确认以防数据的丢失' : '此操作将删除选中的' + selectedNum + '条消息，请进行确认以防数据的丢失',
      onOk: () => {
        const params = {
          type: noticeType === "0" ? "notification" : noticeType === "2" ? "atme" : "",
          ids:id?id:ids,
        };
        axios.delete(`/users/${current_user.login}/messages.json`,{
          data:params,
        }).then((response)=>{
          if(response.status === 200){
            getMessageList();
            //删除当前页码最后一条数据时跳转到前一页
            let totlaPage = Math.ceil((messTotalCount-1)/pageSize);
            setCurrentPage(currentPage>=totlaPage? totlaPage : currentPage);
            setSelectedNum(0);
            setBatchDeleteCheckAll(false);
          }
        });
      }
    });
  }

  function cancelBatchDelete(){
    setIsBatchDelete(false);
    setSelectedNum(0);
    //取消选中效果
    let messageListNew=messageList.slice();
    messageListNew.map((item)=>{
      item.checkedBatch = false;
    });
    setMessageList(messageListNew);
    setBatchDeleteCheckAll(false);
  }

  //跳转到消息详情页面
  function turnToMess(item){
    if(item.notification_url){
      window.open(`${item.notification_url}`);
      readNotice([item.id]);
    }
  }

  return (
    <div className="notice01">
      <div className="sshHead">
        <Menu mode="horizontal" selectedKeys={noticeType} onClick={handleClick}>
          <Menu.Item key="0"><Badge count={noticeUnreadCount} title="">系统通知</Badge></Menu.Item>
          {/* <Menu.Item key="1" id="item-private"><Badge count={0}>私信</Badge></Menu.Item> */}
          <Menu.Item key="2"><Badge count={atUnreadCount}>@我</Badge></Menu.Item>
        </Menu>
        {(noticeType==="0" && noticeUnreadCount>0) || (noticeType==="2"&& atUnreadCount>0) ? <button className="but25" onClick={()=>{readNotice([-1])}}>所有{noticeType === "0" ? "系统通知" : noticeType === "1" ? "私信" : "@我"}一键已读</button>:""}
      </div>

      <div className={isBatchDelete ? "invisible " : "visible"}>
        <div className="vertical-center-style">
          {onlyUnread===1 || messageList &&  messageList.length>0 ? <Checkbox checked={onlyUnread} onChange={(e) => e.target.checked ? setOnlyUnread(1) : setOnlyUnread()}>仅看未读{noticeType === "1" ? `私信（12）` : noticeType === "0" ? `消息（${noticeUnreadCount}）` : `消息（${atUnreadCount}）`}</Checkbox>:""}
        </div>
        {noticeType === "2" && messageList &&  messageList.length > 0 ? <button className="batchDeleteBut" onClick={() => { setIsBatchDelete(true); }}>批量删除</button> : ""}
      </div>

      {messageList && messageList.length===0 ? <NoneData _html="暂无相关消息"/>:""}

      {messageList && messageList.length>0 && <div className={isBatchDelete ? 'visible' : 'invisible'}>
        <div className="vertical-center-style">
          <Checkbox onChange={onChangeAll} checked={batchDeleteCheckedAll}>全选</Checkbox>
          &nbsp;&nbsp;&nbsp;已选择&nbsp;<span className="numberSpan">{selectedNum}</span>&nbsp;项
        </div>
        <div>
          <button onClick={cancelBatchDelete}>取消</button>&nbsp;&nbsp;&nbsp;&nbsp;
          <button className="deleteBut" onClick={selectedNum > 0 ? ()=>deleteNotice() : () => { }}>删除</button>
        </div>
      </div>}

      {messageList && messageList.map(item => {
        // 系统消息
        if (noticeType === "0") {
          // 消息类别
          return (
            <div className="mynotice-content vertical-center-style" key={item.id}>
              <div className="mynotice-cont stretch-style">
                {item.status === 1 ? <Badge color="#FA2020" /> : <span className="system-notice-blank"></span>}
                <i className={"iconfont "+noticeSourceType[item.source]}></i>
                <span className={`sysNotice-length ${item.notification_url?'highlightSpan':''}`} onClick={() => {turnToMess(item)}} dangerouslySetInnerHTML={{__html: item.content}}></span>
              </div>
              <div className="mynotice-cont vertical-center-style float-left-little">
                <span className={item.status === 1?"timeSpan":""}>{item.time_ago}</span>
                {item.status === 1 && <span className="invisable-read" onClick={()=>readNotice([item.id])}>标记为已读</span>}
              </div>
            </div>
          )
        } else if (noticeType === "2") {
          //@我
          return (
            <div className={`mynotice-content vertical-center-style ${isBatchDelete?'batchDel':''}`} key={item.id}>
              <div className="mynotice-cont vertical-center-style">
                <Checkbox value={item.id} className={isBatchDelete ? 'visible-checkbox' : 'invisible-checkbox'} onChange={onChange} checked={item.checkedBatch}></Checkbox>
                {item.sender && <img src={`https://testforgeplus.trustie.net//${item.sender.image_url}`} className="currentImg" onClick={()=>{window.open(`/${item.sender && item.sender.login}`);}}/>}
                <div className={`atme-notice-text stretch-style ${item.notification_url && 'highlightSpan'}`} onClick={() => {turnToMess(item)}}>
                  {item.status === 1 ? <Badge color="#FA2020"/> : <span className="system-notice-blank"></span>}
                  {item.sender && <span className="atme-length" dangerouslySetInnerHTML={{__html: "<b class = 'atme-notice-name'>" + item.sender.name+ "</b>    "+ item.content +"  中@我"}}></span>}
                </div>
              </div>
              <div className="mynotice-cont vertical-center-style">
                <span className={!isBatchDelete && item.status === 1?"timeSpan":""}>{item.time_ago}</span>
                {!isBatchDelete && item.status === 1 && <span className="invisable-read" onClick={()=>readNotice([item.id])}>标记为已读</span>}&nbsp;&nbsp;&nbsp;
                {!isBatchDelete && <span className="invisable-read float-left-little" onClick={()=>deleteNotice([item.id])}>删除</span>}
              </div>
            </div>
          )
        } else{
          //私信
          {/* <div className="mynotice-content vertical-center-style">
            <Badge count={95}><img src="https://testforgeplus.trustie.net//system/lets/letter_avatars/2/D/208_124_118/120.png" className="currentImg private-letter-img" /></Badge>
            <div className="private-letter-right">
              <div>
                <span>蒋宇航</span>
                <span className="timeSpan">4分钟前</span>
                <a onClick={deleteNotice}>删除</a>
              </div>
              <div onClick={() => props.history.push('/settings/notice/privateLetter')}>
                <span className="highlightSpan letter-length-limit">最好的OpenStack控制台，对标OpenStack社区Horizon项目,最好的OpenStack控制台，对标OpenStack社区Horizon项目，在易用性、页面性能等方面进行深度优化，提供简单控制台。</span>
              </div>
            </div>
          </div> */}
        }
      })}

      {/* 分页 */}
      {!isBatchDelete && <div className="paging">
        <Pagination
          simple
          current = {currentPage}
          pageSize={pageSize}
          onChange={(page)=>{setCurrentPage(page)}}
          total = {messTotalCount}
          hideOnSinglePage
        ></Pagination>
      </div>}
    </div>
  )
}
export default MyNotice;