import React, { Component } from "react";
import { Table, Spin, Button, message, Select, Modal, Icon } from "antd";
import $ from "jquery/src/ajax";
import moment from 'moment';
import "./index.less";

class Outbound extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      pVisible: false,
      rVisible: false,
      tVisible: false,
      status: false,
      uList: [],
      tList: [],
      transAgent: "",
      mobile: '',
      info: {},
      dataSource: [],
      pagination: {
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        pageSize: 10,
        onChange: function (page) {
          this.userCallList(page);
        }.bind(this),
        showTotal: function (total) {
          return '共' + total + '条数据';
        }
      },
      columns: [
        {
          title: '通话人',
          dataIndex: 'adminName',
          key: 'adminName',
        },
        {
          title: '联系人',
          dataIndex: 'contacts',
          key: 'contacts',
        },
        {
          title: '电话(尾号)',
          dataIndex: 'mobileLastDigits',
          key: 'mobileLastDigits',
          width: 100,
        },
        {
          title: '时长',
          dataIndex: 'duration',
          key: 'duration',
          render: (text) => {
            return this.isTime(text)
          }
        },
        {
          title: '时间',
          dataIndex: 'createTime',
          key: 'createTime',
        },
      ],
    };
    this.onOk = this.onOk.bind(this);
    this.blindTransferByAgent = this.blindTransferByAgent.bind(this);
    this.webSocket = null;
  }

  componentDidMount() {

  }

  componentWillUnmount() {

  }

  isTime(second) {
    let time = "0秒"
    if (second > 3600) {
      time = moment.utc(second * 1000).format('h小时m分s秒')
    } else if (second > 60) {
      time = moment.utc(second * 1000).format('m分s秒')
    } else {
      time = moment.utc(second * 1000).format('s秒')
    }
    return time
  }

  getWebSocket() {
    const _this = this
    if (typeof (WebSocket) == "undefined") {
      console.log('\x1b[31m您的浏览器不支持WebSocket\x1b[0m')
    } else {
      console.log('\x1b[32m您的浏览器支持WebSocket\x1b[0m')
    }
    // 测试
    // this.webSocket = new WebSocket('ws://uat.jishutao.com/webSocketServer');
    // 生产
    this.webSocket = new WebSocket('wss://bm.jishutao.com/webSocketServer');
    // 处理WebSocket打开事件
    this.webSocket.onopen = () => {
      console.log('WebSocke已打开');
    };
    // 处理收到消息的事件
    this.webSocket.onmessage = (event) => {
      const newMessage = event.data;
      console.log('WebSocke已连接', newMessage);
      _this.setState({
        status: false
      })
      // const newMessage = event.data;
      // this.setState((prevState) => ({
      //   messages: [...prevState.messages, newMessage],
      // }));
      if (this.webSocket) {
        console.log("关闭WebSocket连接")
        this.webSocket.close();
      }
    };
    // 处理WebSocket关闭事件
    this.webSocket.onclose = () => {
      console.log('WebSocket已关闭');
    };
    // 处理WebSocket错误事件
    this.webSocket.onerror = (error) => {
      console.error('WebSocket出错了', error);
    };
  }

  onOk() {
    this.setState({
      status: true
    })
    this.callNumber()
  }
  // 公共库-默认联系人
  getDefaultMobile() {
    const { uid } = this.props
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/userOutbound/getDefaultMobile",
      data: {
        uid,
      }
    }).done(function (data) {
      if (!data.error.length) {
        if (data.data) {
          let mobile = data.data.mobile
          this.setState({
            pVisible: true,
            mobile,
          })
        } else {
          message.warning("暂无查询到联系人号码~")
        }
      } else {
        message.warning(data.error[0].message);
      };

    }.bind(this));
  }
  // 私有-客户联系方式列表
  findCustomerContacts() {
    const { uid } = this.props
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/customer/findCustomerContacts",
      data: {
        uid,
      }
    }).done(function (data) {
      if (!data.error.length) {
        let list = data.data || [];
        let mobile = "";
        if (list && list.length > 0) {
          for (var i = 0; i < list.length; i++) {
            if (list[i].major == 1) {
              mobile = list[i].mobile
            }
          }
        }
        this.setState({
          pVisible: true,
          mobile: mobile,
          uList: list,
        })
      } else {
        message.warning(data.error[0].message);
      };

    }.bind(this));
  }
  // 转移列表
  agentList() {
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/userOutbound/agentList",
      data: {}
    }).done(function (data) {
      if (!data.error.length) {
        let newList = data.data || []
        this.setState({
          transAgent: newList[0].callNo,
          tList: newList
        })
      } else {
        message.warning(data.error[0].message);
      };

    }.bind(this));
  }
  // 呼叫
  callNumber() {
    const { uid } = this.props
    const { mobile } = this.state
    $.ajax({
      method: "post",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/userOutbound/callNumber",
      data: {
        uid,
        callee: mobile,
      }
    }).done(function (data) {
      if (!data.error.length) {
        this.setState({
          pVisible: false
        })
        message.success(data.data)
      } else {
        message.warning(data.error[0].message);
      };

    }.bind(this));
  }
  // 呼叫转移
  blindTransferByAgent() {
    const { transAgent } = this.state
    const _this = this
    $.ajax({
      method: "post",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/userOutbound/blindTransferByAgent",
      data: {
        transAgent,
      }
    }).done(function (data) {
      if (!data.error.length) {
        _this.setState({
          tVisible: false
        })
        message.success(data.data)
      } else {
        message.warning(data.error[0].message);
      };

    }.bind(this));
  }
  // 通话记录
  userCallList(pageNo) {
    const { pagination } = this.state;
    const { uid } = this.props
    this.setState({
      loading: true,
    });
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/userOutbound/userCallList",
      data: {
        uid,
        pageNo: pageNo || 1,
        pageSize: pagination.pageSize,
      },
      success: function (data) {
        this.setState({
          loading: false,
        });
        if (data.error && data.error.length === 0) {
          if (data.data.page.list) {
            pagination.current = data.data.page.pageNo;
            pagination.total = data.data.page.totalCount;
            if (data.data.page && data.data.page.list && !data.data.page.list.length) {
              pagination.current = 0;
              pagination.total = 0;
            }
            this.setState({
              dataSource: data.data.page.list,
              pagination: this.state.pagination,
              pageNo: data.data.pageNo,
              info: data.data.sum
            });
          } else {
            this.setState({
              dataSource: data.data,
              pagination: false,
            });
          }
        } else {
          message.warning(data.error[0].message);
        }
      }.bind(this),
    }).always(
      function () {
        this.setState({
          loading: false,
        });
      }.bind(this)
    );
  }

  render() {
    const { status, pVisible, rVisible, tVisible, transAgent, tList, mobile, uList } = this.state
    const { type, } = this.props

    return (
      <span>
        {type != "history" &&
          <Button
            style={{ background: !status ? "green" : "red", border: 0 }}
            type="primary"
            loading={pVisible}
            onClick={() => {
              if (status) {
                return
              }
              this.getWebSocket();
              type == "public"
                ? this.getDefaultMobile()
                : this.findCustomerContacts()
            }}
          >{!pVisible && <Icon type="phone" />} {!status ? '呼叫' : '正在通话中'}</Button>}
        {type == "private" && status &&
          <Button
            style={{ background: "green", border: 0, marginLeft: 20 }}
            type="primary"
            onClick={() => {
              this.agentList();
              this.setState({ tVisible: true })
            }}
          ><Icon type="phone" /> 呼叫转移</Button>}
        <Button
          style={{ background: "green", border: 0, marginLeft: 20 }}
          type="primary"
          onClick={() => {
            this.userCallList();
            this.setState({ rVisible: true })
          }}
        ><Icon type="phone" /> 历史记录</Button>
        <Modal
          title="联系人电话"
          width={420}
          visible={pVisible}
          maskClosable={false}
          okText="呼叫"
          onOk={this.onOk}
          onCancel={() => {
            this.setState({
              pVisible: false
            })
          }}
        >
          <div className="contacts">
            <Select
              style={{ width: 200 }}
              value={mobile}
              onChange={e => {
                this.setState({
                  mobile: e
                })
              }}
            >
              {
                uList.map(item =>
                  <Select.Option value={item.mobile} key={item.id}>{item.mobile}</Select.Option>
                )
              }
            </Select>
          </div>
        </Modal>
        <Modal
          title="呼叫转移"
          width={420}
          visible={tVisible}
          maskClosable={false}
          okText="呼叫转移"
          onOk={this.blindTransferByAgent}
          onCancel={() => {
            this.setState({
              tVisible: false
            })
          }}
        >
          <div className="contacts">
            <Select
              style={{ width: 200 }}
              value={transAgent}
              onChange={(e) => {
                this.setState({
                  transAgent: e
                })
              }}
            >
              {
                tList.map(item =>
                  <Select.Option value={item.callNo} key={item.id}>{item.name}</Select.Option>
                )
              }
            </Select>
          </div>
        </Modal>
        <Modal
          title="历史记录"
          width={600}
          visible={rVisible}
          maskClosable={false}
          onCancel={() => {
            this.setState({
              rVisible: false
            })
          }}
          footer={null}
        >
          <div>
            <div style={{ marginBottom: 5 }}>公司名称：{this.state.info.name}</div>
            <div style={{ marginBottom: 10 }}>累计通话次数：{this.state.info.callCount}次&nbsp;&nbsp;&nbsp;&nbsp;通话时长：{this.isTime(this.state.info.callDuration)}</div>
            <Spin spinning={this.state.loading}>
              <Table
                size="middle"
                columns={this.state.columns}
                dataSource={this.state.dataSource}
                pagination={this.state.pagination}
              />
            </Spin>
          </div>
        </Modal>
      </span>
    );
  }
}

export default Outbound;
