import React from "react";
import $ from "jquery/src/ajax";
import { Spin, Button, Tabs, Table, message, Modal } from "antd";
import FollowDetail from "./manageCenter/customer/NEW/intentionCustomer/followDetail"


const MessageModal = React.createClass({
  getInitialState() {
    return {
      unreadData: [],
      unreadDataType: "0",
      dataSourceType: "1",
      unreadDataIndex: 0,
      visible: false,
      loading: false,
      pagination: {
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        pageSize: 10,
        onChange: function (page) {
          this.loadReaded(page);
        }.bind(this),
        showTotal: function (total) {
          return "共" + total + "条数据";
        },
      },
      UnreadPagination: {
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        pageSize: 10,
        onChange: function (page) {
          this.loadUnread(page);
        }.bind(this),
        showTotal: function (total) {
          return "共" + total + "条数据";
        },
      },
      categoryArr: [],
      columns: [
        {
          title: "类型",
          dataIndex: "noticeType",
          key: "noticeType",
          render: (text, record) => {
            return <span style={{ color: record.noticeType == 59 && "red" }}>{record.noticeTypeName}</span>;
          },
        },
        {
          title: "时间",
          dataIndex: "createTimeFormattedDate",
          key: "createTimeFormattedDate",
        },
        {
          title: "内容",
          dataIndex: "content",
          key: "content",
          render: (text, record) => {
            return <span style={{ color: record.noticeType == 59 && "red" }}>{text}</span>;
          },
        },
        {
          title: "操作",
          dataIndex: "abc",
          key: "abc",
          render: (text, record) => {
            let contractNo = "";
            if (
              (record.noticeType === 14 || record.noticeType === 40) &&
              record.content.indexOf("合同编号-") !== -1
            ) {
              let arr = record.content.split("合同编号-");
              contractNo = arr[1].match(/(\S*), 订单编号/)[1];
            }
            return record.noticeType === 48 || record.noticeType === 49 ? (
              <Button
                type="primary"
                onClick={() => {
                  this.category();
                  record.id = record.uid;
                  this.setState({
                    followData: record,
                    visitModul: true,
                  });
                }}
              >
                立即跟进
              </Button>
            ) : record.noticeType === 14 || record.noticeType === 40 ? (
              <Button
                disabled={!contractNo}
                type="primary"
                onClick={(e) => {
                  e.stopPropagation();
                  let input = document.getElementById("copyText");
                  input.value = contractNo;
                  input.select();
                  document.execCommand("copy");
                  message.success("复制成功");
                }}
              >
                复制合同号
              </Button>
            ) : null;
          },
        },
      ],
      data: [],
    };
  },
  category() {
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/Varieties/getSuperList",
      data: {},
      success: function (data) {
        let thedata = data.data;
        let theArr = [];
        if (!thedata) {
          if (data.error && data.error.length) {
            message.warning(data.error[0].message);
          }
          thedata = {};
        } else {
          thedata.map(function (item, index) {
            theArr.push({
              value: item.id,
              key: item.cname,
            });
          });
        }
        this.setState({
          categoryArr: theArr,
        });
      }.bind(this),
    });
  },
  loadReaded(pageNo) {
    this.state.data = [];
    this.setState({
      loading: true,
    });
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/notice/readed",
      data: {
        pageNo: pageNo || 1,
        pageSize: this.state.pagination.pageSize,
        type: this.state.unreadDataType,
      },
    })
      .done((data) => {
        if (!data.data) {
          if (data.error && data.error.length) {
            message.warning(data.error[0].message);
            return;
          }
        }
        this.state.data = [];
        for (let i = 0; i < data.data.list.length; i++) {
          let thisdata = data.data.list[i];
          this.state.data.push({
            key: i + 1,
            id: thisdata.id,
            rid: thisdata.rid,
            uid: thisdata.uid,
            aid: thisdata.aid,
            noticeType: thisdata.noticeType,
            year: thisdata.year,
            noticeTypeName: thisdata.noticeTypeName,
            content: thisdata.content,
            createTime: thisdata.createTime,
            createTimeFormattedDate: thisdata.createTimeFormattedDate,
            principle: thisdata.principle,
            unitName: thisdata.unitName,
          });
        }
        this.state.pagination.current = data.data.pageNo;
        this.state.pagination.total = data.data.totalCount;
        this.setState({
          dataSource: this.state.data,
          pagination: this.state.pagination,
        });
      })
      .always(
        function () {
          this.setState({
            loading: false,
          });
        }.bind(this)
      );
  },
  loadUnread(pageNo) {
    this.state.data = [];
    this.setState({
      loading: true,
    });
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/notice/unread",
      data: {},
    })
      .done((data) => {
        if (data.error && data.error.length) {
          message.warning(data.error[0].message);
          return;
        } else {
          let arr = data.data.filter((v) => v.list.length > 0);
          if (arr.length) {
            this.setState({
              newVisible: true,
            });
          }
          let index = data.data.findIndex((v) => v.list.length > 0);
          if (index >= 0) {
            data.data[index].isRead = true;
            this.setState({
              unreadDataType: data.data[index]["id"] + "",
              unreadDataIndex: index,
            });
          } else {
            this.setState({
              unreadDataType: data.data[0]["id"] + "",
              unreadDataIndex: "0",
            });
          }
          this.setState({
            unreadData: data.data,
          });
        }
      })
      .always(
        function () {
          this.setState({
            loading: false,
          });
        }.bind(this)
      );
  },
  componentWillReceiveProps(nextProps) {
    if (!this.state.visible && nextProps.showDesc) {
      this.loadReaded();
      this.loadUnread();
    }
    this.state.visible = nextProps.showDesc;
  },
  handleOk() {
    let arr = this.state.unreadData.filter(
      (v) => v.list.length > 0 && !v.isRead
    );
    if (arr.length > 0) {
      message.warning("还存在未读消息,请查看后再关闭当前页面!");
      return;
    } else {
      this.setState({
        visible: false,
      });
    }
    this.props.closeDesc(false, true);
  },
  handleCancel(e) {
    let arr = this.state.unreadData.filter(
      (v) => v.list.length > 0 && !v.isRead
    );
    if (arr.length > 0) {
      message.warning("还存在未读消息,请查看后再关闭当前页面!");
      return;
    } else {
      this.setState({
        visible: false,
      });
    }
    this.props.closeDesc(false, true);
  },
  closeDesc() {
    this.setState(
      {
        categoryArr: [],
        followData: "",
        visitModul: false,
      },
      () => {
        this.loadReaded(this.state.pagination.current);
      }
    );
  },
  render() {
    return (
      <div className="topTab-modal">
        <Spin spinning={this.state.loading} className="spin-box">
          <Modal
            maskClosable={false}
            title="信息中心"
            visible={this.state.visible}
            onOk={this.handleOk}
            onCancel={this.handleCancel}
            width="1200px"
            footer=""
          >
            <Spin spinning={this.state.loading} className="spin-box">
              <Tabs
                defaultActiveKey={this.state.unreadDataType}
                activeKey={this.state.unreadDataType}
                onChange={(v) => {
                  let index = this.state.unreadData.findIndex((d) => d.id == v);
                  this.state.unreadData[index].isRead = true;
                  this.setState(
                    {
                      unreadDataIndex: index,
                      unreadData: this.state.unreadData,
                      unreadDataType: v,
                    },
                    () => {
                      if (this.state.dataSourceType === "2") {
                        this.loadReaded();
                      }
                    }
                  );
                }}
              >
                {this.state.unreadData.map((v) => (
                  <Tabs.TabPane
                    key={v.id + ""}
                    tab={
                      <div
                        style={{ color: v.id == 7 && "red" }}
                      >
                        {v.list.length === 0 || v.isRead ? null : (
                          <div
                            style={{
                              width: "8px",
                              height: "8px",
                              borderRadius: "8px",
                              background: "#f00",
                              position: "absolute",
                              right: "5px",
                              top: "2px",
                            }}
                          />
                        )}
                        {v.name}
                      </div>
                    }
                  />
                ))}
              </Tabs>
              <Tabs
                defaultActiveKey="1"
                type="card"
                tabPosition="left"
                value={this.state.dataSourceType}
                onChange={(v) => {
                  this.setState({
                    dataSourceType: v,
                  });
                  if (v === "2") {
                    this.loadReaded();
                  }
                }}
              >
                <Tabs.TabPane tab={"未读"} key="1">
                  <Table
                    bordered
                    columns={this.state.columns}
                    dataSource={
                      this.state.unreadData[this.state.unreadDataIndex]
                        ? this.state.unreadData[this.state.unreadDataIndex].list
                        : []
                    }
                    pagination={false}
                  />
                </Tabs.TabPane>
                <Tabs.TabPane tab="已读" key="2">
                  <Table
                    bordered
                    columns={this.state.columns}
                    dataSource={this.state.dataSource}
                    pagination={this.state.pagination}
                  />
                </Tabs.TabPane>
              </Tabs>
            </Spin>
            <textarea id="copyText" style={{ opacity: 0 }} />
          </Modal>
        </Spin>
        <FollowDetail
          categoryArr={this.state.categoryArr}
          followData={this.state.followData}
          visitModul={this.state.visitModul}
          closeDesc={this.closeDesc}
        />
      </div>
    );
  },
});

