import React, { Component } from "react";
import {
  AutoComplete,
  Button,
  DatePicker,
  Input,
  message,
  Modal,
  Select,
  Spin,
  Table,
  Tabs,
  Tag,
  Tooltip,
} from "antd";
import { ShowModal, getContactType } 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 ChannelLog from "../../channelList/channelunit/channellog"; //转交日志
import ChangeLog from "../../channelList/channelunit/changelog"; //更名日志
import DetailList from "./detaillist";//客户订单列表
import Visit from "../../channelList/channelunit/detail/visit"

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

class SignCustomer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      pageNo: 1,
      loading: false,
      changeList: undefined,
      selectedRowKeys: [],
      columns: [
        {
          title: "客户名称",
          dataIndex: "nickname",
          key: "nickname",
          fixed: "left",
          width: 200,
          render: (text, record) => {
            return (
              <div>
                {text}
                {record.member == 1 && <Tag color="#1E90FF">会员</Tag>}
                {record.chargeback == 1 && <Tag color="#F21212">退</Tag>}
                {record.bigCustomer == 1 && <Tag color="#F21212">大客户</Tag>}
              </div>
            );
          },
        },
        {
          title: "签单次数",
          dataIndex: "signNumber",
          key: "signNumber",
          onCellClick: (r) => {
            let rows = {};
            rows["nickname"] = r.nickname
            rows["uid"] = r.id
            this.setState({
              rowData: rows,
              showDetail: true,
            });
          },
          render: (text) =>
            <div
              style={{
                color: "#58A3FF",
                textDecoration: "underline",
                cursor: "pointer"
              }}>
              {text}
            </div>
        },
        {
          title: "总金额（万元）",
          dataIndex: "signAmount",
          key: "signAmount",
        },
        {
          title: "首次签单时间",
          dataIndex: "firstSigningTime",
          key: "firstSigningTime",
        },
        {
          title: "最新签单时间",
          dataIndex: "lastSigningTime",
          key: "lastSigningTime",
        },
        {
          title: "签单类型",
          dataIndex: "lastSalesType",
          key: "lastSalesType",
          render: (text) => (
            <div>{salesList[text]}</div>
          )
        },
        {
          title: "归属人",
          dataIndex: "name",
          key: "name",
        },
        {
          title: "归属部门",
          dataIndex: "depName",
          key: "depName",
        },
        {
          title: "跟进人",
          dataIndex: "followAname",
          key: "followAname",
        },
        {
          title: "跟进方式",
          dataIndex: "lastFollowType",
          key: "lastFollowType",
          render: (text) => (
            <div>{getContactType(text)}</div>
          )
        },
        {
          title: "跟进说明",
          dataIndex: "followExplain",
          key: "followExplain",
          width: 200,
        },
        {
          title: "次数",
          dataIndex: "followNumber",
          key: "followNumber",
          onCellClick: (r) => {
            let rows = {};
            rows["nickname"] = r.nickname
            rows["id"] = r.id
            this.setState({
              rowData: rows,
              followup: true,
            });
          },
          render: (text) =>
            <div
              style={{
                color: "#58A3FF",
                textDecoration: "underline",
                cursor: "pointer"
              }}>
              {text}
            </div>
        },
        {
          title: "最新跟进时间",
          dataIndex: "lastFollowTime",
          key: "lastFollowTime",
        },
        {
          title: "已签项目",
          dataIndex: "taskNames",
          key: "taskNames",
          width: "15%",
        },
      ],
      pagination: {
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        pageSize: 10,
        onChange: function (page) {
          this.loadData(page);
        }.bind(this),
        showTotal: function (total) {
          return "共" + total + "条数据";
        },
      },
      dataSource: [],
      searchInfor: {},
      mvisible: "",
      showDetail: false,
      followup: false,
    };
    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.supervisor1 = this.supervisor1.bind(this);
    this.httpChange = this.httpChange.bind(this);
    this.httpChange1 = this.httpChange1.bind(this);
    this.selectAuto = this.selectAuto.bind(this);
    this.selectAuto1 = this.selectAuto1.bind(this);
    this.blurChange = this.blurChange.bind(this);
    this.blurChange1 = this.blurChange1.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,
          });
        } 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,
    });
  }

  loadData(pageNo) {
    const { searchInfor, pagination } = this.state;
    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/signSummary",
      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);
        }
      }.bind(this),
    }).always(
      function () {
        this.setState({
          loading: false,
        });
      }.bind(this)
    );
  }

  resetAll() {
    this.setState(
      {
        searchInfor: JSON.parse(JSON.stringify({})),
        selectedRowKeys: [],
      },
      () => {
        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));
  }

  supervisor1(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({
            customerArr1: 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({
      followAname: e,
    });
  }

  httpChange1(e) {
    if (e.length >= 1) {
      this.supervisor1(e);
    }
    this.setState({
      adminName: e,
    });
  }

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

  selectAuto1(value, options) {
    this.setState({
      adminName: 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, {
        followAid: theType,
      }),
    });
  }

  blurChange1(e) {
    const { searchInfor } = this.state
    let theType = undefined;
    let contactLists = this.state.customerArr1 || [];
    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/signSummary/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;
  }
  // 选择行
  onSelectChange(selectedRowKeys, selectedRows) {
    this.setState({
      selectedRowKeys,
      selectedRows,
    });
  }
  // 关闭弹窗
  closeDesc() {
    this.setState({
      mvisible: "",
      showDetail: false,
      followup: false,
      rowData: {}
    });
    this.loadData(this.state.pageNo);
  }

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

  render() {
    const { searchInfor, selectedRowKeys, selectedRows, showDetail, followup, rowData } = this.state
    const dataSources = this.state.customerArr || [];
    const options = dataSources.map((group) => (
      <Select.Option key={group.id} value={group.name}>
        {group.name}
      </Select.Option>
    ));
    const dataSources1 = this.state.customerArr1 || [];
    const options1 = dataSources1.map((group) => (
      <Select.Option key={group.id} value={group.name}>
        {group.name}
      </Select.Option>
    ));
    const rowSelection = {
      hideDefaultSelections: true,
      selectedRowKeys,
      onChange: this.onSelectChange.bind(this),
    };
    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" }}>
                  <Input
                    style={{ width: 160 }}
                    placeholder="输入客户名称"
                    value={searchInfor.userName}
                    onChange={e => {
                      this.setState({
                        searchInfor: Object.assign(searchInfor, {
                          userName: e.target.value,
                        }),
                      });
                    }}
                  />
                </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.followAname}
                    onChange={this.httpChange}
                    filterOption={true}
                    onBlur={this.blurChange}
                    onSelect={this.selectAuto}
                  >
                    <Input />
                  </AutoComplete>
                </span>
                <span style={{ marginRight: "10px" }}>
                  <AutoComplete
                    className="certain-category-search"
                    dropdownClassName="certain-category-search-dropdown"
                    dropdownMatchSelectWidth={false}
                    style={{ width: 160 }}
                    dataSource={options1}
                    placeholder="所属人姓名"
                    value={this.state.adminName}
                    onChange={this.httpChange1}
                    filterOption={true}
                    onBlur={this.blurChange1}
                    onSelect={this.selectAuto1}
                  >
                    <Input />
                  </AutoComplete>
                </span>
                <span style={{ marginRight: "10px" }}>
                  <Select
                    style={{ width: 160 }}
                    placeholder="会员状态"
                    value={searchInfor.member}
                    onChange={(e) => {
                      this.setState({
                        searchInfor: Object.assign(searchInfor, {
                          member: e,
                        }),
                      });
                    }}
                  >
                    <Option value={undefined}>全部</Option>
                    <Option value="0">非会员</Option>
                    <Option value="1">会员</Option>
                  </Select>
                </span>

                <span style={{ marginRight: "10px" }}>
                  <Select
                    style={{ width: 160 }}
                    placeholder="有无退单"
                    value={searchInfor.chargeback}
                    onChange={(e) => {
                      this.setState({
                        searchInfor: Object.assign(searchInfor, {
                          chargeback: e,
                        }),
                      });
                    }}
                  >
                    <Option value={undefined}>全部</Option>
                    <Option value="0">无退单</Option>
                    <Option value="1">有退单</Option>
                  </Select>
                </span>

                <span style={{ marginRight: "10px" }}>
                  <Select
                    style={{ width: 160 }}
                    placeholder="选择跟进方式"
                    value={searchInfor.lastFollowType}
                    onChange={(e) => {
                      this.setState({
                        searchInfor: Object.assign(searchInfor, {
                          lastFollowType: e,
                        }),
                      });
                    }}
                  >
                    <Option value={undefined}>全部</Option>
                    <Option value="0">外出</Option>
                    <Option value="1">电话</Option>
                    <Option value="2">QQ</Option>
                    <Option value="3">微信</Option>
                    <Option value="4">邮件</Option>
                    <Option value="5">公出打卡</Option>
                  </Select>
                </span>

                <span style={{ marginRight: "10px" }}>
                  <Select
                    style={{ width: 160 }}
                    placeholder="是否大客户"
                    value={searchInfor.bigCustomer}
                    onChange={(e) => {
                      this.setState({
                        searchInfor: Object.assign(searchInfor, {
                          bigCustomer: e,
                        }),
                      });
                    }}
                  >
                    <Option value={undefined}>全部</Option>
                    <Option value="0">非大客户</Option>
                    <Option value="1">大客户</Option>
                  </Select>
                </span>

                <span style={{ marginRight: "10px" }}>
                  <Select
                    style={{ width: 160 }}
                    placeholder="签单次数"
                    value={searchInfor.signNumber}
                    onChange={(e) => {
                      this.setState({
                        searchInfor: Object.assign(searchInfor, {
                          signNumber: e,
                        }),
                      });
                    }}
                  >
                    <Option value={undefined}>全部</Option>
                    <Option value="1">1次</Option>
                    <Option value="2">2次</Option>
                    <Option value="3">3次</Option>
                    <Option value="4">3次以上</Option>
                  </Select>
                </span>

                <span style={{ marginRight: "10px" }}>
                  <Select
                    style={{ width: 160 }}
                    placeholder="最新签单类型"
                    value={searchInfor.lastSalesType}
                    onChange={(e) => {
                      this.setState({
                        searchInfor: Object.assign(searchInfor, {
                          lastSalesType: e,
                        }),
                      });
                    }}
                  >
                    {
                      salesList.map((item, index) =>
                        <Option value={index}>{item}</Option>
                      )
                    }
                  </Select>
                </span>

                <span style={{ marginRight: "10px" }}>
                  <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" }}>
                  <span style={{ marginRight: "5px", marginBottom: "10px" }}>
                    跟进时间 :
                  </span>
                  <RangePicker
                    style={{ marginRight: "10px", marginBottom: "10px" }}
                    value={[
                      searchInfor.lastFollowTimeStart
                        ? moment(searchInfor.lastFollowTimeStart)
                        : null,
                      searchInfor.lastFollowTimeEnd ? moment(searchInfor.lastFollowTimeEnd) : null,
                    ]}
                    onChange={(data, dataString) => {
                      this.setState({
                        searchInfor: Object.assign(searchInfor, {
                          lastFollowTimeStart: dataString[0],
                          lastFollowTimeEnd: dataString[1],
                        }),
                      });
                    }}
                  />
                </span>

                <span style={{ marginRight: "10px" }}>
                  <span style={{ marginRight: "5px", marginBottom: "10px" }}>
                    首次签单 :
                  </span>
                  <RangePicker
                    style={{ marginRight: "10px", marginBottom: "10px" }}
                    value={[
                      searchInfor.firstSigningTimeStart
                        ? moment(searchInfor.firstSigningTimeStart)
                        : null,
                      searchInfor.firstSigningTimeEnd ? moment(searchInfor.firstSigningTimeEnd) : null,
                    ]}
                    onChange={(data, dataString) => {
                      this.setState({
                        searchInfor: Object.assign(searchInfor, {
                          firstSigningTimeStart: dataString[0],
                          firstSigningTimeEnd: dataString[1],
                        }),
                      });
                    }}
                  />
                </span>

                <span style={{ marginRight: "10px" }}>
                  <span style={{ marginRight: "5px", marginBottom: "10px" }}>
                    最新签单 :
                  </span>
                  <RangePicker
                    style={{ marginRight: "10px", marginBottom: "10px" }}
                    value={[
                      searchInfor.lastSigningTimeStart
                        ? moment(searchInfor.lastSigningTimeStart)
                        : null,
                      searchInfor.lastSigningTimeEnd ? moment(searchInfor.lastSigningTimeEnd) : null,
                    ]}
                    onChange={(data, dataString) => {
                      this.setState({
                        searchInfor: Object.assign(searchInfor, {
                          lastSigningTimeStart: dataString[0],
                          lastSigningTimeEnd: dataString[1],
                        }),
                      });
                    }}
                  />
                </span>

                <Button
                  type="primary"
                  onClick={() => {
                    this.loadData();
                  }}
                  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>
              <div style={{ float: "left" }}>
                <Button
                  type="primary"
                  onClick={() => {
                    this.setState({
                      mvisible: "changelog",
                    });
                  }}
                  style={{ margin: 10 }}
                  disabled={this.state.selectedRowKeys.length !== 1}
                >
                  客户日志
                </Button>
              </div>
              <div style={{ float: "left" }}>
                <Button
                  type="primary"
                  onClick={() => {
                    this.setState({
                      mvisible: "channellog",
                    });
                  }}
                  style={{ margin: 10 }}
                  disabled={this.state.selectedRowKeys.length !== 1}
                >
                  转交日志
                </Button>
              </div>
            </TabPane>
          </Tabs>
          <div className="patent-table">
            <Spin spinning={this.state.loading}>
              <Table
                bordered
                size="middle"
                scroll={{ x: "110%" }}
                columns={
                  this.state.changeList
                    ? this.state.changeList
                    : this.state.columns
                }
                dataSource={this.state.dataSource}
                pagination={this.state.pagination}
                rowSelection={rowSelection}
              />
            </Spin>
          </div>
        </div>
        {this.state.mvisible == "channellog" && (
          <ChannelLog
            cancel={this.closeDesc.bind(this)}
            visible={this.state.mvisible}
            id={selectedRows[0].id}
          />
        )}
        {this.state.mvisible == "changelog" && (
          <ChangeLog
            cancel={this.closeDesc.bind(this)}
            visible={this.state.mvisible}
            id={selectedRows[0].id}
          />
        )}
        {
          showDetail &&
          <Modal
            visible={showDetail}
            title={<div>
              <span style={{ marginRight: 20 }}>客户订单列表</span>
              <span style={{ color: "red" }}>客户名称：{rowData.nickname}</span>
            </div>}
            width="90%"
            footer={null}
            onCancel={this.closeDesc.bind(this)}
          >
            <DetailList
              // data={Object.assign(rowData, params)}
              data={rowData}
            />
          </Modal>
        }
        {
          followup &&
          <Modal
            visible={followup}
            title={<div>
              <span style={{ marginRight: 20 }}>客户跟进列表</span>
              <span style={{ color: "red" }}>客户名称：{rowData.nickname}</span>
            </div>}
            width="90%"
            footer={null}
            onCancel={this.closeDesc.bind(this)}
          >
            <Visit
              data={rowData}
              addbt={false}
            />
          </Modal>
        }
      </div>
    );
  }
}

export default SignCustomer;
