import React, { Component } from "react";
import {
  AutoComplete,
  Button,
  DatePicker,
  Input,
  message,
  Modal,
  Select,
  Spin,
  Table,
  Tabs,
  Tag,
  Tooltip,
} from "antd";
import { ShowModal, getPercentage } from "@/tools";
import { salesList, } from "@/dataDic"
import { ChooseList } from "../../order/orderNew/chooseList";
import $ from "jquery/src/ajax";
import "./index.less";
import moment from "moment";
import DetailList from "./detaillist";
import Cascaders from '../../../common/cascaders'

const { TabPane } = Tabs;
const { RangePicker } = DatePicker;

class SignStatistics extends Component {
  constructor(props) {
    super(props);
    this.state = {
      pageNo: 1,
      loading: false,
      changeList: undefined,
      columns: [
        {
          title: "营销员",
          dataIndex: "name",
          key: "name",
        },
        {
          title: "签单客户",
          dataIndex: "userCount",
          key: "userCount",
          sorter: (a, b) => a.userCount - b.userCount,
        },
        {
          title: "签单个数",
          dataIndex: "orderCount",
          key: "orderCount",
          sorter: (a, b) => a.orderCount - b.orderCount,
          onCellClick: (r) => {
            let cellData = {};
            cellData["aid"] = r.id
            cellData["aname"] = r.name
            this.setState({
              showDetail: true,
              rowData: cellData,
            })
          },
          render: (text) =>
            <div
              style={{
                color: "#58A3FF",
                textDecoration: "underline",
                cursor: "pointer"
              }}>
              {text}
            </div>
        },
        {
          title: "签单总金额（万元）",
          dataIndex: "totalAmount",
          key: "totalAmount",
          sorter: (a, b) => a.totalAmount - b.totalAmount,
        },
        {
          title: "新签数",
          dataIndex: "newSignNumber",
          key: "newSignNumber",
          sorter: (a, b) => a.newSignNumber - b.newSignNumber,
          onCellClick: (r) => {
            let cellData = {};
            cellData["aid"] = r.id
            cellData["aname"] = r.name
            cellData["orderType"] = "1"
            this.setState({
              showDetail: true,
              rowData: cellData,
            })
          },
          render: (text) =>
            <div
              style={{
                color: "#58A3FF",
                textDecoration: "underline",
                cursor: "pointer"
              }}>
              {text}
            </div>
        },
        {
          title: "新签率",
          dataIndex: "newRatio",
          key: "newRatio",
          render: (text) =>
            <span >
              {getPercentage(text)}
            </span>
        },
        {
          title: "复购数",
          dataIndex: "repeatSignNumber",
          key: "repeatSignNumber",
          sorter: (a, b) => a.repeatSignNumber - b.repeatSignNumber,
          onCellClick: (r) => {
            let cellData = {};
            cellData["aid"] = r.id
            cellData["aname"] = r.name
            cellData["orderType"] = "2"
            this.setState({
              showDetail: true,
              rowData: cellData,
            })
          },
          render: (text) =>
            <div
              style={{
                color: "#58A3FF",
                textDecoration: "underline",
                cursor: "pointer"
              }}>
              {text}
            </div>
        },
        {
          title: "复购率",
          dataIndex: "repeatRatio",
          key: "repeatRatio",
          render: (text) =>
            <span >
              {getPercentage(text)}
            </span>
        },
        {
          title: "渠道签单数",
          dataIndex: "channelSignNumber",
          key: "channelSignNumber",
          sorter: (a, b) => a.channelSignNumber - b.channelSignNumber,
          onCellClick: (r) => {
            let cellData = {};
            cellData["aid"] = r.id
            cellData["aname"] = r.name
            cellData["orderType"] = "3"
            this.setState({
              showDetail: true,
              rowData: cellData,
            })
          },
          render: (text) =>
            <div
              style={{
                color: "#58A3FF",
                textDecoration: "underline",
                cursor: "pointer"
              }}>
              {text}
            </div>
        },
        {
          title: "渠道签单率",
          dataIndex: "channelRatio",
          key: "channelRatio",
          render: (text) =>
            <span >
              {getPercentage(text)}
            </span>
        },
      ],
      pagination: {
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        pageSize: 99999,
        onChange: function (page) {
          this.loadData(page);
        }.bind(this),
        showTotal: function (total) {
          return "共" + total + "条数据";
        },
      },
      dataSource: [],
      searchInfor: {},
      params: {},
      showDetail: false,
      companyList: [],
    };
    this.loadData = this.loadData.bind(this);
    this.resetAll = this.resetAll.bind(this);
    this.changeList = this.changeList.bind(this);
    this.selectSuperId = this.selectSuperId.bind(this);
    this.supervisor = this.supervisor.bind(this);
    this.httpChange = this.httpChange.bind(this);
    this.blurChange = this.blurChange.bind(this);
    this.selectAuto = this.selectAuto.bind(this);
    this.exportExec = this.exportExec.bind(this);
  }
  //获取上级组织
  selectSuperId() {
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/organization/selectSuperId",
      data: {},
      success: function (data) {
        let theArr = [];
        if (data.error && data.error.length === 0) {
          for (let i = 0; i < data.data.length; i++) {
            let theData = data.data[i];
            theArr.push(
              <Select.Option value={theData.id} key={theData.id}>
                {theData.name}
              </Select.Option>
            );
          }
          this.setState({
            contactsOption: theArr,
            companyList: data.data,
            searchInfor: Object.assign(this.state.searchInfor, {
              depId: data.data[0].id,
            }),
          }, () => {
            this.loadData();
          });
        } else {
          message.warning(data.error[0].message);
        }
      }.bind(this),
    }).always(
      function () {
        this.setState({
          // loading: false,
        });
      }.bind(this)
    );
  }

  changeList(arr) {
    const newArr = [];
    this.state.columns.forEach((item) => {
      arr.forEach((val) => {
        if (val === item.title) {
          newArr.push(item);
        }
      });
    });
    this.setState({
      changeList: newArr,
    });
  }
  // 搜索
  submit() {
    this.setState({
      params: this.state.searchInfor
    })
    this.loadData()
  }

  loadData(pageNo) {
    const { searchInfor, pagination } = this.state;
    if (!searchInfor.deps) {
      message.warn("请选择你要查询的部门！")
      return
    }
    this.setState({
      loading: true,
    });
    let datas = Object.assign(searchInfor, {
      pageNo: pageNo || 1,
      pageSize: pagination.pageSize,
    });
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/statistis/signStatistics",
      data: datas,
      success: function (data) {
        ShowModal(this);
        if (data.error && data.error.length === 0) {
          if (data.data.list) {
            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 {
            this.setState({
              dataSource: data.data,
              pagination: false,
            });
          }
        } else {
          message.warning(data.error[0].message);
        }
        this.setState({
          loading: false,
        });
      }.bind(this),
    }).always(
      function () {
        this.setState({
          loading: false,
        });
      }.bind(this)
    );
  }

  resetAll() {
    const { companyList } = this.state
    this.setState(
      {
        // searchInfor: { depId: companyList[0].id },
        searchInfor: JSON.parse(JSON.stringify({})),
        params: JSON.parse(JSON.stringify({})),
        aname: "",
        dataSource: [],
      },
      () => {
        this.Cascaders.empty();
        // this.loadData();
      }
    );
  }

  supervisor(e) {
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/customer/listAdminByName",
      data: {
        adminName: e,
        status: "2",
      },
      success: function (data) {
        if (data.error && data.error.length === 0) {
          this.setState({
            customerArr: data.data,
          });
        } else {
          message.warning(data.error[0].message);
        }
      }.bind(this),
    }).always(function () { }.bind(this));
  }

  httpChange(e) {
    if (e.length >= 1) {
      this.supervisor(e);
    }
    this.setState({
      aname: e,
    });
  }

  selectAuto(value, options) {
    this.setState({
      aname: value,
    });
  }

  blurChange(e) {
    const { searchInfor } = this.state
    let theType = undefined;
    let contactLists = this.state.customerArr || [];
    if (e) {
      contactLists.map(function (item) {
        if (item.name == e.toString()) {
          theType = item.id;
        }
      });
    }
    this.setState({
      searchInfor: Object.assign(searchInfor, {
        aid: theType,
      }),
    });
  }
  // 导出Excel
  exportExec() {
    this.setState({
      exportPendingLoading: true,
    });
    message.config({
      duration: 20,
    });
    let loading = message.loading("下载中...");
    let data = this.state.searchInfor;
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url:
        globalConfig.context + "/api/admin/statistis/signStatistics/export",
      data,
      success: function (data) {
        if (data.error.length === 0) {
          this.download(data.data);
        } else {
          message.warning(data.error[0].message);
        }
      }.bind(this),
    }).always(
      function () {
        loading();
        this.setState({
          exportPendingLoading: false,
        });
      }.bind(this)
    );
  }
  // 下载
  download(fileName) {
    window.location.href =
      globalConfig.context + "/open/download?fileName=" + fileName;
  }
  // 关闭弹窗
  closeDesc() {
    this.setState({
      showDetail: false,
      params: {},
    });
    this.loadData(this.state.pageNo);
  }

  componentWillMount() {
    // this.selectSuperId();
  }

  render() {
    const { searchInfor, showDetail, rowData, params, dataSource } = this.state
    const dataSources = this.state.customerArr || [];
    const options = dataSources.map((group) => (
      <Select.Option key={group.id} value={group.name}>
        {group.name}
      </Select.Option>
    ));
    return (
      <div>
        <div className="user-content">
          <div className="content-title">
            <span style={{ fontWeight: 900, fontSize: 16 }}>签单客户数据统计（销售角度）</span>
          </div>
          <Tabs defaultActiveKey="1" className="test">
            <TabPane tab="搜索" key="1">
              <div
                className="user-search"
                style={{
                  marginTop: "10px",
                  marginLeft: "10px",
                  marginRight: "10px",
                }}
              >
                <span style={{ marginRight: "10px" }}>
                  <Cascaders
                    ref={node => this.Cascaders = node}
                    placeholder="选择部门"
                    id="id"
                    name="name"
                    children="list"
                    height={28}
                    onSel={(e) => {
                      searchInfor["deps"] = JSON.stringify(e);
                      this.setState({
                        searchInfor: searchInfor,
                      });
                    }}
                  />
                  {/* <Select
                    placeholder="选择部门"
                    style={{ width: 200 }}
                    value={searchInfor.depId}
                    onChange={(e) => {
                      this.setState({
                        searchInfor: Object.assign(searchInfor, {
                          depId: e,
                        }),
                      });
                    }}
                    notFoundContent="未获取到上级组织列表"
                  >
                    {this.state.contactsOption}
                  </Select> */}
                </span>
                <span style={{ marginRight: "10px" }}>
                  <AutoComplete
                    className="certain-category-search"
                    dropdownClassName="certain-category-search-dropdown"
                    dropdownMatchSelectWidth={false}
                    style={{ width: 160 }}
                    dataSource={options}
                    placeholder="输入姓名"
                    value={this.state.aname}
                    onChange={this.httpChange}
                    filterOption={true}
                    onBlur={this.blurChange}
                    onSelect={this.selectAuto}
                  >
                    <Input />
                  </AutoComplete>
                </span>
                <span style={{ marginRight: "10px" }}>
                  <Select
                    style={{ width: 160 }}
                    placeholder="签单金额"
                    value={searchInfor.amountType}
                    onChange={(e) => {
                      this.setState({
                        searchInfor: Object.assign(searchInfor, {
                          amountType: e,
                        }),
                      });
                    }}
                  >
                    <Option value="0">全部</Option>
                    <Option value="1">小于10万</Option>
                    <Option value="2">10-20万</Option>
                    <Option value="3">20-30万</Option>
                    <Option value="4">30万以上</Option>
                  </Select>
                </span>
                <span style={{ marginRight: "10px" }}>
                  <span style={{ marginRight: "5px", marginBottom: "10px" }}>
                    签单时间 :
                  </span>
                  <RangePicker
                    style={{ marginRight: "10px", marginBottom: "10px" }}
                    value={[
                      searchInfor.signTimeStart
                        ? moment(searchInfor.signTimeStart)
                        : null,
                      searchInfor.signTimeEnd ? moment(searchInfor.signTimeEnd) : null,
                    ]}
                    onChange={(data, dataString) => {
                      this.setState({
                        searchInfor: Object.assign(searchInfor, {
                          signTimeStart: dataString[0],
                          signTimeEnd: dataString[1],
                        }),
                      });
                    }}
                  />
                </span>
                <Button
                  type="primary"
                  onClick={() => {
                    this.submit()
                  }}
                  style={{ marginRight: "10px", marginBottom: "10px" }}
                >
                  搜索
                </Button>
                <Button
                  onClick={this.resetAll}
                  style={{ marginRight: "10px", marginBottom: "10px" }}
                >
                  重置
                </Button>
              </div>
            </TabPane>
            <TabPane tab="更改表格显示数据" key="2">
              <div style={{ marginLeft: 10 }}>
                <Spin spinning={this.state.loading}>
                  <ChooseList
                    columns={this.state.columns}
                    changeFn={this.changeList}
                    changeList={this.state.changeList}
                    top={55}
                    margin={11}
                  />
                </Spin>
              </div>
            </TabPane>
            <TabPane tab="导出" key="3">
              <div style={{ float: "left" }}>
                <Button
                  type="primary"
                  loading={this.state.exportPendingLoading}
                  onClick={this.exportExec}
                  style={{ margin: 10 }}
                >
                  导出Excel
                </Button>
              </div>
            </TabPane>
          </Tabs>
          <div className="patent-table">
            <div style={{ padding: "0px 10px 10px" }}>
              总计：签单客户&nbsp;
              <span style={{ color: "#58A3FF" }}>{dataSource.reduce((prev, next) => { return prev + next.userCount }, 0)}</span>&nbsp;个，签单个数&nbsp;
              <span style={{ color: "#58A3FF" }}>{dataSource.reduce((prev, next) => { return prev + next.orderCount }, 0)}</span>&nbsp;个
            </div>
            <Spin spinning={this.state.loading}>
              <Table
                bordered
                size="middle"
                columns={
                  this.state.changeList
                    ? this.state.changeList
                    : this.state.columns
                }
                dataSource={dataSource}
                pagination={false}
              />
            </Spin>
          </div>
        </div>
        {
          showDetail &&
          <Modal
            visible={showDetail}
            title={<div>
              <span style={{ marginRight: 20 }}>客户订单列表</span>
              <span style={{ color: "red" }}>归属人：{rowData["aname"]}</span>
            </div>}
            width="90%"
            footer={null}
            onCancel={this.closeDesc.bind(this)}
          >
            <DetailList
              data={Object.assign(rowData, params)}
            />
          </Modal>
        }
      </div>
    );
  }
}

export default SignStatistics;
