import React from 'react';
import { Modal, message, Spin, Input, Select, Button, Form, Col, Cascader, Tag, Tooltip, AutoComplete, Icon } from 'antd';
import $ from 'jquery/src/ajax';
import { areaSelect } from '@/NewDicProvinceList';
import { socialAttribute, customerSource } from '@/dataDic.js';
import TextArea from "antd/es/input/TextArea";

const confirm = Modal.confirm;

const AchievementDetailForm = Form.create()(React.createClass({
  getInitialState() {
    return {
      loading: false,
      data: {},
      detailApi: '',
      businessScope: [],
      inputVisible: false,
      cooperationProjects: [],
      selectCooperationProjects: []
    };
  },
  handleSubmit(e) {
    // if (/.*[\u4e00-\u9fa5]+.*$/.test(this.state.content)) {
    // } else {
    //   message.error("请填写正确的姓名，且至少包含一个汉字");
    //   return;
    // }
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      let re = new RegExp("^[\u4e00-\u9fa5]");
      if (!re.test(values.name)) {
        message.warning('公司名称必须以汉字开头！')
        return
      }
      if (!re.test(values.name.charAt(values.name.length - 1))) {
        message.warning('公司名称必须以汉字结尾！')
        return
      }
      if (values.name.length > 64) {
        message.warning('公司名称字数不超过64个！')
        return false;
      };
      let regu = /[`~!#$%^&*'_[\]+=<>?:"{}|~！#￥%……&*=-@-!{}|/《》？：“”【】、；;‘’，,.。、\s+]/g;
      if (regu.test(values.name)) {
        message.warning('公司名称不能存在特殊符号或空格!')
        return false;
      }
      if (!/^[A-Z0-9]{15}$|^[A-Z0-9]{17}$|^[A-Z0-9]{18}$|^[A-Z0-9]{20}$/.test(values.orgCode)) {
        message.warning('请输入正确的统一社会信用代码！')
        return
      }
      if (/.*[\u4e00-\u9fa5]+.*$/.test(values.content)) {
      } else {
        message.error("请填写正确的联系人，且至少包含一个汉字");
        return false;
      };
      if (/.*[\u4e00-\u9fa5]+.*$/.test(values.position)) {
      } else {
        message.error("请填写正确的职位，且至少包含一个汉字");
        return false;
      };
      if (!values.ProvinceCity[1]) {
        message.warning('请选择地区');
        return false;
      };
      if (values.content.length > 32) {
        message.warning('联系人字数不超过32个')
        return false;
      };
      if (values.length > 13) {
        message.warning('电话号码字数不超过13个')
        return false;
      };
      if (this.state.businessScope.length === 0) {
        message.warning('请选择主营产品')
        return false;
      }
      if (this.state.selectCooperationProjects.length === 0) {
        message.warning('请选择意向合作项目')
        return false;
      }
      if (!this.state.level && this.state.level != 0) {
        message.warning('请选择客户类型')
        return false;
      }
      if (!this.state.nature && this.state.nature != 0) {
        message.warning('请选择客户性质')
        return false;
      }
      if (this.state.nature == 0 && !this.state.natureOther) {
        message.warning('其他说明不能为空')
        return false;
      }
      let arr = [];
      for (let i of this.state.selectCooperationProjects) {
        arr.push(i.label)
      }
      if (!err) {
        this.setState({
          loading: true
        });
        $.ajax({
          method: "POST",
          dataType: "json",
          crossDomain: false,
          url: globalConfig.context + '/api/admin/customer/addCustomer',
          data: {
            name: values.name,
            orgCode: values.orgCode,
            contacts: values.content,
            contactMobile: values.telnum,
            societyTag: '0',                       //社会属性默认为 社会企业
            //source:values.customerSource,
            province: (values.ProvinceCity)[0],//省
            city: (values.ProvinceCity)[1],//市
            area: (values.ProvinceCity)[2],//区
            type: '1',
            intendedProject: arr.join(','),
            businessScope: this.state.businessScope.join(','),
            position: values.position,
            level: this.state.level,
            nature: this.state.nature,
            natureOther: this.state.natureOther,
          }
        }).done(function (data) {
          this.setState({
            loading: false
          });
          if (!data.error.length) {
            message.success('保存成功！');
            this.setState({
              verification: false
            })
            this.props.handleOk();
          } else {
            message.warning(data.error[0].message);
          }
        }.bind(this));
      }
    });
  },
  componentWillMount() {
    this.state.name = '';
    this.state.content = '';
    this.state.position = '';
    this.state.telnum = '';
    // this.state.societyTagt='0';
    this.state.customerSource = '0';
    this.state.inputValue = '';
    this.state.businessScope = [];
    this.state.inputVisible = false;

    this.state.cooperationProjects = [];
    this.state.selectCooperationProjects = [];
  },
  componentWillReceiveProps(nextProps) {
    if (!this.props.visible && nextProps.visible) {
      this.state.name = '';
      this.state.content = '';
      this.state.position = '';
      this.state.telnum = '';
      this.state.inputValue = '';
      this.state.businessScope = [];
      this.state.inputVisible = false;
      this.state.cooperationProjects = [];
      this.state.selectCooperationProjects = [];
      // this.state.societyTagt='0';
      this.props.form.resetFields();
    };
  },
  handleClose(removedTag) {
    let businessScope = this.state.businessScope.filter(tag => { return tag !== removedTag });
    this.setState({ businessScope });
  },
  handleCloseCooperation(removedTag) {
    let selectCooperationProjects = this.state.selectCooperationProjects.filter(tag => { return tag.value !== removedTag.value });
    this.setState({ selectCooperationProjects });
  },
  showInput() {
    let str = this.state.businessScope.join('/')
    this.setState({
      inputVisible: true,
      inputValue: str
    });
  },
  handleInputConfirm() {
    let inputValue = this.state.inputValue;
    let arr = inputValue.split('/');
    let lv = true;
    for (let i of arr) {
      if (!i.replace(/\s+/g, '')) {
        message.warning("请填写关键词且不为空");
        return;
      }
      if (i.length > 16) {
        message.warning('单个标签字数不能超过16个字符')
        lv = false;
        return;
      }
    }
    if (lv) {
      arr = Array.from(new Set(arr));
      arr = arr.filter(v => v);
      this.setState({
        businessScope: arr,
        inputVisible: false,
        inputValue: '',
      });
    }
  },
  //加载(自动补全)
  supervisor(value) {
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + '/api/admin/order/getBusinessProjectByName',
      data: {
        businessName: value
      },
      success: function (data) {
        let thedata = data.data;
        if (data.error.length === 0) {
          this.setState({
            cooperationProjects: thedata,
          });
        } else {
          message.warning(data.error[0].message);
        }
      }.bind(this),
    }).always(
      function () {

      }.bind(this)
    );
  },
  onSelect(value) {
    let arr = this.state.cooperationProjects.filter(v => v.id === value);
    let arr1 = this.state.selectCooperationProjects.filter(v => v.value === value);
    if (arr.length > 0) {
      if (arr1.length > 0) {
        message.warning('选项已存在');
      } else {
        this.state.selectCooperationProjects.push({
          label: arr[0].bname,
          value: arr[0].id,
        })
        this.setState({
          selectCooperationProjects: this.state.selectCooperationProjects
        })
      }
    }
  },
  checkUserName() {
    this.setState({
      verification: false
    })
    let yzName = this.props.form.getFieldValue('name')
    if (!yzName) {
      message.warning('请输入公司名称');
      return;
    }
    let re = new RegExp("^[\u4e00-\u9fa5]");
    if (!re.test(yzName)) {
      message.warning('公司名称必须以汉字开头！')
      return
    }
    if (!re.test(yzName.charAt(yzName.length - 1))) {
      message.warning('公司名称必须以汉字结尾！')
      return
    }
    if (yzName.length > 64) {
      message.warning('公司名称字数不超过64个！')
      return;
    };
    let regu = /[`~!#$%^&*'_[\]+=<>?:"{}|~！#￥%……&*=-@-!{}|/《》？：“”【】、；;‘’，,.。、\s+]/g;
    if (regu.test(yzName)) {
      message.warning('公司名称不能存在特殊符号或空格！')
      return false;
    }
    $.ajax({
      method: "get",
      dataType: "json",
      crossDomain: false,
      url: globalConfig.context + '/api/admin/customer/checkUserName',
      data: {
        userName: this.props.form.getFieldValue('name')
      },
      success: function (data) {
        if (data.error.length === 0) {
          if (!data.data) {
            this.setState({
              verification: true
            })
          } else {
            Modal.info({
              title: '提醒',
              content: (
                <div>
                  <p>企业客户已存在！请在“客户管理-企业客户-企业客户查询”输入企业全称查询所属人信息</p>
                </div>
              ),
            });
            this.setState({
              verification: false
            })
          }
        } else {
          message.warning(data.error[0].message);
        }
      }.bind(this),
    }).always(
      function () {

      }.bind(this)
    );
  },

  render() {
    const theData = this.state.data || {};
    const { getFieldDecorator } = this.props.form;
    const FormItem = Form.Item
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
    };

    return (
      <div>
        <Form layout="horizontal" onSubmit={this.handleSubmit} id="demand-form">
          <Spin spinning={this.state.loading}>
            <div>
              <Col style={{ color: 'red', marginBottom: '10px' }} span={12} offset={6}>注意:请录入真实有效的客户信息</Col>
              <div className="clearfix">
                <FormItem className="mid-item"
                  {...formItemLayout}
                  label="公司名称" >
                  {getFieldDecorator('name', {
                    rules: [{ required: true, message: '此项为必填项!' }],
                    initialValue: this.state.name
                  })(
                    <span style={{ display: 'flex', alignItems: 'center', position: 'relative' }}>
                      <Input placeholder="公司名称" />
                      {this.state.verification && <Icon type="check-circle" style={{
                        fontSize: 16,
                        color: '#30e031',
                        position: 'absolute',
                        right: '80px',
                      }} />}
                      <Button onClick={this.checkUserName} type="primary" style={{ marginLeft: '10px' }}>验证</Button>
                    </span>
                  )}
                </FormItem>
              </div>
              <div className="clearfix">
                <FormItem
                  {...formItemLayout}
                  label="统一社会信用代码"
                >
                  {getFieldDecorator('orgCode', {
                    rules: [{ required: true, message: '此项为必填项!' }],
                    initialValue: this.state.orgCode
                  })(
                    <Input placeholder="统一社会信用代码" />
                  )}
                </FormItem>
              </div>
              <Col style={{ color: 'red', marginBottom: '10px' }} span={12} offset={6}>如,科德集团则填写91430105670766451M</Col>
              <div className="clearfix">
                <FormItem
                  {...formItemLayout}
                  label="省-市-区"
                >
                  {getFieldDecorator('ProvinceCity', {
                    rules: [{ required: true, message: '此项为必填项!' }],
                    initialValue: this.state.ProvinceCity
                  })(
                    <Cascader options={areaSelect()} placeholder="选择城市" />
                  )}
                </FormItem>
              </div>
              <div className="clearfix">
                <FormItem className="mid-item"
                  {...formItemLayout}
                  label="联系人" >
                  {getFieldDecorator('content', {
                    rules: [{ required: true, message: '此项为必填项!' }],
                    initialValue: this.state.content
                  })(
                    <Input placeholder="联系人姓名" />
                  )}
                </FormItem>
              </div>
              <div className="clearfix">
                <FormItem className="mid-item"
                  {...formItemLayout}
                  label="职位" >
                  {getFieldDecorator('position', {
                    rules: [{ required: true, message: '此项为必填项!' }],
                    initialValue: this.state.position
                  })(
                    <Input placeholder="联系人职位" />
                  )}
                </FormItem>
              </div>
              <div className="clearfix">
                <FormItem className="mid-item"
                  {...formItemLayout}
                  label="联系电话" >
                  {getFieldDecorator('telnum', {
                    rules: [{ required: true, message: '此项为必填项!' }],
                    initialValue: this.state.telnum
                  })(
                    <Input placeholder="请填写手机号,仅填座机号时,请后续补充手机号" />
                  )}
                </FormItem>
              </div>
              <div className="clearfix">
                <FormItem className="mid-item"
                  {...formItemLayout}
                  required
                  label="主营产品" >
                  <div>
                    {this.state.businessScope.map((tag, index) => {
                      const isLongTag = tag.length > 20;
                      const tagElem = (
                        <Tag closable key={tag} afterClose={() => this.handleClose(tag)}>
                          {isLongTag ? `${tag.slice(0, 20)}...` : tag}
                        </Tag>
                      );
                      return isLongTag ? <Tooltip title={tag} key={tag}>{tagElem}</Tooltip> : tagElem;
                    })}
                    {
                      !this.state.inputVisible &&
                      <Button
                        size="small"
                        type="primary"
                        onClick={this.showInput}>
                        + 新增主营产品
                      </Button>
                    }
                  </div>
                  {this.state.inputVisible && (<div>
                    <TextArea
                      style={{ width: '300px', height: '100px' }}
                      value={this.state.inputValue}
                      onChange={(e) => {
                        this.setState({
                          inputValue: e.target.value
                        })
                      }} />
                    <div style={{ color: '#f00' }}>提示：请用 / 符号隔开关键字</div>
                    <div>
                      <Button
                        size="small"
                        type="primary"
                        onClick={this.handleInputConfirm}>
                        确定
                      </Button>
                      <Button
                        size="small"
                        style={{ marginLeft: '5px' }}
                        onClick={() => {
                          this.setState({
                            inputVisible: false,
                            inputValue: ''
                          })
                        }}>
                        取消
                      </Button>
                    </div>
                  </div>)}
                </FormItem>
              </div>
              <div className="clearfix">
                <FormItem
                  className="mid-item"
                  {...formItemLayout}
                  required
                  label="意向合作项目" >
                  <div>
                    <div style={{ paddingBottom: this.state.selectCooperationProjects.length === 0 ? 0 : '10px' }}>
                      {this.state.selectCooperationProjects.map((tag, index) => {
                        const isLongTag = tag.label.length > 20;
                        const tagElem = (
                          <Tag closable key={tag.label} afterClose={() => this.handleCloseCooperation(tag)}>
                            {isLongTag ? `${tag.label.slice(0, 20)}...` : tag.label}
                          </Tag>
                        );
                        return isLongTag ? <Tooltip title={tag.label} key={tag.label}>{tagElem}</Tooltip> : tagElem;
                      })}
                    </div>
                    <div>
                      <AutoComplete
                        style={{ width: 200 }}
                        onSearch={this.supervisor}
                        onSelect={this.onSelect}
                        placeholder="请输入关键字"
                      >
                        {
                          this.state.cooperationProjects.map(function (item) {
                            return <Select.Option key={item.id} value={item.id}>{item.bname}</Select.Option>
                          })
                        }
                      </AutoComplete>
                    </div>
                  </div>
                </FormItem>
              </div>
              <div className="clearfix">
                <FormItem
                  className="mid-item"
                  {...formItemLayout}
                  required
                  label="客户类型" >
                  <Select
                    placeholder="请选择客户类型"
                    value={this.state.level}
                    onChange={(e) => {
                      this.setState({ level: e });
                    }}
                  >
                    <Option value={0}>一般客户（一年以上预签）</Option>
                    <Option value={1}>意向客户（半年内预签）</Option>
                    <Option value={2}>重点客户（一个月内预签）</Option>
                  </Select>
                </FormItem>
              </div>
              <div className="clearfix">
                <FormItem
                  className="mid-item"
                  {...formItemLayout}
                  required
                  label="客户性质" >
                  <Select
                    placeholder="请选择客户性质"
                    value={this.state.nature}
                    onChange={(e) => {
                      this.setState({ nature: e });
                    }}
                  >
                    <Option value={1}>政府机构</Option>
                    <Option value={2}>科研院所</Option>
                    <Option value={3}>高等院校</Option>
                    <Option value={4}>国有企业</Option>
                    <Option value={5}>民营企业</Option>
                    <Option value={6}>社会团体</Option>
                    <Option value={0}>其他（请注明）</Option>
                  </Select>
                </FormItem>
              </div>
              {
                this.state.nature == 0 &&
                <div className="clearfix">
                  <FormItem
                    className="mid-item"
                    {...formItemLayout}
                    required
                    label="其他说明" >
                    <Input
                      placeholder="其他说明"
                      value={this.state.natureOther}
                      onChange={e => {
                        this.setState({
                          natureOther: e.target.value
                        })
                      }}
                    />
                  </FormItem>
                </div>
              }
              {/*<div className="clearfix">*/}
              {/*	<FormItem className="mid-item"*/}
              {/*      {...formItemLayout}*/}
              {/*       label="社会属性"*/}
              {/*     >*/}
              {/*     {getFieldDecorator('societyTagt', {*/}
              {/*                rules: [{ required: true, message: '此项为必填项!' }],*/}
              {/*                initialValue: this.state.societyTagt*/}
              {/*            })(*/}
              {/*		  <Select placeholder="客户社会属性">*/}
              {/*            {*/}
              {/*                socialAttribute.map(function (item) {*/}
              {/*                    return <Select.Option key={item.value} >{item.key}</Select.Option>*/}
              {/*                })*/}
              {/*            }*/}
              {/*          </Select>*/}
              {/*        )}*/}
              {/*	 </FormItem>*/}
              {/*</div>*/}
            </div>
            <FormItem wrapperCol={{ span: 12, offset: 6 }}>
              <Button type="primary" htmlType="submit" style={{ marginRight: '50px' }}>保存</Button>
              <Button type="ghost" onClick={this.props.closeDesc}>取消</Button>
            </FormItem>
          </Spin>
        </Form >
      </div>
    )
  }
}));

