import React, { Component } from "react";
import {
  Form,
  Button,
  DatePicker,
  Input,
  message,
  Select,
  Spin,
  Table,
  Tabs,
  AutoComplete,
} from "antd";
import { ShowModal } from "@/tools";
import { ChooseList } from "../../manageCenter/order/orderNew/chooseList";
import $ from "jquery/src/ajax";
import moment from "moment";
import AutoCompleteSearch from "./autoCompleteSearch";
import Cascaders from "../cascaders"

const { TabPane } = Tabs;
const { RangePicker, MonthPicker } = DatePicker;
const FormItem = Form.Item;

class TabelContent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      changeList: undefined,
      dataSource: [],
      pagination: {
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        pageSize: 10,
        onChange: function (page) {
          this.loadData(page);
        }.bind(this),
        showTotal: function (total) {
          return "共" + total + "条数据";
        },
      },
      searchValues: this.props.searchConfig || {},
      contactsOption: [],
      departmentLoading: false,
    };
    this.loadData = this.loadData.bind(this);
    this.resetAll = this.resetAll.bind(this);
    this.exportExec = this.exportExec.bind(this);
    this.selectSuperId = this.selectSuperId.bind(this);
    this.onRefresh = this.onRefresh.bind(this);
    this.changeList = this.changeList.bind(this);
    this.autoCompleteSearchRef = {};
  }

  loadData(pageNo) {
    this.setState({
      loading: true,
    });
    let searchInfor = {
      pageNo: pageNo || 1,
      pageSize: this.state.pagination.pageSize,
    };
    if (this.props.query) {
      let obj = JSON.parse(JSON.stringify(this.props.query));
      searchInfor = Object.assign(searchInfor, obj);
    }

    if (Object.keys(this.state.searchValues).length > 0) {
      let obj1 = JSON.parse(JSON.stringify(this.state.searchValues));
      searchInfor = Object.assign(searchInfor, obj1);
      for (let i in searchInfor) {
        if (searchInfor[i] == "" && i == "startTime") {
          delete searchInfor.startTime;
        } else if (searchInfor[i] == "" && i == "endTime") {
          delete searchInfor.endTime;
        }
      }
    }
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + this.props.tabelApi,
      data: searchInfor,
      success: function (data) {
        ShowModal(this);
        this.setState({
          loading: false,
        });
        if (data.error && data.error.length === 0) {
          this.props.searchOperation && this.props.searchOperation(searchInfor);
          if (data.data.list) {
            this.state.pagination.current = data.data.pageNo;
            this.state.pagination.total = data.data.totalCount;
            if (data.data && data.data.list && !data.data.list.length) {
              this.state.pagination.current = 0;
              this.state.pagination.total = 0;
            }
            this.setState({
              dataSource: this.props.dataProcessing
                ? this.props.dataProcessing(data)
                : data.data.list,
              pagination: this.state.pagination,
              pageNo: data.data.pageNo,
            });
          } else {
            this.setState({
              dataSource: this.props.dataProcessing
                ? this.props.dataProcessing(data)
                : data.data,
              pagination: false,
            });
          }
        } else {
          message.warning(data.error[0].message);
        }
      }.bind(this),
    }).always(
      function () {
        this.setState({
          loading: false,
        });
      }.bind(this)
    );
  }

  exportExec() {
    // debugger
    // console.log(this.props.exportApi);
    message.config({
      duration: 20,
    });
    let loading = message.loading("下载中...");
    this.setState({
      exportPendingLoading: true,
    });

    let data = {};
    let obj1 = JSON.parse(JSON.stringify(this.state.searchValues));
    // console.log(obj1);
    data = Object.assign(data, obj1);

    if (this.props.exportExecProcessing) {
      data = this.props.exportExecProcessing(data);
    }
    // console.log(data);
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: this.props.exportApi,
      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;
  }

  //获取上级组织
  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)
    );
  }

  componentDidMount() {
    this.loadData();
    if (this.props.searchList) {
      let arr = this.props.searchList.filter(
        (v) => v.type === "departmentSelect"
      );
      let arr1 = this.props.searchList.filter((v) => v.defaultValue);
      if (arr.length > 0) {
        // this.selectSuperId();
      }
      if (arr1.length > 0) {
        for (let i of arr1) {
          this.state.searchValues[i.dataKey] = i.defaultValue;
        }
      }
    }
  }

  resetAll() {
    for (let i of Object.keys(this.autoCompleteSearchRef)) {
      this.autoCompleteSearchRef[i].onReset();
    }
    let obj = this.props.query || {};
    this.setState(
      {
        searchValues: JSON.parse(JSON.stringify(obj)),
      },
      () => {
        this.Cascaders.empty();
        this.loadData();
      }
    );
  }

  //刷新页面
  onRefresh(lv) {
    if (lv) {
      this.loadData();
    } else {
      this.loadData(this.state.pageNo);
    }
  }
  changeList(arr) {
    const newArr = [];
    this.props.columns.forEach((item) => {
      arr.forEach((val) => {
        if (val === item.title) {
          newArr.push(item);
        }
      });
    });
    this.setState({
      changeList: newArr,
    });
  }
  render() {
    const { searchValues } = this.state;
    // console.log(this.props.searchList);
    return (
      <div>
        <Tabs defaultActiveKey="1" className="test">
          {this.props.searchList && (
            <TabPane tab="搜索" key="1">
              <div className="user-search" style={{ paddingTop: "10px" }}>
                <Form layout="inline">
                  {(this.props.searchList || []).map((v, k) => {
                    return v.type === "text" ? (
                      <FormItem label={v.title} key={k}>
                        <Input
                          placeholder={v.placeholder}
                          value={
                            searchValues[v.dataKey]
                              ? searchValues[v.dataKey]
                              : v.defaultValue || undefined
                          }
                          style={
                            v.style ? v.style : { width: 150, marginRight: 10 }
                          }
                          onChange={(e) => {
                            searchValues[v.dataKey] = e.target.value;
                            this.setState({
                              searchValues: searchValues,
                            });
                          }}
                        />
                      </FormItem>
                    ) : v.type === "autoComplete" ? (
                      <FormItem
                        label={v.title}
                        style={{ marginTop: "-8px" }}
                        key={k}
                      >
                        <AutoCompleteSearch
                          ref={(ref) => {

                            // console.log(ref);

                            (this.autoCompleteSearchRef[v.dataKey] = ref)
                          }
                          }
                          value={searchValues[v.dataKey]}
                          onSelect={(value, title) => {
                            // console.log(value, title);
                            searchValues[v.dataKey] = value;
                            searchValues["aName"] = title;
                            if (v.dataTitle) {
                              searchValues[v.dataTitle] = title;
                            }
                            this.setState({
                              searchValues: searchValues,
                            });
                          }}
                          config={v}
                        />
                      </FormItem>
                    ) : v.type === "select" || v.type === "departmentSelect" ? (
                      <FormItem
                        label={v.title}
                        style={{ marginTop: "-8px" }}
                        key={k}
                      >
                        <Spin spinning={this.state.departmentLoading}>
                          {
                            <Select
                              placeholder={v.placeholder}
                              style={
                                v.style
                                  ? v.style
                                  : { width: 200, marginRight: 10 }
                              }
                              value={
                                searchValues[v.dataKey]
                                  ? searchValues[v.dataKey]
                                  : v.defaultValue || undefined
                              }
                              onChange={(e) => {
                                searchValues[v.dataKey] = String(e);
                                if (v.type === "departmentSelect") {
                                  let arr = this.state.contactsOption.filter(
                                    (v) => String(v.value) === String(e)
                                  );
                                  searchValues["depName"] = arr[0].label;
                                }
                                this.setState({
                                  searchValues: searchValues,
                                });
                              }}
                            >
                              {v.selectOptionList
                                ? v.selectOptionList()
                                : (v.type === "departmentSelect"
                                  ? this.state.contactsOption
                                  : v.selectList
                                    ? typeof v.selectList === "function"
                                      ? v.selectList()
                                      : v.selectList
                                    : []
                                ).map((v) => (
                                  <Select.Option
                                    key={v.value}
                                    value={v.value}
                                  >
                                    {v.label}
                                  </Select.Option>
                                ))}
                            </Select>
                          }
                        </Spin>
                      </FormItem>
                    ) : v.type === "times" ? (
                      <FormItem label={v.title} key={k}>
                        {v.format === "YYYY/MM" ? (
                          <MonthPicker
                            value={
                              searchValues[v.dataKey]
                                ? moment(searchValues[v.dataKey])
                                : null
                            }
                            style={{ marginRight: "10px", marginTop: "2px" }}
                            onChange={(data, dataString) => {
                              searchValues[v.dataKey] = String(dataString);
                              this.setState({
                                searchValues: searchValues,
                              });
                            }}
                          />
                        ) : (
                          <RangePicker
                            style={{ marginRight: "10px", marginTop: "2px" }}
                            value={[
                              searchValues[v.dataKey[0]]
                                ? moment(searchValues[v.dataKey[0]])
                                : null,
                              searchValues[v.dataKey[1]]
                                ? moment(searchValues[v.dataKey[1]])
                                : null,
                            ]}
                            onChange={(data, dataString) => {
                              searchValues[v.dataKey[0]] = String(
                                dataString[0]
                              );
                              searchValues[v.dataKey[1]] = String(
                                dataString[1]
                              );
                              this.setState({
                                searchValues: searchValues,
                              });
                            }}
                          />
                        )}
                      </FormItem>
                    ) : v.type === "types" ? (
                      <FormItem
                        label={v.title}
                        key={k}
                        style={{ bottom: "8px" }}
                      >
                        <Select
                          placeholder={v.placeholder}
                          style={
                            v.style ? v.style : { width: 200, marginRight: 10 }
                          }
                          value={
                            searchValues[v.dataKey]
                              ? searchValues[v.dataKey]
                              : v.defaultValue || undefined
                          }
                          onChange={(e) => {
                            searchValues[v.dataKey] = String(e);
                            // searchValues["statusName"] = arr[0].label;
                            this.setState({
                              searchValues: searchValues,
                            });
                          }}
                        >
                          <Option value="1">已完成法务/已回款</Option>
                          <Option value="2">已完成法务/已诉讼</Option>
                          <Option value="3">已完成法务/已坏账处理</Option>
                        </Select>
                      </FormItem>
                    ) : v.type === "newDepartmentSelect" ? (
                      <FormItem
                        label={v.title}
                        key={k}
                      >
                        <Cascaders
                          ref={node => this.Cascaders = node}
                          placeholder="请选择订单部门"
                          id="id"
                          name="name"
                          children="list"
                          height={28}
                          onSel={(e) => {
                            searchValues["deps"] = JSON.stringify(e);
                            this.setState({
                              searchValues: searchValues,
                            });
                          }}
                        />
                      </FormItem>
                    ) : null;
                  })}
                  <Button
                    type="primary"
                    onClick={() => {
                      this.loadData();
                    }}
                    style={{ marginRight: "10px", marginBottom: "10px" }}
                  >
                    搜索
                  </Button>
                  <Button
                    onClick={this.resetAll}
                    style={{ marginRight: "10px", marginBottom: "10px" }}
                  >
                    重置
                  </Button>
                </Form>
              </div>
            </TabPane>
          )}
          <TabPane tab="更改表格显示数据" key="2">
            <div style={{ marginLeft: 10 }}>
              <ChooseList
                columns={this.props.columns}
                changeFn={this.changeList}
                changeList={this.state.changeList}
                top={55}
                margin={11}
              />
            </div>
          </TabPane>
          {this.props.exportApi ? (
            <TabPane tab="导出" key="3">
              <div style={{ float: "left" }}>
                <Button
                  loading={this.state.exportPendingLoading}
                  onClick={this.exportExec}
                  style={{ margin: 10 }}
                >
                  导出excel
                </Button>
              </div>
            </TabPane>
          ) : ''}
        </Tabs>
        <div className="patent-table">
          <Spin spinning={this.state.loading}>
            <Table
              bordered
              size="middle"
              scroll={this.props.scroll}
              columns={
                this.state.changeList != undefined
                  ? this.state.changeList
                  : this.props.columns
              }
              onRowClick={this.props.onRowClick ? this.props.onRowClick : () => { }}
              dataSource={this.state.dataSource}
              pagination={this.state.pagination}
            />
          </Spin>
        </div>
      </div>
    );
  }
}

export default TabelContent;
