import React from 'react';
import $ from 'jquery/src/ajax';
import {
  Form, Button, Input, Select, Spin, Table,
  message, DatePicker, Tabs, TreeSelect
} from 'antd';
import moment from 'moment';
import { ShowModal } from "@/tools";
import { ChooseList } from "../../order/orderNew/chooseList";

const { TabPane } = Tabs
const { RangePicker } = DatePicker
const OutboundDetail = Form.create()(React.createClass({
  getInitialState() {
    return {
      searchValues: {}, // 列表筛选条件
      loading: false, //加载动画
      changeList: undefined, // 更改后的表格显示数据
      dataSource: [], // 列表数据
      teamList: [], // 团队列表
      pagination: {
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        pageSize: 10,
        onChange: function (page) {
          this.loadData(page);
        }.bind(this),
        showTotal: function (total) {
          return '共' + total + '条数据';
        }
      },
      columns: [
        {
          title: '姓名',
          dataIndex: 'name',
          key: 'name',
        },
        {
          title: '所属团队',
          dataIndex: 'teamName',
          key: 'teamName',
        },
        {
          title: '拨出次数',
          dataIndex: 'callSum',
          key: 'callSum',
        },
        {
          title: '接通次数',
          dataIndex: 'connectSum',
          key: 'connectSum',
        },
        {
          title: '有效次数',
          dataIndex: 'validSum',
          key: 'validSum',
        },
        {
          title: '时长',
          dataIndex: 'callDurationSum',
          key: 'callDurationSum',
          render: (text, record) => {
            return (
              <div>
                {this.isTime(text)}
              </div>
            )
          }
        },
        {
          title: '时间',
          dataIndex: 'dayDate',
          key: 'dayDate',
        },

      ],
      visible: "",
    };
  },

  componentWillMount() {
    this.salesTeam();
    let params = this.getParametersFromCookies();
    if (params.teamId) {
      const { searchValues } = this.state
      let obj = {
        teamId: Number(params.teamId),
        startTime: params.startTime,
        endTime: params.endTime,
      }
      this.setState({
        searchValues: Object.assign(searchValues, obj),
      }, () => {
        this.loadData();
      });
    } else {
      this.loadData();
    }
  },

  getParametersFromCookies() {
    let params = {};
    let ca = document.cookie.split(';');
    for (let i = 0; i < ca.length; i++) {
      let c = ca[i];
      while (c.charAt(0) === ' ') c = c.substring(1, c.length);
      let eqPos = c.indexOf('=');
      if (eqPos > -1) {
        let paramName = c.substring(0, eqPos);
        let paramValue = decodeURIComponent(c.substring(eqPos + 1));
        params[paramName] = paramValue;
      }
    }
    return params;
  },

  // 列表接口
  loadData(pageNo) {
    const { searchValues, pagination } = this.state;
    this.setState({
      loading: true,
    });
    let datas = Object.assign(searchValues, {
      pageNo: pageNo || 1,
      pageSize: pagination.pageSize,
    });
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/userOutbound/listCallDay",
      data: datas,
      success: function (data) {
        ShowModal(this);
        this.setState({
          loading: false,
        });
        let theArr = [];
        if (data.error && data.error.length === 0) {
          if (data.data) {
            pagination.current = data.data.pageNo;
            pagination.total = data.data.totalCount;
            if (data.data && data.data.list && !data.data.list.length) {
              pagination.current = 0
              pagination.total = 0
            };
            this.setState({
              dataSource: data.data.list,
              pagination: this.state.pagination,
              pageNo: data.data.pageNo,
            });
          }
        } else {
          message.warning(data.error[0].message);
        }
      }.bind(this),
    }).always(
      function () {
        this.setState({
          loading: false,
        });
      }.bind(this)
    );
  },

  // 团队
  salesTeam() {
    this.setState({
      loading: true
    });
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/salesTeam/lvlList",
      data: {},
      success: function (data) {
        this.setState({
          loading: false,
        });
        if (data.error && data.error.length === 0) {
          let list = data.data
          this.setState({
            teamList: list ? this.handleTreeData(list) : []
          });
        } else {
          message.warning(data.error[0].message);
        }
      }.bind(this),
    }).always(function () {
      this.setState({
        loading: false
      });
    }.bind(this));
  },

  // 树状默认数据处理
  handleTreeData(treeData) {
    let nodeDta = [];
    treeData.map(item => {
      let treeObj = {};
      treeObj.key = item.id
      treeObj.id = item.id
      treeObj.value = item.id
      treeObj.label = item.name
      treeObj.title = item.name
      treeObj.lvl = item.lvl
      item.list ? treeObj.children = this.handleTreeData(item.list) : null;
      nodeDta.push(treeObj)
    })
    return nodeDta
  },

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

  reset() {
    this.setState({
      searchValues: {}
    }, () => {
      this.loadData();
    })
  },

  changeList(arr) {
    const newArr = [];
    this.state.columns.forEach(item => {
      arr.forEach(val => {
        if (val === item.title) {
          newArr.push(item);
        }
      });
    });
    this.setState({
      changeList: newArr
    });
  },

  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
  },

  render() {
    const { searchValues, teamList } = this.state
    return (
      <div className="user-content">
        <div className="content-title">
          <Tabs defaultActiveKey="1" onChange={this.callback} className="test">
            <TabPane tab="搜索" key="1">
              <div className="user-search" style={{ paddingBottom: 10 }}>
                <Input
                  placeholder="请输入姓名"
                  style={{ width: "180px" }}
                  value={searchValues["name"]
                    ? searchValues["name"]
                    : ""}
                  onChange={e => {
                    searchValues["name"] = e.target.value;
                    this.setState({
                      searchValues: searchValues,
                    });
                  }}
                />
                <TreeSelect
                  style={{ width: 180 }}
                  value={searchValues["teamId"]
                    ? searchValues["teamId"]
                    : undefined}
                  dropdownStyle={{ maxHeight: 300, overflow: 'auto' }}
                  treeData={teamList}
                  placeholder="请选择团队"
                  showSearch
                  treeNodeFilterProp="title"
                  onChange={(e) => {
                    searchValues["teamId"] = e;
                    this.setState({
                      searchValues,
                    });
                  }}
                />
                <Select
                  placeholder="有效次数"
                  style={{ width: 180 }}
                  value={searchValues["quantityType"]
                    ? searchValues["quantityType"]
                    : undefined}
                  onChange={e => {
                    searchValues["quantityType"] = e;
                    this.setState({
                      searchValues,
                    });
                  }}
                >
                  <Select.Option value={1}>10次以下</Select.Option>
                  <Select.Option value={2}>10-20次</Select.Option>
                  <Select.Option value={3}>20-50次</Select.Option>
                  <Select.Option value={4}>50次以上</Select.Option>
                </Select>
                <RangePicker
                  style={{ width: 300 }}
                  value={[
                    searchValues["startTime"] ? moment(searchValues["startTime"]) : null,
                    searchValues["endTime"] ? moment(searchValues["endTime"]) : null,
                  ]}
                  onChange={(data, dataString) => {
                    searchValues["startTime"] = dataString[0];
                    searchValues["endTime"] = dataString[1];
                    this.setState({
                      searchValues,
                    });
                  }}
                />
                <Button
                  type="primary"
                  onClick={this.search}
                  style={{ margin: "0 10px" }}
                >搜索</Button>
                <Button onClick={this.reset}>重置</Button>
              </div>
            </TabPane>
            <TabPane tab="更改表格显示数据" key="2">
              <div style={{ marginLeft: 10 }}>
                <ChooseList
                  columns={this.state.columns}
                  changeFn={this.changeList}
                  changeList={this.state.changeList}
                  top={55}
                  margin={11}
                />
              </div>
            </TabPane>
          </Tabs>
          <div className="patent-table">
            <Spin spinning={this.state.loading}>
              <Table
                bordered
                columns={
                  this.state.changeList
                    ? this.state.changeList
                    : this.state.columns
                }
                dataSource={this.state.dataSource}
                pagination={this.state.pagination}
              />
            </Spin>
          </div>
        </div>
      </div>
    );
  }
}));

export default OutboundDetail;