const AddPerson = Form.create()(React.createClass({
  getInitialState() {
    return {
      loading: false,
      data: {},
      detailApi: ''
    };
  },

  handleSubmit(e) {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (values.companyNamet.length > 64) {
        message.warning('联系人字数不超过64个')
        return false;
      };
      if (!values.ProvinceCity[1]) {
        message.warning('请选择地区');
        return false;
      };
      if (values.telnums.length > 13) {
        message.warning('电话号码字数不超过13个')
        return false;
      };
      if (!err) {
        this.setState({
          loading: true
        });
        $.ajax({
          method: "POST",
          dataType: "json",
          crossDomain: false,
          url: globalConfig.context + '/api/admin/customer/addCustomer',
          data: {
            contacts: values.companyNamet,
            societyTag: values.societyTagt,
            name: values.companyNamet,
            contactMobile: values.telnums,
            source: values.customerSource,
            province: (values.ProvinceCity)[0],//省
            city: (values.ProvinceCity)[1],//市
            area: (values.ProvinceCity)[2],//区
            type: '0'
          }
        }).done(function (data) {
          this.setState({
            loading: false
          });
          if (!data.error.length) {
            message.success('保存成功！');
            this.props.handleOk();
          } else {
            message.warning(data.error[0].message);
          }
        }.bind(this));
      }
    });
  },
  componentWillMount() {
    this.state.companyNamet = '';
    this.state.telnum = '';
    this.state.societyTagt = '0';
    this.state.customerSource = '0';
  },
  componentWillReceiveProps(nextProps) {
    if (!this.props.visible && nextProps.visible) {
      this.state.companyNamet = '';
      this.state.telnum = '';
      this.state.societyTagt = '0';
      this.state.customerSource = '0';
      this.props.form.resetFields();
    };
  },

  render() {
    const theData = this.state.data || {};
    const { getFieldDecorator } = this.props.form;
    const FormItem = Form.Item
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
    };

    return (
      <div>
        <Form layout="horizontal" onSubmit={this.handleSubmit} id="demand-form">
          <Spin spinning={this.state.loading}>
            <Col style={{ color: 'red', marginBottom: '10px' }} span={12} offset={6}>注意:请录入真实有效的客户信息</Col>
            <div className="clearfix">
              <FormItem className="mid-item"
                {...formItemLayout}
                label="客户姓名" >
                {getFieldDecorator('companyNamet', {
                  rules: [{ required: true, message: '此项为必填项!' }],
                  initialValue: this.state.companyNamet
                })(
                  <Input placeholder="客户姓名" />
                )}
              </FormItem>
            </div>
            <div className="clearfix">
              <FormItem
                {...formItemLayout}
                label="省-市-区"
              >
                {getFieldDecorator('ProvinceCity', {
                  rules: [{ required: true, message: '此项为必填项!' }],
                  initialValue: this.state.ProvinceCity
                })(
                  <Cascader options={areaSelect()} placeholder="选择城市" />
                )}
              </FormItem>
            </div>
            <div className="clearfix">
              <FormItem className="mid-item"
                {...formItemLayout}
                label="联系电话" >
                {getFieldDecorator('telnums', {
                  rules: [{ required: true, message: '此项为必填项!' }],
                  initialValue: this.state.telnums
                })(
                  <Input placeholder="联系电话" />
                )}
              </FormItem>
            </div>
            <div className="clearfix">
              <FormItem className="mid-item"
                {...formItemLayout}
                label="社会属性"
              >
                {getFieldDecorator('societyTagt', {
                  rules: [{ required: true, message: '此项为必填项!' }],
                  initialValue: this.state.societyTagt
                })(
                  <Select placeholder="客户社会属性">
                    {
                      socialAttribute.map(function (item) {
                        return <Select.Option key={item.value} >{item.key}</Select.Option>
                      })
                    }
                  </Select>
                )}
              </FormItem>
            </div>
            <div className="clearfix">
              <FormItem className="mid-item"
                {...formItemLayout}
                label="客户来源"
              >
                {getFieldDecorator('customerSource', {
                  rules: [{ required: true, message: '此项为必填项!' }],
                  initialValue: this.state.customerSource
                })(
                  <Select placeholder="客户来源">
                    {
                      customerSource.map(function (item) {
                        return <Select.Option key={item.value} >{item.key}</Select.Option>
                      })
                    }
                  </Select>
                )}
              </FormItem>
            </div>
            <FormItem wrapperCol={{ span: 12, offset: 6 }}>
              <Button style={{ marginRight: '50px' }} type="primary" htmlType="submit">保存</Button>
              <Button type="ghost" onClick={this.props.closeDesc}>取消</Button>
            </FormItem>
          </Spin>
        </Form >
      </div>
    )
  }
}));