const ShowModal = React.createClass({
  getInitialState() {
    return {
      newVisible: false,
      messageModalShow: false,
    };
  },

  componentWillReceiveProps(nextProps) {
    if (this.timer) {
      clearTimeout(this.timer);
    }

    this.timer = setTimeout(() => {
      this.performAction(nextProps);
    }, 500);

  },

  performAction(nextProps) {
    this.setState({
      newVisible: nextProps.ShowModal
    });
  },

  handleOk() {
    this.setState({
      newVisible: false,
      messageModalShow: false,
    });
  },

  closeMessageModal(e, s) {
    this.setState({
      ShowModal: e,
      newVisible: false,
      messageModalShow: e
    })
    this.props.onClose();
  },

  render() {
    return (
      <div>
        <Modal
          style={{ position: "relative" }}
          title="消息提醒"
          visible={this.state.newVisible}
          closable={false}
          footer={null}
          destroyOnClose={true}
        >
          <div style={{ textAlign: "center" }}>
            您有新消息尚未查看,请及时查看信息!
            <span
              style={{ color: "#58a3ff", cursor: "pointer" }}
              //  href={"/admin/index.html#normal"}
              onClick={() => {
                this.setState({
                  messageModalShow: true,
                  newVisible: false,
                })
                !!this.props.seeInfo && this.props.seeInfo()
              }}
            >点我查看信息</span>
          </div>
          <Button
            onClick={this.handleOk}
            type={"primary"}
            style={{
              position: "relative",
              left: "50%",
              transform: "translateX(-50%)",
              bottom: -10
            }}
          >
            关闭
          </Button>
          <MessageModal
            showDesc={this.state.messageModalShow}
            closeDesc={this.closeMessageModal}
          />
        </Modal>
      </div>
    );
  }
});

export default ShowModal;