import React from 'react';
import {
	Icon,
	Button,
	AutoComplete,
	Input,
	Select,
	Spin,
	Table,
	Switch,
	message,
	DatePicker,
	Form,
	Modal,
	Tabs,
	Tooltip
} from 'antd';
import $ from 'jquery/src/ajax';
import moment from 'moment';
import { cityArr,patentTypeList} from '@/dataDic.js';
import {
  beforeUploadFile,
  splitUrl,
  getPatentType,
  getcityArr,
  ShowModal,
  getMessageReminderStart
} from "@/tools.js";
import './customer.less';
import ShowModalDiv from "@/showModal.jsx";
import ImgList from "../../../../common/imgList";
import {ChooseList} from "../../../order/orderNew/chooseList";
import ReminderLog from "./reminderLog";
const Option = AutoComplete.Option;
const { TabPane } = Tabs;
//图片组件
const PicturesWall = React.createClass({
    getInitialState() {
        return {
            previewVisible: false,
            previewImage: '',
            fileList: this.props.pictureUrl,
        }
    },
    getDefaultProps(){
    	return{
    		changeClick:this.modifyChange
    	}
    },
    handleCancel() {
        this.setState({ previewVisible: false })
    },
    handlePreview(file) {
        this.setState({
            previewImage: file.url || file.thumbUrl,
            previewVisible: true,
        });
    },
    handleChange(info) {
        let fileList = info.fileList;
        this.setState({ fileList });
        this.props.fileList(fileList);
    },
    componentWillReceiveProps(nextProps) {
        this.state.fileList = nextProps.pictureUrl;
    },
    render() {
        const { previewVisible, previewImage, fileList } = this.state;
        const uploadButton = (
            
        );
        return (
            
				{beforeUploadFile(infor)}
					}}
					onChange={(infor)=>{
						this.handleChange(infor)
					}}
					fileList={fileList}
				/>
             
        );
    }
});
const PatentPayment = Form.create()(React.createClass({
	departmentList() {
		this.setState({
			loading: true
		});
		$.ajax({
			method: "get",
			dataType: "json",
			crossDomain: false,
			url: globalConfig.context + "/api/admin/organization/selectSuperId",
			data: {},
			success: function(data) {
	            let thedata = data.data;
				let theArr=[];
				if(!thedata) {
					if(data.error && data.error.length) {
						message.warning(data.error[0].message);
					};
				}else{
					thedata.map(function(item,index){
						theArr.push({
							key:index,
							name:item.name,
							id:item.id,
						})
					})
				}
				this.setState({
					departmentArr:theArr,
				})
			}.bind(this),
			}).always(function() {
				this.setState({
					loading: false
				});
			}.bind(this));
	},
	loadData(pageNo){
		this.setState({
			loading: true
		}),
		$.ajax({
			method: "get",
			dataType: "json",
			crossDomain: false,
			url: globalConfig.context + '/api/admin/patentNew/selectPatentNew',
			data: {
				pageNo: pageNo || 1,
				pageSize: this.state.pagination.pageSize,
				status:this.state.statusSearch,
				name:this.state.nameSearch,
				aname:this.state.anameSearch,
				patentNo:this.state.patentNoSearch,
				departmentId:this.state.departmentSearch,
				startDate:this.state.timesArr[0],
				endDate:this.state.timesArr[1],
				type:this.state.typeSearch,
				createStart:this.state.releaseDate[0],
				createEnd:this.state.releaseDate[1],
			},
			success:function (data) {
				ShowModal(this);
				let theArr = [];
				if(!data.data) {
					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({
							id:thisdata.id,
							province:thisdata.province,
							status:thisdata.status,
							patentNo:thisdata.patentNo,
							name:thisdata.name,
							type:thisdata.type,
							applyDates:thisdata.applyDates,
							authorizationDates:thisdata.authorizationDates,
							patentAmount:thisdata.patentAmount,
							applicant:thisdata.applicant,
							contactMobile:thisdata.contactMobile,
							email:thisdata.email,
							certificateUrl:thisdata.certificateUrl,
							aname:thisdata.aname,
							depName:thisdata.depName,
							userName:thisdata.userName,
							uid:thisdata.uid,
							createTimes:thisdata.createTimes
						});
					};
					this.state.pagination.current = data.data.pageNo;
					this.state.pagination.total = data.data.totalCount;
				};
				if(!data.data.list.length) {
					this.state.pagination.current = 0
					this.state.pagination.total = 0
				}
				this.setState({
					pageNo: pageNo,
					dataSource: theArr,
					pagination: this.state.pagination,
				});
			}.bind(this)
		}).always(function() {
			this.setState({
				loading: false
			});
		}.bind(this));
	},
	getInitialState(){
		return {
			loading:false,
			visible:false,
			orgCodeUrl:[],
			fileList:[],
			departmentArr:[],
			timesArr:[],
			pagination: {
				defaultCurrent: 1,
				defaultPageSize: 10,
				showQuickJumper: true,
				pageSize: 10,
				onChange: function(page) {
					this.loadData(page);
				}.bind(this),
				showTotal: function(total) {
					return '共' + total + '条数据';
				}
			},
			releaseDate:[],
			dataSource:[],
			columns:[{
				title: '专利号',
				dataIndex: 'patentNo',
				key: 'patentNo'
			},{
				title: '专利名称',
				dataIndex: 'name',
				key: 'name'
			},{
				title: '专利类型',
				dataIndex: 'type',
				key: 'type',
				render:text=>{
					return getPatentType(text)
				}
			},{
				title: '申请日期',
				dataIndex: 'applyDates',
				key: 'applyDates'
			},{
				title: '授权日期',
				dataIndex: 'authorizationDates',
				key: 'authorizationDates'
			},{
				title: '费用',
				dataIndex: 'patentAmount',
				key: 'patentAmount'
			},{
				title: '客户名称',
				dataIndex: 'userName',
				key: 'userName',
				width:100,
				render: (text,record) => {
					return (
						
							{record.uid ? text : record.applicant}
						
					)
				}
			},{
				title: '录入人',
				dataIndex: 'aname',
				key: 'aname'
			},{
				title: '录入日期',
				dataIndex: 'createTimes',
				key: 'createTimes'
			},{
				title: '录入公司',
				dataIndex: 'depName',
				key: 'depName'
			},{
				title: '联系电话',
				dataIndex: 'contactMobile',
				key: 'contactMobile'
			},{
				title: '电子邮箱',
				dataIndex: 'email',
				key: 'email'
			},{
				title: '状态',
				dataIndex: 'status',
				key: 'status',
				//状态 0 未提醒 1 剩余90天 2剩余30天 3剩余20天 4剩余10天 5剩余3天 6剩余2天 7剩余1天
				render:text=>{
					return (getMessageReminderStart(text,true))
				}
			}, {
				title: '操作',
				dataIndex: 'id',
				key: 'id',
				render: (text) => (
					
				)
			}
			],
			customerServiceList:[]
		}
	},
	componentWillMount(){
		this.loadData()
		this.departmentList()
		let data=localStorage.getItem('newData');
		if(data!='{}'&&data){
			var newData = JSON.parse(data);
			this.tableRowClick(newData);
		};
	},
	new(){
		this.reset();
		this.setState({
			visible:true
		})
	},
	visitCancel(){
		this.state.fileList = [];
		this.setState({
			visible:false
		})
	},
	onSure(){
		let theorgCodeUrl = [];
		if (this.state.orgCodeUrl.length) {
		    let picArr = [];
		    this.state.orgCodeUrl.map(function (item) {
				if ( item.response && item.response.data && item.response.data.length ){
					picArr.push(item.response.data);
				}
		    });
		    theorgCodeUrl = picArr.join(",");
		};
		if (!this.state.patentNo) {
			message.warning('专利号不能为空')
			return
		}
		if (!this.state.patentName) {
			message.warning('专利名称不能为空')
			return
		}
		if (!this.state.appDate) {
			message.warning('申请日期不能为空')
			return
		}
		if(isNaN(parseInt(this.state.patentType))){
		    message.warning('专利类型不能为空');
		    return
		}
		if (!this.state.authDate) {
			message.warning('授权日期不能为空')
			return
		}
		if (!this.state.customerUid) {
			message.warning('客户名称不能为空')
			return
		}
		let mobile = /^1[0-9]{10}$/ , phone = /^([0-9]{3,4}-)?[0-9]{7,8}$/ , phone1 = /^\d{3,4}-\d{3,4}-\d{3,4}$/;
		if(this.state.contactPhone && !(mobile.test(this.state.contactPhone) || phone.test(this.state.contactPhone) || phone1.test(this.state.contactPhone))){
			message.warning('电话格式不正确');
			return
		}
		let emailReg = new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$"); //正则表达式
		if(this.state.email === ''){
			message.warning('电子邮箱不能为空');
			return
		}
		if(!emailReg.test(this.state.email)){
			message.warning('电子邮箱格式不正确');
			return
		}
		this.setState({
			loading:true
		})
		$.ajax({
			method: "POST",
			dataType: "json",
			crossDomain: false,
			url: globalConfig.context +'/api/admin/patentNew/addPatentNew' ,
			data: {
				patentNo:this.state.patentNo,
				name:this.state.patentName,
				type:this.state.patentType,
				applyDates:this.state.appDate,
				authorizationDates:this.state.authDate,
				// applicant:this.state.proposer,
				province:this.state.province,
				contactMobile:this.state.contactPhone,
				email:this.state.email,
				certificateUrl:theorgCodeUrl.length?theorgCodeUrl:'',
				uid:this.state.customerUid,
			}
		}).done(function(data) {
			this.setState({
				loading: false
			});
			if(!data.error.length) {
				message.success('保存成功!');
				this.onCal()
				this.loadData()
			} else {
				message.warning(data.error[0].message);
			}
		}.bind(this));
	},
	tableRowClick(record,index){
		this.state.RowData = record
		this.setState({
			avisible:true,
			patentNo:record.patentNo,
			patentName:record.name,
			province:record.province,
			status:record.status,
			patentType:record.type,
			appDate:record.applyDates,
			authDate:record.authorizationDates,
			proposer:record.applicant,
			contactPhone:record.contactMobile,
			email:record.email,
			certificateUrl:record.certificateUrl,
			orgCodeUrl: record.certificateUrl ? splitUrl(record.certificateUrl, ',', globalConfig.avatarHost + '/upload') : [],
			customerUid:record.uid,
			customerName:record.userName
		})
		localStorage.setItem('newData','{}');
	},
	xiugai(record){
		let theorgCodeUrl = [];
		if (this.state.orgCodeUrl.length) {
		    let picArr = [];
		    this.state.orgCodeUrl.map(function (item) {
				if ( item.response && item.response.data && item.response.data.length ){
					picArr.push(item.response.data);
				}
		    });
		    theorgCodeUrl = picArr.join(",");
		};
		if (!this.state.patentNo) {
			message.warning('专利号不能为空')
			return
		}
		if (!this.state.patentName) {
			message.warning('专利名称不能为空')
			return
		}
		if (!this.state.appDate) {
			message.warning('申请时间不能为空')
			return
		}
		if(isNaN(parseInt(this.state.patentType))){
		    message.warning('专利类型不能为空');
		    return
		}
		if (!this.state.authDate) {
			message.warning('授权日期不能为空')
			return
		}
		if (!this.state.customerUid) {
			message.warning('客户名称不能为空')
			return
		}
		let mobile = /^1[0-9]{10}$/ , phone = /^([0-9]{3,4}-)?[0-9]{7,8}$/ , phone1 = /^\d{3,4}-\d{3,4}-\d{3,4}$/;
		if(this.state.contactPhone && !(mobile.test(this.state.contactPhone) || phone.test(this.state.contactPhone) || phone1.test(this.state.contactPhone))){
			message.warning('电话格式不正确');
			return
		}
		let emailReg = new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$"); //正则表达式
		if(this.state.email === ''){
			message.warning('电子邮箱不能为空');
			return
		}
		if(!emailReg.test(this.state.email)){
			message.warning('电子邮箱格式不正确');
			return
		}
		this.setState({
			loading: true
		})
		$.ajax({
			method: "POST",
			dataType: "json",
			crossDomain: false,
			url: globalConfig.context +'/api/admin/patentNew/updatePatentNew' ,
			data: {
				id:record.id,
				patentNo:this.state.patentNo,
				name:this.state.patentName,
				type:this.state.patentType,
				applyDates:this.state.appDate,
				authorizationDates:this.state.authDate,
				// applicant:this.state.proposer,
				province:this.state.province,
				contactMobile:this.state.contactPhone,
				email:this.state.email,
				status:this.state.status,
				certificateUrl:theorgCodeUrl.length?theorgCodeUrl:'',
				uid:this.state.customerUid,
			},
			success: function (data) {
			}.bind(this),
		}).done(function(data) {
			this.setState({
				loading: false
			});
			if(!data.error.length) {
				message.success('修改成功!');
				this.avisitCancel()
				this.loadData(this.state.pageNo)
			} else {
				message.warning(data.error[0].message);
			}
		}.bind(this));
	},
	baocunxiugai(){
		this.xiugai(this.state.RowData)
	},
	avisitCancel(){
		this.setState({
			avisible:false,
			customerServiceList:[]
		})
	},
	reset(){
		this.setState({
			patentNo:'',
			patentName:'',
			patentType:undefined,
			appDate:undefined,
			authDate:undefined,
			orgCodeUrl:[],
			proposer:'',
			province:undefined,
			contactPhone:'',
			email:'',
			customerUid:undefined,
			customerName:undefined,
			customerServiceList:[],
		})
	},
	searchReset(){
		this.setState({
			statusSearch:undefined,
			nameSearch:undefined,
			anameSearch:undefined,
			patentNoSearch:undefined,
			departmentSearch:undefined,
			typeSearch:undefined,
			timesArr:[],
			releaseDate:[]
		},()=>{
			this.loadData()
		})
	},
	search(){
		this.loadData()
	},
	onCal(){
		this.setState({
			visible:false
		})
	},
	getOrgCodeUrl(e) {
	    this.setState({ orgCodeUrl: e });
	},
	changeList(arr) {
		const newArr = [];
		this.state.columns.forEach(item => {
			arr.forEach(val => {
				if (val === item.title) {
					newArr.push(item);
				}
			});
		});
		this.setState({
			changeList: newArr
		});
	},
	//获取外联专员列表
	getAdminList(value = '') {
		if(value.length < 4){return}
		$.ajax({
			method: "get",
			dataType: "json",
			crossDomain: false,
			url: globalConfig.context + "/api/admin/customer/getUserByName",
			data: {
				name: value,
			},
			success: function (data) {
				let theArr = [];
				if (data.error && data.error.length) {
					message.warning(data.error[0].message);
				}else{
					if(data.data){
						data.data.map(function (item, _) {
							theArr.push({
								value: item.id,
								label: item.name,
							});
						});
					}
				}
				this.setState({
					customerServiceList: theArr,
				});
			}.bind(this),
		}).always(
			function () {
			}.bind(this)
		);
	},
	render(){
		const theData = this.state.RowData || {};
		const FormItem = Form.Item;
		const formItemLayout = {
			labelCol: { span: 8 },
			wrapperCol: { span: 14 },
		};
		const { MonthPicker, RangePicker, WeekPicker } = DatePicker;
		return (
      
        
        
          客户专利提醒
			
				
					
				
				
					
						
					
				
			
          {this.state.mark ? (
            
              请选择申请时间:
               {
                  this.setState({
                    timesArr: f
                  });
                }}
                style={{ marginTop: "0", marginLeft: "10px" }}
              />
				请选择录入日期:
				 {
						this.setState({ releaseDate: dataString });
					}}
				/>
            
          ) : (
            ""
          )}
          
			{this.state.avisible ? 
            
              
                    *专利号
                  
                }
              >
                {!this.props.isOnlyRead ?
                   {
                      this.setState({ patentNo: e.target.value });
                    }}
                    style={{ width: "240px" }}
                  /> : {this.state.patentNo}
                }
              
              
                    *专利名称
                  
                }
              >
                {!this.props.isOnlyRead ?
                   {
                      this.setState({ patentName: e.target.value });
                    }}
                    style={{ width: "240px" }}
                  /> : {this.state.patentName}
                }
              
              
                {!this.props.isOnlyRead ?
                   : {getPatentType(this.state.patentType)}
                }
              
              
					 *申请日期
				    
				}
              >
				  {
					  !this.props.isOnlyRead ?
						   {}}
							  value={this.state.appDate ? moment(this.state.appDate) : null}
							  onChange={(data, dataString) => {
								  this.setState({ appDate: dataString });
							  }}
						  /> : {this.state.appDate ? moment(this.state.appDate).format('YYYY-MM-DD') : ''}
				  }
              
              
					 *授权日期
				    
				}
              >
				  {
					  !this.props.isOnlyRead ?
                 {}}
                  value={
                    this.state.authDate ? moment(this.state.authDate) : null
                  }
                  onChange={(data, dataString) => {
                    this.setState({ authDate: dataString });
                  }}
                /> : {this.state.authDate ? moment(this.state.authDate).format('YYYY-MM-DD') : ''}
 }
              
              
                {theData.patentAmount}
              
              
                
				 {!this.props.isOnlyRead ?  :
				  
				 }
					{!this.props.isOnlyRead ? 图片建议:要清晰。
 : null}
                
               
			  
				  
							*客户名称
						  
					  }
				  >
					  {
						  !this.props.isOnlyRead ?
							   : {this.state.customerName}
					  }
				  
			   
              {this.state.proposer ? 
				  {this.state.proposer}
               : null}
              
				  {
					  !this.props.isOnlyRead ?
                 : {getcityArr(this.state.province)}
 }
              
              
				  {
					  !this.props.isOnlyRead ?
                   {
                      this.setState({ contactPhone: e.target.value });
                    }}
                    style={{ width: "240px" }}
                  /> : {this.state.contactPhone}
                }
              
              
                    *电子邮箱
                  
                }
              >
				  {
					  !this.props.isOnlyRead ?
                   {
                      this.setState({ email: e.target.value });
                    }}
                    style={{ width: "240px" }}
                  /> : {this.state.email}
                }
              
              
                
					{/*状态 0 未提醒 1 剩余90天 2剩余30天 3剩余20天 4剩余10天 5剩余3天 6剩余2天 7剩余1天*/}
					{
						getMessageReminderStart(this.state.status,true)
					}
                
              
             
			  {!this.props.isOnlyRead ? 
              
              
            
 : }
           : 
}
			{this.state.visible ?
            
            
              
              
            
           : 
}
        
 
		  {this.state.reminderLogVisible ? 
{
			  	this.setState({
					reminderLogVisible:false,
					reminderLogId:''
				})
			  }}
		  /> : null}
       
    );
	}
}))
export default PatentPayment;