import React from 'react';
import { AutoComplete,Icon, Button, Input, Select, Spin, Table, DatePicker, message, Cascader, Switch, Modal } from 'antd';
import { contractStateList, contractTypeList } from '../../../dataDic.js';
import { provinceSelect, getProvince } from '../../../NewDicProvinceList';
import { companySearch, getContractState, getContractType, getSearchUrl } from '../../../tools.js';
import ajax from 'jquery/src/ajax/xhr.js';
import $ from 'jquery/src/ajax';
import ContractAdd from './contractAdd.jsx';
import ContractDetail from './contractDetail.jsx';
const Option = AutoComplete.Option;
import moment from 'moment';
import './contract.less';

const Contract = React.createClass({
    loadData(pageNo) {
        this.state.data = [];
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/contract/list",
            data: {
                pageNo: pageNo || 1,
                pageSize: this.state.pagination.pageSize,
                province: this.state.province ? this.state.province[0] : undefined,
                uid: this.state.khId,
                type: this.state.contractType,
                status: this.state.contractState,
                contractId: this.state.contractId,
                startDateFormattedDate: this.state.startDateFormattedDate,
                endDateFormattedDate: this.state.endDateFormattedDate,
            },
            success: function (data) {
                if (data.error.length || !data.data || !data.data.list) {
                    message.warning(data.error[0].message);
                    return;
                };
                for (let i = 0; i < data.data.list.length; i++) {
                    let thisdata = data.data.list[i];
                    this.state.data.push({
                        key: i,
                        completeDate: thisdata.completeDate,
                        completeDateFormattedDate: thisdata.completeDateFormattedDate,
                        contacts: thisdata.contacts,
                        depict: thisdata.depict,
                        founder: thisdata.founder,
                        id: thisdata.id,
                        province: thisdata.province,
                        serialNumber: thisdata.serialNumber,
                        signDate: thisdata.signDate,
                        signDateFormattedDate: thisdata.signDateFormattedDate,
                        status: thisdata.status,
                        type: thisdata.type,
                        uid: thisdata.uid,
                        unitName: thisdata.unitName,
                    });
                };
                this.state.pagination.defaultCurrent = data.data.pageNo;
                this.state.pagination.total = data.data.totalCount;
                this.setState({
                    dataSource: this.state.data,
                    pagination: this.state.pagination
                });
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getAuthorList() {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/contract/principal",
            success: function (data) {
                if (!data.data) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                    };
                    return;
                };
                let _me = this, theArr = [];
                for (var item in data.data) {
                    theArr.push(
                        <Select.Option value={item} key={item}>{data.data[item]}</Select.Option>
                    )
                };
                this.setState({
                    authorOption: theArr
                });
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getCompanyList() {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/getUnitNames",
            success: function (data) {
                if (data.error.length || !data.data) {
                    return;
                };
                let _me = this, theArr = [];
                for (var item in data.data) {
                    theArr.push(
                        <Select.Option value={item} key={item}>{data.data[item]}</Select.Option>
                    )
                };
                this.setState({
                    companyOption: theArr
                });
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getStateList() {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/contract/status",
            success: function (data) {
                if (!data.data) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                        return;
                    };
                };
                let _me = this, theArr = [];
                for (var item in data.data) {
                    theArr.push(
                        <Select.Option value={item} key={item}>{data.data[item]}</Select.Option>
                    )
                };
                this.setState({
                    statusOption: theArr
                });
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getInitialState() {
        return {
            visible: false,
            data: [],
            loading: false,
            showAdd: false,
            showDesc: false,
            searchMore: true,
            selectedRowKeys: [],
            selectedRows: [],
            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: 'serialNumber',
                    key: 'serialNumber',
                }, {
                    title: '省份',
                    dataIndex: 'province',
                    key: 'province',
                    render: text => { return getProvince(text); }
                }, {
                    title: '公司名称',
                    dataIndex: 'unitName',
                    key: 'unitName',
                }, {
                    title: '签订时间',
                    dataIndex: 'signDateFormattedDate',
                    key: 'signDateFormattedDate',
                }, {
                    title: '合同状态',
                    dataIndex: 'status',
                    key: 'status',
                    render: (text) => { return getContractState(text) }
                }, {
                    title: '合同类型',
                    dataIndex: 'type',
                    key: 'type',
                    render: (text) => { return getContractType(text) }
                }, {
                    title: '创建人',
                    dataIndex: 'founder',
                    key: 'founder'
                }, {
                    title: '技术员',
                    dataIndex: 'techPrincipal',
                    key: 'techPrincipal',
                }, {
                    title: '描述',
                    dataIndex: 'describe',
                    key: 'describe',
                }
            ],
            dataSource: []
        };
    },
    getContractList() {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/contract/serialNumber",
            success: function (data) {
                if (!data.data) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                    };
                    return;
                };
                let theArr = [];
                for (let i = 0; i < data.data.length; i++) {
                    let item = data.data[i];
                    theArr.push(
                        <Select.Option value={item.contractId} key={item.contractId}>{item.serialNumber}</Select.Option>
                    );
                };
                this.setState({
                    contractListOption: theArr
                });
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    componentWillMount() {
        let _me = this, tArr = [], sArr = [];
        contractTypeList.map(function (item) {
            tArr.push(
                <Select.Option value={item.value} key={item.key}>{item.key}</Select.Option>
            )
        });
        contractStateList.map(function (item) {
            sArr.push(
                <Select.Option value={item.value} key={item.key}>{item.key}</Select.Option>
            )
        });
        this.setState({
            typeOption: tArr,
            stateOption: sArr
        });
        this.getAuthorList();
        this.getCompanyList();
        this.getStateList();
        this.getContractList();
        if (window.location.search) {
            let theObj = getSearchUrl(window.location.search);
            if (theObj.rid) {
                theObj.id = theObj.rid;
                if (theObj.rid != 'null' && theObj.uid != 'null') {
                    this.tableRowClick(theObj);
                };
            };
        };
        this.loadData();
    },
    tableRowClick(record, index) {
        this.state.RowData = record;
        if (record.status === '0') {
            this.setState({
                showAdd: true
            });
        } else {
        	if(index!=undefined){
        		this.setState({
               		 showDesc: true
           		 });
        	}
        };
    },
    delectRow() {
        let deletedIds = [];
        for (let idx = 0; idx < this.state.selectedRows.length; idx++) {
            let rowItem = this.state.selectedRows[idx];
            if (rowItem.id) {
                deletedIds.push(rowItem.id)
            };
        };
        this.setState({
            selectedRowKeys: [],
            loading: deletedIds.length > 0
        });
        $.ajax({
            method: "POST",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/contract/delete",
            data: {
                ids: deletedIds
            }
        }).done(function (data) {
            if (!data.error.length) {
                message.success('删除成功！');
                this.setState({
                    loading: false,
                });
            } else {
                message.warning(data.error[0].message);
            };
            this.loadData();
        }.bind(this));
    },
    closeDesc(e, s) {
        this.state.showDesc = e;
        if (s) {
            this.loadData();
        };
    },
    addClick() {
        this.setState({
            showAdd: true
        });
    },
    closeAdd(e, s) {
        this.setState({
            showAdd: e
        });
        if (s) {
            this.loadData();
        };
    },
    searchSwitch() {
        this.setState({
            searchMore: !this.state.searchMore
        });
    },
    search() {
        this.loadData();
    },
    reset() {
    	this.state.names='';
        this.state.province = undefined;
        this.state.unitId = undefined;
        this.state.contractState = undefined;
        this.state.contractType = undefined;
        this.state.contractId = undefined;
        this.state.startDateFormattedDate = undefined;
        this.state.endDateFormattedDate = undefined;
        this.loadData();
    },
    //客户名称初始加载
	customerList(e){ 
		$.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/customer/findCustomerByName",
            data:{
            	name:e
            },
            success: function (data) {                	  
				       let thedata=data.data;
				    if (!thedata) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                    };	
                    thedata = {}; 
               }; 
					this.setState({
						customerArr:thedata,	
                    });
				}.bind(this),
			}).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));  
	},
    //值改变时请求客户名称
	httpChange(e){
		this.setState({
			names:e
		})
		if(e.length>=2){
			this.customerList(e); 
			return false;
		}
	},
    //客户输入框失去焦点是判断客户是否存在
	blurChange(e){
		let theType='';
		let contactLists=this.state.customerArr||[];
			if (e) {
            contactLists.map(function (item) {
                if (item.name == e.toString()) {
                    theType = item.id;
                }
           });     
        }	
		 if(!theType){
		 	 theType='';
			 return message.warning('当前客户名不存在') 
		};
		this.setState({
			khId:theType
		})
	},
	//获取联系人下拉框
	getNewWoman(ids) { 
         $.ajax({
                method: "get",
                dataType: "json",
                crossDomain: false,
                url: globalConfig.context + "/api/admin/customer/findCustomerContacts",
                data:{
                	uid:ids,
                },
                success: function (data) {                	  
                		let theArr = [];
								    let thedata=data.data;
								    if (!thedata) {
					                    if (data.error && data.error.length) {
					                        message.warning(data.error[0].message);
					                    };	
					                    thedata = {}; 
					               };   
							      thedata.map(function (item,index) {	
							          	theArr.push(<Select.Option value={index}>{item.name}</Select.Option>)						          
				            });
				           let telNum=thedata.telNum;
				           
						       this.setState({
						       		 telNumArr:thedata,
						       		 nub:thedata.telNum?thedata[0].telNum:'',
		                   orderStatusOption: theArr, 
	                 });
					}.bind(this),
				}).always(function () {
	            this.setState({
	                loading: false
	            });
	        }.bind(this));
	},
    render() {
        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedRows: selectedRows,
                    selectedRowKeys: selectedRowKeys
                });
            }
        };
        const dataSources=this.state.customerArr || [];
        const options = dataSources.map((group) =>
				      <Option key={group.id} value={group.name}>{group.name}</Option>
				     );
        const hasSelected = this.state.selectedRowKeys.length > 0;
        return (
            <div className="foster-box">
                <div className="foster-content">
                    <div className="content-title">
                        <span>合同申请管理</span>
                        <ContractAdd
                            companyOption={this.state.companyOption}
                            authorOption={this.state.authorOption}
                            typeOption={this.state.typeOption}
                            data={this.state.RowData}
                            onClick={this.addClick}
                            showAdd={this.state.showAdd}
                            closeAdd={this.closeAdd} />
                    </div>
                    <div className="foster-query">
                        <Cascader placeholder="选择省份"
                            style={{ width: 100, marginTop: "-4px" }}
                            value={this.state.province}
                            options={provinceSelect()}
                            showSearch
                            filterOption={companySearch}
                            onChange={(e) => { this.setState({ province: e }) }} />
                        <AutoComplete
					        className="certain-category-search"
					        dropdownClassName="certain-category-search-dropdown"
					        dropdownMatchSelectWidth={false}
					        dropdownStyle={{ width: '150px' }}
					        size="large"
					        style={{ width: '150px' }}
					        dataSource={options}
					        placeholder="输入名称"
					        optionLabelProp="value" 
					        onChange={this.httpChange}
					        onSelect={this.autoChange}
					        filterOption={true}
					        onBlur={this.blurChange}
					        value={this.state.names}
						      >
						    <Input />
						</AutoComplete>
                        <Select placeholder="选择合同编号"
                            style={{ width: 120 }}
                            value={this.state.contractId}
                            showSearch
                            filterOption={companySearch}
                            onChange={(e) => { this.setState({ contractId: e }) }}>
                            {this.state.contractListOption}
                        </Select>
                        <Select placeholder="选择一个合同类型"
                            style={{ width: 200 }}
                            value={this.state.contractType}
                            showSearch
                            filterOption={companySearch}
                            onChange={(e) => { this.setState({ contractType: e }) }}>
                            {this.state.typeOption}
                        </Select>
                        <Select style={{ width: 120 }}
                            value={this.state.contractState}
                            onChange={(e) => { this.setState({ contractState: e }) }}
                            placeholder="选择一个状态">
                            {this.state.stateOption}
                        </Select>
                        <span>更多搜索  <Switch defaultChecked={false} onChange={this.searchSwitch} /></span>
                        <Button type="primary" onClick={this.search}>搜索</Button>
                        <Button onClick={this.reset}>重置</Button>
                        <Button style={{ background: "#3fcf9e", border: "none", color: "#fff" }}
                            disabled={!hasSelected}
                            onClick={this.delectRow}>删除<Icon type="minus" /></Button>
                        <div className="search-more" style={this.state.searchMore ? { display: 'none' } : {}}>
                            <span>签订时间:</span>
                            <DatePicker style={{ width: '140px' }}
                                allowClear={false}
                                value={this.state.startDateFormattedDate ? moment(this.state.startDateFormattedDate) : null}
                                onChange={(date, dateString) => { this.setState({ startDateFormattedDate: dateString }) }} />
                            <span>到</span>
                            <DatePicker style={{ width: '140px' }}
                                allowClear={false}
                                value={this.state.endDateFormattedDate ? moment(this.state.endDateFormattedDate) : null}
                                onChange={(date, dateString) => { this.setState({ endDateFormattedDate: dateString }) }} />
                        </div>
                    </div>
                    <div className="foster-table">
                        <Spin spinning={this.state.loading}>
                            <Table columns={this.state.columns}
                                dataSource={this.state.dataSource}
                                rowSelection={rowSelection}
                                pagination={this.state.pagination}
                                onRowClick={this.tableRowClick} />
                        </Spin>
                    </div>
                    <ContractDetail
                        data={this.state.RowData}
                        authorOption={this.state.authorOption}
                        statusOption={this.state.statusOption}
                        showDesc={this.state.showDesc}
                        closeDesc={this.closeDesc} />
                </div >
            </div>
        );
    }
});

export default Contract;