import React, { Component } from "react";
import TabelContent from "../../../common/tabelContent";
import {
  Button,
  Modal,
  Form,
  DatePicker,
  Input,
  Radio,
  message,
  Spin,
  Select,
  Tabs,
  Table,
} from "antd";
import $ from "jquery/src/ajax";
import { ShowModal, getPercentage } from "@/tools";
import moment from "moment";
import { provinceSelect, getProvince } from "../../../NewDicProvinceList";
import { ChooseList } from "../../../manageCenter/order/orderNew/chooseList";
import OrderList from "./order"

const { TabPane } = Tabs;
const FormItem = Form.Item;
const Option = Select.Option;
const { RangePicker } = DatePicker;

class Source extends Component {
  constructor(props) {
    super(props);
    this.state = {
      cellData: {},
      onelist: [
        {
          value: "0",
          label: "按签单金额",
        },
        {
          value: "1",
          label: "按签单数",
        },
      ],
      columns: [
        {
          title: "序号",
          dataIndex: "key",
          key: "key",
          width: 45,
        },
        {
          title: "省份",
          dataIndex: "province",
          key: "province",
          width: 120,
          onCellClick: (r) => {
            let cellData = {};
            cellData["province"] = r.province
            this.setState({
              visible: true,
              datas: cellData,
            })
          },
          render: (text, record) =>
            <span >
              {getProvince(text)}
            </span>
        },
        {
          title: "签单数（个）",
          dataIndex: "counts",
          key: "counts",
          width: 170,
          onCellClick: (r) => {
            let cellData = {};
            cellData["province"] = r.province
            this.setState({
              visible: true,
              datas: cellData,
            })
          },
        },
        {
          title: "签单金额（万元）",
          dataIndex: "totalAmount",
          key: "totalAmount",
          width: 170,
          onCellClick: (r) => {
            let cellData = {};
            cellData["province"] = r.province
            this.setState({
              visible: true,
              datas: cellData,
            })
          },
        },
        {
          title: "电话/占比",
          dataIndex: "dhl",
          key: "dhl",
          width: 170,
          onCellClick: (r) => {
            let cellData = {};
            cellData["province"] = r.province
            cellData["salesType"] = 1
            this.setState({
              visible: true,
              datas: cellData,
            })
          },
          render: (text, record) =>
            <span >
              {record.dh + "/" + getPercentage(text)}
            </span>
        },
        {
          title: "网络/占比",
          dataIndex: "wll",
          key: "wll",
          width: 170,
          onCellClick: (r) => {
            let cellData = {};
            cellData["province"] = r.province
            cellData["salesType"] = 2
            this.setState({
              visible: true,
              datas: cellData,
            })
          },
          render: (text, record) =>
            <span >
              {record.wl + "/" + getPercentage(text)}
            </span>
        },
        {
          title: "渠道/占比",
          dataIndex: "qdl",
          key: "qdl",
          width: 170,
          onCellClick: (r) => {
            let cellData = {};
            cellData["province"] = r.province
            cellData["salesType"] = 3
            this.setState({
              visible: true,
              datas: cellData,
            })
          },
          render: (text, record) =>
            <span >
              {record.qd + "/" + getPercentage(text)}
            </span>
        },
        {
          title: "复购/占比",
          dataIndex: "gxfgl",
          key: "gxfgl",
          width: 170,
          onCellClick: (r) => {
            let cellData = {};
            cellData["province"] = r.province
            cellData["salesType"] = 6
            this.setState({
              visible: true,
              datas: cellData,
            })
          },
          render: (text, record) =>
            <span >
              {record.gxfg + "/" + getPercentage(text)}
            </span>
        },
        {
          title: "复购其他/占比",
          dataIndex: "qtfgl",
          key: "qtfgl",
          width: 170,
          onCellClick: (r) => {
            let cellData = {};
            cellData["province"] = r.province
            cellData["salesType"] = 7
            this.setState({
              visible: true,
              datas: cellData,
            })
          },
          render: (text, record) =>
            <span >
              {record.qtfg + "/" + getPercentage(text)}
            </span>
        },
        {
          title: "转介绍/占比",
          dataIndex: "zjsl",
          key: "zjsl",
          width: 170,
          onCellClick: (r) => {
            let cellData = {};
            cellData["province"] = r.province
            cellData["salesType"] = 4
            this.setState({
              visible: true,
              datas: cellData,
            })
          },
          render: (text, record) =>
            <span >
              {record.zjs + "/" + getPercentage(text)}
            </span>
        },
        {
          title: "其他/占比",
          dataIndex: "qtl",
          key: "qtl",
          width: 170,
          onCellClick: (r) => {
            let cellData = {};
            cellData["province"] = r.province
            cellData["salesType"] = 5
            this.setState({
              visible: true,
              datas: cellData,
            })
          },
          render: (text, record) =>
            <span >
              {record.qt + "/" + getPercentage(text)}
            </span>
        },
      ],
      pagination: {
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        pageSize: 10,
        onChange: function (page) {
          this.loadData(page);
        }.bind(this),
        showTotal: function (total) {
          return "共" + total + "条数据";
        },
      },
      contactsOption: [],
      loading: false,
      changeList: undefined,
      searchValues: {},
      dataSource: [],
      visible: false,
    };
  }

