import React, { useEffect, useState } from "react";
import styles from "./style.less";
import { observer, observable } from "mobx-react";
import { useHistory, useLocation } from "react-router-dom";
import $store from "@store/";
import { useRef } from "react";
import { timeDiffer, dealDiffSheetType } from "@utils/util";
import PropTypes from "prop-types";
import { Tabs, List, Radio, Tooltip, Modal, Button, message, Form } from "antd";
import {
  getAccountMsgPage,
  getMenuDesc,
  getReportInfo,
  setReadStatus,
  getAccountResourceVoByResourceId,
  getUnReadMessageNum,
} from "../../apis/personal";
import { switchPage, getUnionId } from "@apis/common.js";

// newResourceMsg  ：报表上新
// fineReportChange ：报表内容更新
// fineDataResourceChange ：报表元数据更新
// 权限通知：
const messageType = [
  "newResourceMsg",
  "fineReportChange",
  "fineDataResourceChange",
];

export default observer(function (props) {
  const history = useHistory();
  const [tabNum, settabNum] = useState(1);
  const [messageList, setMessageList] = useState([]); /**消息通知列表 */
  const [isShowDetail, setIsShowDetail] = useState(
    false
  ); /**控制 详情消息弹出 */
  const [msgDetail, setMsgDetail] = useState({}); /**消息通知 当条 点击详情 */
  const [reportName, setReportName] = useState(""); /**消息弹窗-相关报表名字 */
  const [hasPermission, setHasPermission] = useState(
    false
  ); /**消息弹窗-去看看权限 */

  //表单配置
  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 },
  };

  const options = [
    { label: "系统公告", value: 1 },
    { label: "权限通知", value: 2 },
  ];

  const subMenuList = [
    {
      defaultOpen: true,
      openType: "self",
      parentId: null,
      resourceCode: null,
      resourceId: "",
      resourceList: [],
      resourceType: "sys",
      sortNo: "2",
      status: true,
      sysResource: false,
      topParentId: "",
      resourceIcon: "RadarChartOutlined",
      resourceName: "个人信息",
      resourceUrl: "/home/center",
    },
    {
      defaultOpen: true,
      openType: "self",
      parentId: null,
      resourceCode: null,
      resourceId: "",
      resourceList: [],
      resourceType: "sys",
      sortNo: "2",
      status: true,
      sysResource: false,
      topParentId: "",
      resourceIcon: "DatabaseOutlined",
      resourceName: "消息通知",
      resourceUrl: "/home/message",
    },
    // {
    //   defaultOpen: true,
    //   openType: "self",
    //   parentId: null,
    //   resourceCode: null,
    //   resourceId: "",
    //   resourceList: [],
    //   resourceType: "sys",
    //   sortNo: "2",
    //   status: true,
    //   sysResource: false,
    //   topParentId: "",
    //   resourceIcon: "ApartmentOutlined",
    //   resourceName: "权限申请记录",
    //   resourceUrl: "/home/right",
    // },
  ];

  function calcValue(str) {
    if (str === "sysToken") {
      return `${sessionStorage.getItem("token")}$`;
    }
  }
  const chooseTab = (e) => {
    //console.log("e",e.target.value);
    settabNum(e.target.value);
  };

  useEffect(() => {
    getMessageList();
  }, []);

  /**获取 消息通知列表 */
  const getMessageList = () => {
    let accountId = sessionStorage.getItem("accountId");
    let config = {
      accountId,
      messageType: ["System_bulletin", "Permission_msg"],
    };
    getAccountMsgPage(config).then(({ data, resultCode }) => {
      if (+resultCode === 0) {
        data.records.map((item) => {
          item.messageDetailTitle = item.messageDetailTitle.replace(
            /\\n/g,
            " "
          );
          item.messageContent = item.messageContent.replace(/\\n/g, "\n");
        });
        setMessageList(data.records.slice(0, 3));
      }
    });
  };
  //处理 消息 详情
  const goHandleMessage = () => {
    if (!hasPermission) {
      message.warning("该报表无权限!");
      return;
    }
    const { messageDetailType, messageContentObjectId } = msgDetail || {};
    switch (messageDetailType) {
      case "fineDataResourceChange":
        //根据id 找到 该元数据
        getMenuDesc({ resourceId: messageContentObjectId }).then(
          ({ data, resultCode }) => {
            if (+resultCode === 0) {
              $store.app.setMetaData({
                data,
                visible: true,
              });
            }
          }
        );
        break;
      case "fineReportChange":
        getReportInfo({ resourceId: messageContentObjectId }).then(
          ({ data, resultCode }) => {
            if (+resultCode === 0) {
              switchPage({
                // pageId: relationship[key].pageId,
                modelName: data.resourceName,
                pageName: data.resourceName,
                pageUrl: data.resourceUrl,
                resourceId: data.resourceId,
                visitId: sessionStorage.getItem("unionId"),
              });
              let dataOpt = {
                id: data.resourceId,
                name: data.resourceName,
                openType: "self",
                path: data.resourceUrl,
                type: data.resourceType,
              };

              dealDiffSheetType(data).then((response) => {
                $store.app.setNavList({ ...dataOpt });
                $store.app.setCurNav(dataOpt.path);
                if (response.type === "sys") {
                  history.push(response.link);
                } else {
                  history.push(`/home/outer/${response.activeItem.resourceId}`);
                }
              });
            }
          }
        );
        break;
    }
  };

  //获取 未读消息的数量
  const getUnReadNum = () => {
    let accountId = sessionStorage.getItem("accountId");
    getUnReadMessageNum(accountId).then(({ data, resultCode }) => {
      if (+resultCode === 0) {
        $store.app.setNewsCount(+data);
      }
    });
  };

  //更改消息状态
  const changeReadStatus = (msgId) => {
    let accountId = sessionStorage.getItem("accountId");
    const config = {
      accountId,
      messageIds: [msgId],
    };
    setReadStatus({ ...config });
  };

  //获取 相关报表
  const getReportDetail = (id) => {
    if (!id) {
      return;
    }
    getAccountResourceVoByResourceId({ resourceId: id }).then(
      ({ data, resultCode }) => {
        if (+resultCode === 0) {
          setReportName(data.resourceName);
          setHasPermission(data.hasPermission);
        }
      }
    );
  };

  const {
    messageDetailType,
    messageContentObjectId,
    createTime,
    messageContent,
  } = msgDetail || {};

  return (
    <div className={styles.right_park}>
      {Array.isArray(messageList) && messageList.length > 0 ? (
        <div className="right_park_title">
          <div className="title_left">消息通知</div>
          <div
            className="go_more"
            onClick={() => {
              let dataOpt = {
                id: 122,
                name: "消息通知",
                openType: "self",
                path: "/home/message",
                type: "sys",
              };
              sessionStorage.setItem("curNav", "/home/message");
              sessionStorage.setItem("activedUrl", "/home/message");
              $store.sysMenu.setSubmenuList(subMenuList);
              $store.app.setActivedUrl("/home/message");
              let arr = $store.app.navList.slice(1);
              arr.push(dataOpt);
              $store.app.setNavList(arr, "set");
              $store.app.setCurNav("/home/message");
              history.push("/home/message");
              //埋点记录
              switchPage({
                // pageId: relationship[key].pageId,
                modelName: "消息通知",
                pageName: "消息通知",
                pageUrl: "/home/message",
                resourceId: "10000001",
                visitId: sessionStorage.getItem("unionId"),
              });
            }}
          >
            更多 &gt;
          </div>
          {/* <div className="clear"></div> */}
        </div>
      ) : (
        <></>
      )}

      {/* tab 切换-系统公告 权限通知 */}
      {/* <Radio.Group
        options={options}
        onChange={chooseTab}
        value={tabNum}
        optionType="button"
      /> */}
      <div className="message_list">
        {Array.isArray(messageList) && messageList.length > 0 ? (
          messageList.map((item) => {
            return (
              <>
                <div className="message_item" key={item.messageId}>
                  <Tooltip
                    placement="top"
                    title={
                      item.messageDetailTitle.length > 20
                        ? item.messageDetailTitle
                        : ""
                    }
                  >
                    <span
                      className={
                        item.messageReadStatus
                          ? "message_desc"
                          : "isBlod message_desc"
                      }
                      onClick={() => {
                        setMsgDetail(item);
                        setIsShowDetail(true);
                        messageType.includes(item.messageDetailType)
                          ? getReportDetail(item.messageContentObjectId)
                          : "";
                        //更改消息状态（点开 -》 已读）
                        changeReadStatus(item.messageId);
                        // getUnReadNum();
                      }}
                    >
                      {item.messageDetailTitle}
                    </span>
                  </Tooltip>
                  <span className="msg_time">
                    {timeDiffer(item.createTime)}
                  </span>
                </div>
              </>
            );
          })
        ) : (
          <>
            <div className="message_null">
              <img
                src={require("@assets/imgs/messgae_null.png").default}
                width={100}
              />
              <div className="noMsg_desc">暂无消息</div>
            </div>
          </>
        )}
      </div>

      {/* 点击消息详情 对话框 */}
      <Modal
        title="消息通知"
        visible={isShowDetail}
        onCancel={() => {
          setIsShowDetail(false);
          //关闭对话框-更新top实时小红点数量
          // getUnReadNum();
          getMessageList();
        }}
        footer={
          <Button
            type="primary"
            key="goHandle"
            onClick={goHandleMessage}
            disabled={
              messageDetailType === "newResourceMsg" ||
              messageDetailType === "permissionOverDueSoon"
                ? true
                : false
            }
          >
            {messageDetailType === "newResourceMsg"
              ? "申请权限"
              : messageDetailType === "permissionOverDueSoon"
              ? "续期"
              : "去看看"}
          </Button>
        }
      >
        <Form {...formItemLayout}>
          <Form.Item
            label="消息时间"
            style={{ fontWeight: 600, marginBottom: 8 }}
          >
            <span style={{ fontWeight: 400 }}>{createTime}</span>
          </Form.Item>
          {messageDetailType === "fineReportChange" && (
            <Form.Item
              label="相关报表"
              style={{ fontWeight: 600, marginBottom: 8 }}
            >
              <span style={{ fontWeight: 400 }}>{reportName}</span>
            </Form.Item>
          )}
          <Form.Item
            label="消息内容"
            style={{ fontWeight: 600, marginBottom: 8 }}
          >
            <div
              style={{
                fontWeight: 400,
                whiteSpace: "pre-wrap",
                paddingTop: 5,
                paddingBottom: 5,
              }}
            >
              {messageContent}
            </div>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
});