const AddIntention = React.createClass({
  getInitialState() {
    return {
      visible: false,
      tabsKey: 1,
      loading: false,
      dataSource: [],
    };
  },
  handleCancel(e) {
    this.setState({
      visible: false,
    });
    this.props.closeDesc(false);
  },
  handleOk(e) {
    this.setState({
      visible: false,
    });
    this.props.closeDesc(false, true);
  },

  componentWillReceiveProps(nextProps) {
    if (!this.state.visible && nextProps.showDesc) {
      this.state.tabsKey = "1";
    };
    this.state.visible = nextProps.showDesc;

  },
  render() {

    return (
      <div className="patent-desc">
        {
          this.state.visible &&
          <Modal maskClosable={false} visible={this.state.visible}
            onOk={this.checkPatentProcess} onCancel={this.handleCancel}
            width='600px'
            title='新建客户'
            footer=''
            className="admin-desc-content">
            <Spin spinning={this.state.loading}>
              {this.props.api.indexOf('Personal') < 0 ? <AchievementDetailForm
                data={this.props.data}
                newmodal={this.props.newmodal}
                closeDesc={this.handleCancel}
                visible={this.state.visible}
                handleOk={this.handleOk} /> : <AddPerson
                data={this.props.data}
                newmodal={this.props.newmodal}
                closeDesc={this.handleCancel}
                visible={this.state.visible}
                handleOk={this.handleOk}
              />}
            </Spin>
          </Modal>
        }
      </div>
    );
  },
});

export default Form.create({})(AddIntention);