  changeList(arr) {
    const newArr = [];
    this.state.columns.forEach((item) => {
      arr.forEach((val) => {
        if (val === item.title) {
          newArr.push(item);
        }
      });
    });
    this.setState({
      changeList: newArr,
    });
  }
  // 重置
  resetAll() {
    this.setState(
      {
        searchValues: JSON.parse(JSON.stringify({})),
        selectedRowKeys: [],
      },
      () => {
        this.loadData();
      }
    );
  }
  // 列表接口
  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/statistis/orderSalesSource",
      data: datas,
      success: function (data) {
        ShowModal(this);
        this.setState({
          loading: false,
        });
        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);
        }
      }.bind(this),
    }).always(
      function () {
        this.setState({
          loading: false,
        });
      }.bind(this)
    );
  }
  //获取上级组织
  selectSuperId() {
    this.setState({
      departmentLoading: true,
    });
    $.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({
              value: theData.id,
              label: theData.name,
            });
          }
          this.setState({
            contactsOption: theArr,
          });
        } else {
          message.warning(data.error[0].message);
        }
      }.bind(this),
    }).always(
      function () {
        this.setState({
          departmentLoading: false,
        });
      }.bind(this)
    );
  }
  //导出excel
  exportExec() {
    message.config({
      duration: 20,
    });
    let loading = message.loading("下载中...");
    this.setState({
      exportPendingLoading: true,
    });
    let data = {};
    let obj1 = JSON.parse(JSON.stringify(this.state.searchValues));
    data = Object.assign(data, obj1);
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: "/api/admin/statistis/orderSalesSource/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;
  }

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

  render() {
    const { searchValues, onelist, columns, changeList, contactsOption, visible } = this.state;
    return (
      <div className="user-content signatureStatistics">
        <div className="content-title">
          <span
            style={{
              fontWeight: 900,
              fontSize: 16,
              display: "block",
              marginBottom: 10,
            }}
          >销售来源统计表 &nbsp;<spn style={{ color: "rgb(49,49,255)" }}>注：可通过签单数、签单金额查询统计</spn></span>
        </div>
        <Tabs defaultActiveKey="1">
          <TabPane tab="搜索" key="1">
            <div style={{ paddingTop: 10 }}>
              <Form layout="inline">
                <FormItem>
                  <Select
                    placeholder={"请选择部门"}
                    style={{ width: 150 }}
                    value={searchValues["depId"]
                      ? searchValues["depId"]
                      : undefined}
                    onChange={(e) => {
                      searchValues["depId"] = e;
                      this.setState({
                        searchValues: searchValues,
                      });
                    }}
                  >
                    {contactsOption.map((cit, index) => (
                      <Option key={cit.value}>{cit.label}</Option>
                    ))}
                  </Select>
                </FormItem>
                <FormItem>
                  <Select
                    placeholder={"请选择省份"}
                    style={{ width: 150 }}
                    value={searchValues["province"]
                      ? searchValues["province"]
                      : undefined}
                    onChange={(e) => {
                      searchValues["province"] = e;
                      this.setState({
                        searchValues: searchValues,
                      });
                    }}
                  >
                    {provinceSelect().map((cit, cin) => (
                      <Option key={cit.value}>{cit.label}</Option>
                    ))}
                  </Select>
                </FormItem>
                <FormItem>
                  <Select
                    placeholder={"请选择"}
                    style={{ width: 150 }}
                    value={searchValues["sort"]
                      ? searchValues["sort"]
                      : undefined}
                    onChange={(e) => {
                      searchValues["sort"] = e
                      this.setState({
                        searchValues: searchValues,
                      });
                    }}
                  >
                    {onelist.map((it, ins) => (
                      <Option key={it.value}>{it.label}</Option>
                    ))}
                  </Select>
                </FormItem>
                <FormItem>
                  <RangePicker
                    value={[
                      searchValues["startDate"]
                        ? moment(searchValues["startDate"])
                        : null,
                      searchValues["endDate"] ? moment(searchValues["endDate"]) : null,
                    ]}
                    onChange={(data, dataString) => {
                      searchValues["startDate"] = dataString[0],
                        searchValues["endDate"] = dataString[1],
                        this.setState({
                          searchValues: searchValues,
                        });
                    }}
                  />
                </FormItem>
                <Button
                  type="primary"
                  onClick={() => { this.loadData() }}
                  style={{ marginRight: "10px" }}
                >
                  搜索
                </Button>
                <Button
                  onClick={() => { this.resetAll() }}
                  style={{ marginRight: "10px" }}
                >
                  重置
                </Button>
              </Form>
            </div>
          </TabPane>
          <TabPane tab="更改表格显示数据" key="2">
            <div style={{ marginLeft: 10 }}>
              <ChooseList
                columns={columns}
                changeFn={this.changeList.bind(this)}
                changeList={changeList}
                top={55}
                margin={11}
              />
            </div>
          </TabPane>
          <TabPane tab="导出" key="3">
            <div
              style={{
                marginLeft: 10,
                padding: "10px 0",
                display: "flex",
              }}
            >
              <Button
                type="primary"
                onClick={() => { this.exportExec() }}
                style={{ marginLeft: "10px" }}
              >
                导出excel
              </Button>
            </div>
          </TabPane>
        </Tabs>
        <div className="patent-table">
          <Spin spinning={this.state.loading}>
            <Table
              bordered
              size="middle"
              columns={changeList ? changeList : columns}
              dataSource={this.state.dataSource}
              pagination={this.state.pagination}
            />
          </Spin>
        </div>
        {
          visible &&
          <Modal
            visible={visible}
            title="客户订单列表"
            width="90%"
            footer={null}
            onCancel={() => {
              this.setState({
                visible: false,
                datas: {},
              });
            }}
          >
            <OrderList
              data={this.state.datas}
            />
          </Modal>
        }
      </div>
    );
  }
}

export default Source;
