import React from 'react';
import ajax from 'jquery/src/ajax/xhr.js';
import $ from 'jquery/src/ajax';
import moment from 'moment';
import '@/manageCenter/financialManage/distribute/public.less';
import { Button, Spin, DatePicker, Radio, message, Icon } from 'antd';
import { getToday, ShowModal } from '@/tools';
import ShowModalDiv from "@/showModal.jsx";
import './index.less';

const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const { RangePicker } = DatePicker

const Outbound = React.createClass({

  getInitialState() {
    return {
      status: 1,
      releaseDate: getToday(1),
      dataList: [],
      htmlMenus: [],
    }
  },

  componentWillMount() {
    this.loadData();
    this.mainMenu();
  },

  mainMenu() {
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/selectNavList",
      data: {},
      success: function (data) {
        if (!data.data) {
          if (data.error && data.error.length) {
            message.warning(data.error[0].message);
            return;
          }
        }
        let menu = data.data;
        this.setState({
          htmlMenus: menu,
        });
      }.bind(this),
    }).always(
      function (data) {
        this.setState({
          loading: false,
        });
      }.bind(this)
    );
  },

  loadData() {
    const { releaseDate } = this.state
    this.setState({
      loading: true,
    });
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/statistics/salesTeam",
      data: {
        startTime: releaseDate[0],
        endTime: releaseDate[1],
      },
      success: function (data) {
        ShowModal(this);
        this.setState({
          loading: false,
        });
        if (data.error && data.error.length === 0) {
          this.setState({
            dataList: data.data
          })
        } else {
          message.warning(data.error[0].message);
        }
      }.bind(this),
    }).always(
      function () {
        this.setState({
          loading: false,
        });
      }.bind(this)
    );
  },

  clean() {
    this.setState({
      loading: true,
    });
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/statistics/salesTeam/clean",
      success: function (data) {
        if (data.error && data.error.length === 0) {
          ShowModal(this);
          this.setState({
            loading: false,
          });
          this.loadData();
        } else {
          message.warning(data.error[0].message);
        }
      }.bind(this),
    }).always(
      function () {
        this.setState({
          loading: false,
        });
      }.bind(this)
    );
  },

  search() {
    this.loadData();
  },

  reset() {
    this.state.releaseDate = []
    this.loadData();
  },

  getNewUrl(url, cd) {
    const { htmlMenus = [] } = this.state
    let id = ''
    htmlMenus.map(function (item) {
      if (item.url == url) {
        id = item.id;
      }
    });
    return `${url}?rid=${id}#${cd}`
  },

  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 if (second > 0) {
      time = moment.utc(second * 1000).format('s秒')
    }
    return time
  },

  setParametersInCookies(params) {
    for (let paramName in params) {
      if (params.hasOwnProperty(paramName)) {
        let paramValue = params[paramName];
        let expires = "";
        let now = new Date();
        let date = new Date(now.getTime() + 5 * 1000);
        expires = "; expires=" + date.toUTCString();
        document.cookie = paramName + "=" + encodeURIComponent(paramValue) + expires + "; path=/";
      }
    }
  },

  onOpen(teamId) {
    // const url = "outboundDetail"
    // this.props.handlekey(url)
    const { releaseDate } = this.state
    const params = {
      teamId,
      startTime: releaseDate[0],
      endTime: releaseDate[1]
    };
    this.setParametersInCookies(params)
    const url = this.getNewUrl("/admin/customer.html", `outboundDetail`)
    window.open(url, '_blank')
  },

  render() {
    const { status, dataList } = this.state
    return (
      <div className="user-content">
        <ShowModalDiv ShowModal={this.state.showModal} onClose={() => { this.setState({ showModal: false }) }} />
        <div className="content-title" style={{ marginBottom: 10 }}>
          <span style={{ fontWeight: 900, fontSize: 16 }}>外呼统计</span>
        </div>
        <div className="user-search">
          <RadioGroup value={status}
            onChange={e => {
              this.setState({
                status: e.target.value
              })
              if (e.target.value == 0) {
                this.setState({
                  releaseDate: []
                })
              } else {
                this.setState({
                  releaseDate: getToday(e.target.value)
                }, () => {
                  this.loadData()
                })
              }
            }}
          >
            <RadioButton value={1}>今日</RadioButton>
            <RadioButton value={2}>昨日</RadioButton>
            <RadioButton value={3}>近7日</RadioButton>
            <RadioButton value={4}>近15日</RadioButton>
            <RadioButton value={5}>近30日</RadioButton>
            <RadioButton value={0}>自定义</RadioButton>
          </RadioGroup>
          {
            status == 0 &&
            <span>
              <RangePicker
                style={{ width: 200, marginLeft: 15 }}
                value={[
                  this.state.releaseDate[0]
                    ? moment(this.state.releaseDate[0])
                    : null,
                  this.state.releaseDate[1]
                    ? moment(this.state.releaseDate[1])
                    : null,
                ]}
                onChange={(data, dataString) => {
                  this.setState({ releaseDate: dataString })
                }}
              />
              <Button style={{ margin: "0 15px" }} type="primary" onClick={this.search}>搜索</Button>
              <Button onClick={this.reset}>重置</Button>
            </span>
          }
          <Button style={{ margin: "0 15px" }} type="primary" onClick={this.clean}>刷新</Button>
        </div>
        <div className="patent-table">
          <Spin spinning={this.state.loading}>
            <div className='plist'>
              {
                dataList.map(item =>
                  <div className='plitems' style={{ background: ["", "#99FFCC", "#FFCC99", "#99CCFF"][item.lvl] }} key={item.id}>
                    <div className='pleft'>
                      <div className='round'><Icon type="phone" style={{ fontSize: 40, color: "#fff" }} /></div>
                      <div>{item.name}</div>
                      <div>（{["", "一级", "二级", "三级"][item.lvl]}）</div>
                    </div>
                    <div>
                      <div>
                        <span>• 团队人数：</span>
                        <a onClick={this.onOpen.bind(this,item.id)}>
                          <span style={{ textDecoration: "underline", color: "#0000FF" }}>{item.teamPeopleSum}</span>
                        </a>
                      </div>
                      <div>
                        <span>• 拨出次数：</span>
                        <a onClick={this.onOpen.bind(this,item.id)}>
                          <span style={{ textDecoration: "underline", color: "#0000FF" }}>{item.teamCallSum}</span>
                        </a>
                      </div>
                      <div>
                        <span>• 接通次数：</span>
                        <a onClick={this.onOpen.bind(this,item.id)}>
                          <span style={{ textDecoration: "underline", color: "#0000FF" }}>{item.teamConnectSum}</span>
                        </a>
                      </div>
                      <div>
                        <span>• 有效次数：</span>
                        <a onClick={this.onOpen.bind(this,item.id)}>
                          <span style={{ textDecoration: "underline", color: "#0000FF" }}>{item.teamValidSum}</span>
                        </a>
                      </div>
                      <div>
                        <span>• 时长：</span>
                        <a onClick={this.onOpen.bind(this,item.id)}>
                          <span style={{ textDecoration: "underline", color: "#0000FF" }}>{this.isTime(item.teamCallDurationSum)}</span>
                        </a>
                      </div>
                    </div>
                  </div>
                )
              }

            </div>
          </Spin>
        </div>
      </div>
    );
  },
});

export default Outbound;