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

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

const ALL_TYPE = {
  0: '公出协单',
  1: '非公出协单'
}
class NoPublicStatistics extends Component {
  constructor(props) {
    super(props);
    this.state = {
      pageNo: 1,
      loading: false,
      changeList: undefined,
      columns: [
        {
          title: "序号",
          dataIndex: "key",
          key: "key",
          width: 45,
        },
        {
          title: "协单类型",
          dataIndex: "type",
          key: "type",
          width: 80,
        },
        {
          title: "内容",
          dataIndex: "content",
          key: "content",
          width: 140,
        },
        {
          title: "发起人员",
          dataIndex: "aname",
          key: "aname",
          width: 75,
        },
        {
          title: "协单人员",
          dataIndex: "assistAidName",
          key: "assistAidName",
          width: 120,
        },
        {
          title: "客户名称",
          dataIndex: "userNames",
          key: "userNames",
          width: 140,
        },
        {
          title: "签单次数",
          dataIndex: "signNumber",
          key: "signNumber",
          width: 70,
          textAlign: 'center'
        },
        {
          title: "公出次数（累计数）",
          dataIndex: "publicCount",
          key: "publicCount",
          width: 80,
        },
        {
          title: "协单数总数/协单/非公出协单",
          dataIndex: "xdcs",
          key: "xdcs",
          width: 95,
          render(text, record) {
            let assistCEle = <span>{ record.assistCount }</span>
            if ( record.assistCount > 5 ) {
              assistCEle = <span style={{ color: 'red' }}>{ record.assistCount }</span>
            }
            return <div>
              { assistCEle }
              <span>/{ record.publicAssistCount }</span>
              <span>/{ record.nonPublicCount }</span>
            </div>
          },
        },
        {
          title: "协单时间",
          dataIndex: "releaseStart",
          key: "releaseStart  ",
          width: 140,
        },
        {
          title: "协单项目",
          dataIndex: "assistType",
          key: "assistType",
          width: 260,
        },
        {
          title: "已签项目",
          dataIndex: "taskNames",
          key: "taskNames ",
          minWidth: 300,
        },
      ],
      pagination: {
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        pageSize: 10,
        onChange: function (page) {
          this.loadData(page);
        }.bind(this),
        showTotal: function (total) {
          return "共" + total + "条数据";
        },
      },
      dataSource: [],
      type: undefined, // 协单类型
      contentType: [], // 协单内容
      assistType: [], // 协单项目类型
      releaseDate: [moment(Date.now() - 777600000).format('YYYY-MM-DD'), moment(Date.now()).format('YYYY-MM-DD')],
      deptId: undefined, // 公出部门
      theTypes: undefined,
      theTypes1: undefined,
      theCustomerTypes: undefined,
      assistCount: undefined, // 协单总数
      
    };
    this.loadData = this.loadData.bind(this);
    this.resetAll = this.resetAll.bind(this);
    this.changeList = this.changeList.bind(this);
    this.httpChange = this.httpChange.bind(this);
    this.blurChange = this.blurChange.bind(this);
    this.selectAuto = this.selectAuto.bind(this);
    this.httpChange1 = this.httpChange1.bind(this);
    this.blurChange1 = this.blurChange1.bind(this);
    this.selectAuto1 = this.selectAuto1.bind(this);
    this.getCustomer = this.getCustomer.bind(this);
    this.selectCustomerAuto = this.selectCustomerAuto.bind(this);
    this.httpCustomerChange = this.httpCustomerChange.bind(this);
    this.blurCustomerChange = this.blurCustomerChange.bind(this);
    this.exportExec = this.exportExec.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,
    });
  }

  getSearchParams() {
    const { type, contentType, assistType, theTypes, theTypes1, deptId, releaseDate, assistCount } = this.state
    return {
      type,
      contentType: contentType && contentType.length ? contentType.join(',') : undefined,
      assistType: assistType && assistType.length ? assistType.join(',') : undefined,
      aid: theTypes || undefined, // 公出人员
      assistAid: theTypes1 || undefined, // 协单人员
      deptId,
      startTime: releaseDate[0] || undefined,
      endTime: releaseDate[1] || undefined,
      assistCount,
    }
  }

  loadData(pageNo) {
    this.setState({
      loading: true,
    });
    const paramsData = Object.assign({
      pageNo: pageNo || 1,
      pageSize: this.state.pagination.pageSize
    }, this.getSearchParams())
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/release/listAssist",
      data: paramsData,
      success: function (data) {
        ShowModal(this);
        let theArr = [];
        this.setState({
          loading: false,
        });
        if (data.error && data.error.length === 0) {
          for (let i = 0; i < data.data.list.length; i++) {
            let thisdata = data.data.list[i];
            thisdata.key = (data.data.pageNo - 1) * data.data.pageSize + i + 1;
            theArr.push(thisdata);
          }
          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: theArr,
            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)
    );
  }

  resetAll() {
    this.setState(
      {
        releaseDate: [moment(Date.now() - 777600000).format('YYYY-MM-DD'), moment(Date.now()).format('YYYY-MM-DD')],
        type: undefined,
        contentType: [],
        assistType: [],
        theTypes: undefined,
        theTypes1: undefined,
        deptId: undefined,
        assistCount: undefined
      },
      () => {
        this.Cascaders.empty();
        this.loadData();
      }
    );
  }

  getSupervisorList(e, succCallback) {
    $.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) {
          succCallback && succCallback(data.data)
        } else {
          message.warning(data.error[0].message);
        }
      }.bind(this),
    });
  }

  httpChange(e) {
    if (e.length >= 1) {
      this.getSupervisorList(e, (data) => {
        this.setState({
          customerArr: data
        })
      })
    }
    this.setState({
      auto: e,
    });
  }

  httpChange1(e) {
    if (e.length >= 1) {
      this.getSupervisorList(e, (data) => {
        this.setState({
          customerArr1: data
        })
      })
    }
    this.setState({
      auto1: e,
    });
  }

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

  selectAuto1(value, options) {
    this.setState({
      auto1: value,
    });
  }

  httpCustomerChange(e) {
    if (e.length >= 1) {
      this.getCustomer(e);
    }
    this.setState({
      customer: e,
    });
  }

  selectCustomerAuto(value, options) {
    this.setState({
      customer: value,
    });
  }

  getCustomer(e) {
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + "/api/admin/customer/getUserByName",
      data: {
        name: e,
      },
      success: function (data) {
        if (data.error && data.error.length === 0) {
          this.setState({
            customerList: data.data,
          });
        } else {
          message.warning(data.error[0].message);
        }
      }.bind(this),
    });
  }

  findDataIdByName(e, list = []) {
    if (list && list.length) {
      return list.find(item => item.name == e.toString()).id
    }
    return
  }

  blurCustomerChange(e) {
    const { contactLists } = this.state
    this.setState({
      theCustomerTypes: this.findDataIdByName.bind(this, e, contactLists),
    });
  }
  
  blurChange(e) {
    const { customerArr } = this.state
    this.setState({
      theTypes: this.findDataIdByName.bind(this, e, customerArr),
    });
  }

  blurChange1(e) {
    const { customerArr1 } = this.state
    this.setState({
      theTypes1: this.findDataIdByName.bind(this, e, customerArr1),
    });
  }

  componentWillMount() {
    this.loadData();
  }

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

    const paramsData = this.getSearchParams()

    let newParams = {}
    Object.keys(paramsData).map(key => {
      if (paramsData[key]) {
        newParams[key] = paramsData[key]
      }
    })

    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url:
        globalConfig.context + "/api/admin/release/listAssistExprot",
      data: newParams,
      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;
  }

  render() {
    const dataSources = this.state.customerArr || [];
    const dataSources1 = this.state.customerArr1 || [];
    const options = dataSources.map((group) => (
      <Select.Option key={group.id} value={group.name}>
        {group.name}
      </Select.Option>
    ));
    const options1 = dataSources1.map((group) => (
      <Select.Option key={group.id} value={group.name}>
        {group.name}
      </Select.Option>
    ));
    const customerList = this.state.customerList || [];
    const customerOptions = customerList.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>协单统计</span>
          </div>
          <Tabs defaultActiveKey="1" className="test">
            <TabPane tab="搜索" key="1">
              <div
                className="user-search"
                style={{
                  marginTop: "10px",
                  marginLeft: "10px",
                  marginRight: "10px",
                }}
              >
                <span>
                  <Select
                    placeholder="全部协单类型"
                    style={{ width: 120 }}
                    value={this.state.type}
                    onChange={(e) => {
                      this.setState({ type: e });
                    }}
                  >
                    {
                      Object.keys(ALL_TYPE).map(key =>
                        <Select.Option value={key}>{ ALL_TYPE[key] }</Select.Option>
                      )
                    }
                  </Select>
                </span>
                <span>
                  <Select
                    placeholder="请选择协单内容"
                    style={{ width: 120 }}
                    value={this.state.contentType}
                    onChange={(e) => {
                      this.setState({ contentType: e });
                    }}
                    multiple
                  >
                    { 
                      assistContentOptions.map(item =>
                        <Select.Option value={item.value}>{item.label}</Select.Option>
                      )
                    }
                  </Select>
                </span>
                <span>
                  <AutoComplete
                    className="certain-category-search"
                    dropdownClassName="certain-category-search-dropdown"
                    dropdownMatchSelectWidth={false}
                    style={{ width: "120px" }}
                    dataSource={options}
                    placeholder="输入公出发起人"
                    value={this.state.auto}
                    onChange={this.httpChange}
                    filterOption={true}
                    onBlur={this.blurChange}
                    onSelect={this.selectAuto}
                  >
                    <Input />
                  </AutoComplete>
                </span>
                <span>
                  <AutoComplete
                    className="certain-category-search"
                    dropdownClassName="certain-category-search-dropdown"
                    dropdownMatchSelectWidth={false}
                    style={{ width: "120px" }}
                    dataSource={options1}
                    placeholder="输入协单人员"
                    value={this.state.auto1}
                    onChange={this.httpChange1}
                    filterOption={true}
                    onBlur={this.blurChange1}
                    onSelect={this.selectAuto1}
                  >
                    <Input />
                  </AutoComplete>
                </span>
                <span>
                  <AutoComplete
                    className="certain-category-search"
                    dropdownClassName="certain-category-search-dropdown"
                    dropdownMatchSelectWidth={false}
                    style={{ width: "160px" }}
                    dataSource={customerOptions}
                    placeholder="输入客户名称"
                    value={this.state.customer}
                    onChange={this.httpCustomerChange}
                    filterOption={true}
                    onBlur={this.blurCustomerChange}
                    onSelect={this.selectCustomerAuto}
                  >
                    <Input />
                  </AutoComplete>
                </span>
                <span>
                  <Select
                    placeholder="请选择协单项目"
                    style={{ width: 180 }}
                    value={this.state.assistType}
                    onChange={(e) => {
                      this.setState({ assistType: e });
                    }}
                    multiple
                  >
                    { 
                      assistTypeOptions.map(item =>
                        <Select.Option value={item.value}>{item.label}</Select.Option>
                      )
                    }
                  </Select>
                </span>
                <span style={{ marginRight: "10px" }}>
                  <span style={{ marginRight: "5px", marginBottom: "10px" }}>
                    协单时间:
                  </span>
                  <RangePicker
                    allowClear={window.adminData.shiroList.indexOf("11") == -1}
                    disabledDate={(current) => {//“运营管理”角色只能查看部分时间段（暂时10天）的数据
                      let iskeep = window.adminData.shiroList.indexOf("11") != -1
                      return iskeep && current && current.valueOf() < Date.now() - 864000000;
                    }}
                    style={{ marginRight: "10px", marginBottom: "10px", width: 200 }}
                    value={[
                      this.state.releaseDate[0]
                        ? moment(this.state.releaseDate[0])
                        : null,
                      this.state.releaseDate[1]
                        ? moment(this.state.releaseDate[1])
                        : null,
                    ]}
                    onChange={(data, dataString) => {
                      this.setState({ releaseDate: dataString });
                    }}
                  />
                </span>
                <Cascaders
                  ref={node => this.Cascaders = node}
                  placeholder="请选择公出部门"
                  id="id"
                  name="name"
                  children="list"
                  height={28}
                  onSel={(e) => {
                    this.setState({
                      deptId: JSON.stringify(e),
                    });
                  }}
                />
                <span>
                  <Select
                    placeholder="请选择协单总数"
                    style={{ width: 120 }}
                    value={this.state.assistCount}
                    onChange={(e) => {
                      this.setState({ assistCount: e });
                    }}
                  >
                    <Select.Option value={1}>小于5</Select.Option>
                    <Select.Option value={2}>5-9</Select.Option>
                    <Select.Option value={3}>10-14</Select.Option>
                    <Select.Option value={4}>大于14</Select.Option>
                  </Select>
                </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
                  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"
                columns={
                  this.state.changeList
                    ? this.state.changeList
                    : this.state.columns
                }
                dataSource={this.state.dataSource}
                pagination={this.state.pagination}
              />
            </Spin>
          </div>
        </div>
      </div>
    );
  }
}

export default NoPublicStatistics;
