import React from 'react';
import { Button,Cascader,Input, Select, Spin, Table, message, Form, Tabs} from 'antd';
import ajax from 'jquery/src/ajax/xhr.js';
import $ from 'jquery/src/ajax';
import { citySelect, provinceList } from '@/NewDicProvinceList';
import {ShowModal} from '../../../../tools.js'
import ShowModalDiv from "@/showModal.jsx";
import {ChooseList} from "../../../order/orderNew/chooseList";

const QueryCustomer = React.createClass({
	loadData(pageNo, apiUrl) {
		this.setState({
			loading: true,
			ispage:pageNo,
		});
		let api=apiUrl?apiUrl:this.props.ApiUrl;
		$.ajax({
      method: "post",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + api,
      data: {
        pageNo: pageNo || 1,
        pageSize: this.state.pagination.pageSize,
        name: this.state.nameSearch,
        province: !this.state.addressSearch.length
          ? this.state.provinceSearch
          : this.state.addressSearch[0],
        city: !this.state.addressSearch.length
          ? ""
          : this.state.addressSearch[1],
        sort: this.state.sort
      },
      success: function (data) {
        ShowModal(this);
        let theArr = [];
        if (data.error.length || data.data.list == "") {
          if (data.error && data.error.length) {
            message.warning(data.error[0].message);
          }
        } else {
          for (let i = 0; i < data.data.list.length; i++) {
            let thisdata = data.data.list[i];
            theArr.push({
              key: i,
              id: thisdata.uid,
              name: thisdata.name,
              contacts: thisdata.contacts,
              contactMobile: thisdata.contactMobile,
              createTime:
                thisdata.createTime && thisdata.createTime.split(" ")[0],
              transferTime:
                thisdata.transferTime && thisdata.transferTime.split(" ")[0],
              locationProvince: thisdata.province
                ? (thisdata.province || '')  + (thisdata.city ? "-" + thisdata.city : '') + (thisdata.area ? "-" + thisdata.area : '')
                : "--",
            });
          }
          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,
          selectedRowKeys: [],
        });
      }.bind(this),
    }).always(
      function () {
        this.setState({
          loading: false,
        });
      }.bind(this)
    );
	},
	getInitialState(){
		return {
			sort: 0,
			addressSearch: [],
			dataSource:[],
			loading:false,
			selectedRowKeys: [],
			selectedRows:[],
			selectedData:[],
			pagination: {
				defaultCurrent: 1,
				defaultPageSize: 10,
				showQuickJumper: true,
				pageSize: 10,
				onChange: function(page) {
					this.loadData(page);
				}.bind(this),
				showTotal: function(total) {
					return '共' + total + '条数据';
				}
			},
			columns: [{
					title: '客户名称',
					dataIndex: 'name',
					key: 'name',
				}, {
					title: '地区',
					dataIndex: 'locationProvince',
					key: 'locationProvince',
				},
				// {
				// 	title: '联系人',
				// 	dataIndex: 'contacts',
				// 	key: 'contacts',
				// },{
				// 	title: '联系电话',
				// 	dataIndex: 'contactMobile',
				// 	key: 'contactss',
				// },
				{
					title: '创建时间',
					dataIndex: 'createTime',
					key: 'createTime',
				},
				{
					title: '转换时间',
					dataIndex: 'transferTime',
					key: 'transferTime',
				},
				{
					title: '操作',
					dataIndex: 'abc',
					key: 'abc',
					render: (text, record, index) => {
						return <div>
                            <Button onClick={(e) =>{ e.stopPropagation(), this.receive(record)}} type="primary">领取</Button>
                        </div>
					}
				}
			],
		}
	},
	/*单个领取*/
	receive(e) {
		this.setState({
			loading: true,
			selectedRowKeys: [],
		});
		$.ajax({
			method: "get",
			dataType: "json",
			crossDomain: false,
			url: globalConfig.context + "/api/admin/customer/receiveCustomer",
			data: {
				uid: e.id,
			}
		}).done(function(data) {
			if(!data.error.length) {
				message.success('领取成功!');
				this.setState({
					loading: false,
				});
			} else {
				message.warning(data.error[0].message);
			};
			this.loadData(this.state.ispage);
		}.bind(this));
	},
	closeDesc(e) {
		this.state.visitModul = e;
	},
	search() {
		this.loadData();
	},
	reset() {
		this.state.nameSearch='';
		this.state.provinceSearch=undefined;
		this.state.addressSearch=[];
		this.state.sort = 0
		this.loadData()
	},
	componentWillReceiveProps(nextProps) {
		if(nextProps.ApiUrl!=this.props.ApiUrl) {
			this.state.nameSearch='';
			this.state.provinceSearch=undefined;
			this.state.addressSearch=[];
			this.loadData(null,nextProps.ApiUrl);
		};
	},
	componentWillMount() {
		//城市
		let Province = [];
		provinceList.map(function(item) {
			var id = String(item.id)
			Province.push(
				<Select.Option value={id} key={item.name}>{item.name}</Select.Option>
			)
		});
		this.state.Provinces = Province;
		this.loadData();
	},
	changeList(arr) {
		const newArr = [];
		this.state.columns.forEach(item => {
			arr.forEach(val => {
				if (val === item.title) {
					newArr.push(item);
				}
			});
		});
		this.setState({
			changeList: newArr
		});
	},
	render(){
		const intentionState=this.props.intentionState;
		const FormItem = Form.Item;
		const {TabPane} = Tabs
		const rowSelection = {
			selectedRowKeys: this.state.selectedRowKeys,
			onChange: (selectedRowKeys, selectedRows) => {
				this.setState({
					selectedRows:selectedRows,
					selectedRowKeys: selectedRowKeys
				});
			},
			onSelect: (recordt, selected, selectedData) => {
				this.setState({
					selectedData:selectedData,
					recordt: recordt.id
				})
			},

		};
		return (
      <div className="user-content">
        <ShowModalDiv ShowModal={this.state.showModal} />
        <div className="content-title">
          <span>{!intentionState ? "单位公共客户" : "个人公共客户"}</span>
        </div>
        <Tabs defaultActiveKey="1" onChange={this.callback} className="test">
          <TabPane tab="搜索" key="1">
            <div className="user-search">
              <Input
                placeholder="客户名称"
                value={this.state.nameSearch}
                style={{ width: 150 }}
                onChange={(e) => {
                  this.setState({ nameSearch: e.target.value });
                }}
              />
              <Select
                placeholder="省"
                style={{ width: 80 }}
                value={this.state.provinceSearch}
                onChange={(e) => {
                  this.setState({ provinceSearch: e });
                }}
              >
                {this.state.Provinces}
              </Select>
              <span style={{ marginRight: "10px" }}>
                <Cascader
                  options={citySelect()}
                  value={this.state.addressSearch}
                  placeholder="选择城市"
                  onChange={(e, pre) => {
                    this.setState({ addressSearch: e });
                  }}
                />
              </span>
			  <span>排序：</span>
              <Select style={{ width: 120 }} value={this.state.sort} onChange={e => {this.setState({sort: e})}} placeholder="选择排序">
                <Option value={0}>默认</Option>
                <Option value={1}>降序</Option>
                <Option value={2}>升序</Option>
              </Select>
              <Button type="primary" onClick={this.search}>
                搜索
              </Button>
              <Button onClick={this.reset}>重置</Button>
            </div>
          </TabPane>
			<TabPane tab="更改表格显示数据" key="2">
				<div style={{ marginLeft: 10 }}>
					<ChooseList
						columns={this.state.columns}
						changeFn={this.changeList}
						changeList={this.state.changeList}
						top={55}
						margin={11}
					/>
				</div>
			</TabPane>
        </Tabs>
        <div className="patent-table">
          <Spin spinning={this.state.loading}>
            <Table
			  size="middle"
			  columns={
				  this.state.changeList
					  ? this.state.changeList
					  : this.state.columns
			  }
              dataSource={this.state.dataSource}
              // rowSelection={rowSelection}
              pagination={this.state.pagination}
            />
          </Spin>
        </div>
      </div>
    );
	}
})
export default QueryCustomer;
