/*
 * Creator:     ML
 * CreatDate:   2019-08-20
 * descripts：  个人信息  修改联系方式
*/
import React from 'react';
import { Form, Row, Col, Input, Select, DatePicker, Button, Modal, Table, message, Divider ,Popconfirm,Icon,Tooltip} from 'antd';
import { $http } from '../../../containers/config/https';
import '../css/index.less';
import { Util } from 'tools/index';
const FormItem = Form.Item;
const confirm = Modal.confirm;
const Option = Select.Option;
const userData = sessionStorage.userData ? JSON.parse(sessionStorage.userData) : {}
const PerfectingContactWay = Form.create()(
  class PerfectingContactWay extends React.Component {
    constructor(props) {
      super(props)
      this.state = {
        baseType:[],//联系类型
        typeData:[],//联系方式列表
        isMod:-1,//是否编辑 修改
        dec:"",//联系方式描述
        editId:"",//联系方式修改id
        editIds:"",//联系方式Id
        allDis:false,//编辑事方式不可选
        disDec:[],//已使用的联系方式
        codeHelp: '',
        codeStatus: '',
        visibleCode:false,
        numberVisible:false,//联系号码提示显隐
        numberMessage:"",//联系号码文字提示
      }
    }
    componentDidMount() {
        // this.getType()
        // this.getTypeTable()
        this.props.onPerfectingContactWay(this)
    }
    getTypeTable=()=>{
        let data = {}
        data = {
            params: [{
                userID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID:"",
                power:"personalInfo"
                }],
     };
     $http.post('urlS', this, {
         code: "01040089",
         data: data,
         success: function (res) {
             if (+res.errorCode === 0 && res.result) {
                res.result.contactAry.map((item,i)=>{
                    item.key = i
                })
                this.setState({
                    typeData:res.result.contactAry
                })
             }
         }
     });
    }
    getType=()=>{
        let data = {}
        data = {
            params: [{
                userID:JSON.parse(sessionStorage.userData).userID,
                }],
     };
     $http.post('urlS', this, {
         code: "01040034",
         data: data,
         success: function (res) {
             if (+res.errorCode === 0 && res.result) {
                res.result.map((item,i)=>{
                    item.key = i
                })
                this.setState({
                    baseType:res.result
                })
             }
         }
     });
    }
    //获取不可点击的联系方式 已绑定
    getDisSelect=()=>{
        this.setState({
            disDec:[]
        },()=>{
            //最多可绑定两次
            let res = {};
            this.state.typeData.forEach(({ userContactTypeID } = item) => res[userContactTypeID] ? res[userContactTypeID].len++ : res[userContactTypeID] = { key: userContactTypeID, len: 1 });
            res = Object.values(res);
            res.map((item,i)=>{
                if(item.len>=2&&item.userContactTypeDesc=="手机"){
                    this.state.disDec.push(item.key)
                        this.setState({
                            disDec : this.state.disDec,
                    })
                }
            })
           //只能绑定一次
            // this.state.baseType.map((item,index)=>{
            //     this.state.typeData.map((bindItem,i)=>{
            //         if(item.descripts==bindItem.userContactTypeDesc){
            //             this.state.disDec.push(item.id)
            //             this.setState({
            //                 disDec : this.state.disDec,
            //             })
            //         }
            //     })
            // })
            })
        
    }
    handCanel=()=>{
        this.setState({
            isMod:-1,
            allDis:false,
            visibleCode:false,
            numberVisible:false
        })
        this.props.form.resetFields();
    }
    handSave=()=>{
        this.props.form.validateFields((err, values) => {
            if(!err){
                let data = {}
                if(this.state.isMod==1){
                    data = {
                        params: [{
                            userID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID:"",
                            updateUserID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID:"",
                            power:"contact",
                            contactValue:this.props.form.getFieldValue('contactNumber')||"",
                            userContactID:this.state.editId,
                            contactTypeId:this.props.form.getFieldValue('contactType')||"",
                            contactTypeDesc:this.state.dec,
                            }],
                 };
                }else{
                    data = {
                        params: [{
                            userID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID:"",
                            updateUserID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID:"",
                            power:"contact",
                            contactTypeId:this.props.form.getFieldValue('contactType')||"",
                            contactValue:this.props.form.getFieldValue('contactNumber')||"",
                            contactTypeDesc:this.state.dec,
                            }],
                 };
                }
               
             $http.post('urlS', this, {
                 code: "01040090",
                 data: data,
                 success: function (res) {
                     if (+res.errorCode === 0 ) {
                        if(this.state.isMod==1){
                            message.success(
                                this.props.localeProvider&&this.props.localeProvider.PersonalInformationSuccessfullyModified?this.setMessage('PersonalInformationSuccessfullyModified', 'descripts'):"修改成功"
                            );
                        }else{
                            message.success(
                                this.props.localeProvider&&this.props.localeProvider.PersonalInformationAddedSuccessfully?this.setMessage('PersonalInformationAddedSuccessfully', 'descripts'):"添加成功"
                            );
                        }
                        this.getTypeTable()
                        this.getDisSelect()
                        this.handCanel()
                     }
                 }
             });
        
            }
        })
    }
    editDocMes=(record,num)=>{
        if(num==1){
         this.setState({
            isMod:1,
            editId:record.userContactID,
            dec:record.userContactTypeDesc,
            allDis:true
        })
        this.props.form.setFieldsValue({ contactType:record.userContactTypeID,contactNumber:record.userContactValue})  
        if(record.userContactTypeDesc=="手机"){
            this.setState({
                visibleCode:true
            })
        }else{
            this.setState({
                visibleCode:false
            })
        }
        }else{
            let data = {}
            let arr = []
            arr.push(record.userContactID)
            data = {
                params: [{
                    userID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID:'',
                    updateUserID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID:'',
                    power:"deleteContact",
                    userContactRemoveAry:arr
                    }],
         };
         $http.post('urlS', this, {
            code: "01040090",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0 ) {
                    message.success(
                        this.props.localeProvider&&this.props.localeProvider.PersonalInformationSuccessfullyDeleted?this.setMessage('PersonalInformationSuccessfullyDeleted', 'descripts'):"删除成功"
                    );
                   this.getTypeTable()
                   this.getDisSelect()
                   this.handCanel()
                }
            }
        });
        }
    }
    //选择联系方式
    handleSelect=(id)=>{
        this.setState({
            editIds:id,
            numberVisible:false
        })
        this.state.baseType.map((item,index)=>{
            if(id==item.id){
                this.setState({
                    dec:item.descripts
                })
            }
        })
    }
    // 验证码
    changeEvent = (e) => {
        if (e.target.value.length > 0) {
            this.setState({
                codeHelp: '',
                codeStatus: ''
            });
        } else {
            this.setState({
                codeHelp: '请输入验证码',
                codeStatus: 'error'
            });
        }
    }
    //联系号码提示框
    numberTip = () => {
        this.props.form.validateFields(['contactNumber'], (errors, values) => {
            if (errors == null) {
                return
            }
            if (!errors) {
                this.setState({
                    numberVisible: false
                })
            } else {
                this.setState({
                    numberVisible: true,
                    numberMessage: errors.contactNumber.errors[0].message,
                })
                setTimeout(()=>{
                    this.setState({
                        numberVisible: false
                    })
                },1500)
            }
        });
    }
    //国际化
    setMessage(name, message) {
        return this.props.localeProvider ? this.props.localeProvider[name][message] : ''
    }
    render() {
      const { isMod,allDis,numberMessage,numberVisible,editId,editIds } = this.state
      const {
        form: { validateFields },
    } = this.props;
    let localeData = this.props.localeProvider
    const { getFieldDecorator } = this.props.form;
    const mesIcon = <Icon type="exclamation-circle" />
    //联系类型
    let contactOp = []
    // disabled={this.state.disDec.includes(item.id)}s
    this.state.baseType&& this.state.baseType.map(item => {
        contactOp.push(<Option key={item.id} value={String(item.id)}>{item.descripts}</Option>)
    })
    const columns = [
        {
            width: 60,
            align: "center",
            title: '联系方式',
            dataIndex: 'userContactTypeDesc',
            key: 'fundus',
            editable: true,
        },
        {
            width: 100,
            align: "center",
            title: '联系号码',
            dataIndex: 'userContactValue',
            key: 'breast',
            editable: true,
        },
        {
            title: '操作',
            dataIndex: 'operation',
            key: 'action',
            align: "center",
            width: 80,
            render: (text, record, index) => {
                if(record.userContactTypeDesc=="手机"){
                    return (
                        <span>
                            <span  className='span' style={{cursor:"pointer"}} onClick={()=>this.editDocMes(record,"1")}>{localeData&&localeData.PersonalInformationedit?this.setMessage('PersonalInformationedit', 'descripts'):"编辑"}</span>
                            {/* 分割线 */}
                        </span>
                )
                }else{
                    return (
                        <span>
                <span  className='span' style={{cursor:"pointer"}} onClick={()=>this.editDocMes(record,"1")}>{localeData&&localeData.PersonalInformationedit?this.setMessage('PersonalInformationedit', 'descripts'):"编辑"}</span>
                            {/* 分割线 */}
                            <Divider type="vertical" />
                            <Popconfirm title={localeData&&localeData.PersonalInformationSureYouWantTo?this.setMessage('PersonalInformationSureYouWantTo', 'descripts'):"删除不可恢复，你确定要删除吗?"} onConfirm={(e) => this.editDocMes(record,"2")} >
                               <span className="span" style={{ color: 'rgba(240,65,52,1)' }}>{localeData&&localeData.PersonalInformationdelete?this.setMessage('PersonalInformationdelete', 'descripts'):"删除"}</span>
                            </Popconfirm>
                        </span>
                )
                }
            }
        }
    ];
      return (
        <div>
         <Form>
            <Row gutter={8}>
                <Col span={12} >
                    <FormItem label={localeData&&localeData.PersonalInformationContactType?this.setMessage('PersonalInformationContactType', 'descripts'):"联系类型："} wrapperCol={{ span: 17 }} labelCol={{ span: 7 }}>
                        {getFieldDecorator('contactType', {
                            initialValue: undefined,
                            rules: [{ required: localeData&&localeData.PersonalInformationContactType&&this.setMessage('PersonalInformationContactType', 'required')=="Y"?true:false,message: localeData&&localeData.PersonalInformationContactType?this.setMessage('PersonalInformationContactType', 'message'):"请选择联系类型：" }],
                        })(
                            <Select onDropdownVisibleChange={this.getDisSelect} disabled={allDis} placeHolder={localeData&&localeData.PersonalInformationContactType?this.setMessage('PersonalInformationContactType', 'message'):"请选择联系类型：" } onSelect={this.handleSelect}>
                                {contactOp}
                            </Select>
                        )}
                    </FormItem>
                </Col >
            </Row>
            <Row gutter={8}>
                <Col span={12} className="numberDom">
                <Tooltip getPopupContainer={() => document.querySelector('.numberDom')} overlayStyle={{ zIndex: 999, }} overlayClassName="toolDom numberPosition" title={<div className="titleIcon">{mesIcon}<span >{numberMessage}</span></div>} visible={numberVisible}>
                    <FormItem label={localeData&&localeData.PersonalInformationContactNumber?this.setMessage('PersonalInformationContactNumber', 'descripts'):"联系号码：" } wrapperCol={{ span: 17 }} labelCol={{ span: 7 }}>
                        {getFieldDecorator('contactNumber', {
                            validateTrigger:["onPressEnter","onBlur"],
                            initialValue: undefined,
                            rules: [
                            { required: localeData&&localeData.PersonalInformationContactNumber&&this.setMessage('PersonalInformationContactNumber', 'required')=="Y"?true:false, message: localeData&&localeData.PersonalInformationContactNumber?this.setMessage('PersonalInformationContactNumber', 'message'):"请输入联系号码" },
                            { validator: (rule, value, callback)=>Util.validFContact(rule, value, callback,this.state.editIds)},
                            ],
                            getValueFromEvent: (event) => {
                                if(editIds=="1"||editIds=="4"){
                                    return event.target.value.replace(/\D/g, '')
                                }else if(editIds=="2"){
                                    return event.target.value.replace(/[^0-9-]/g, '')
                                }else{
                                    return event.target.value
                                }
                            },
                        })(
                            <Input 
                            maxLength={editIds=="1"||editIds=="4"?11:(editIds=="3"?20:40)}
                            placeHolder={localeData&&localeData.PersonalInformationContactNumber?this.setMessage('PersonalInformationContactNumber', 'message'):"请输入联系号码" }
                            onPressEnter={this.numberTip}
                            onBlur={this.numberTip}
                            onChange={()=>this.setState({numberVisible:false})}
                            onClick={()=>this.setState({numberVisible:false})}
                            />
                        )}
                    </FormItem>
                </Tooltip>
                </Col >
            </Row>
            <Row gutter={8} style={{ display:(this.state.visibleCode?"block":"none") }}>
                <Col span={12}>
                    <FormItem
                        // help={this.state.codeHelp}
                        // validateStatus={this.state.codeStatus}
                        label={localeData&&localeData.PersonalInformationVerificationCode?this.setMessage('PersonalInformationVerificationCode', 'descripts'):"验证码"  } wrapperCol={{ span: 17 }} labelCol={{ span: 7 }}
                    >
                         {getFieldDecorator('code', {
                            initialValue: undefined,
                            rules: [{ required: this.state.visibleCode?true:false, message: localeData&&localeData.PersonalInformationVerificationCode?this.setMessage('PersonalInformationVerificationCode', 'message'):"请输入验证码"  }],
                        })(
                            // onChange={(e) => this.changeEvent(e)}SendTheVerificationCod DigitVerificationCode
                            <Input  prefix={<Icon type="safety-certificate" />} placeholder={localeData&&localeData.PersonalInformationDigitVerificationCode?this.setMessage('PersonalInformationDigitVerificationCode', 'message'):"4位验证码"} maxLength={4} id="verificationCode" addonAfter={<div className="codePhone">{localeData&&localeData.PersonalInformationSendTheVerificationCode?this.setMessage('PersonalInformationSendTheVerificationCode', 'descripts'):"发送验证码"}</div>} />
                        )}
                    </FormItem>
                </Col>
            </Row>
            <Row gutter={8}>
                <Col span={12} style={{textAlign:"right"}}>	
                    <Button style={{margin:"0 8px"}}  key="submits" type="primary" onClick={this.handCanel} >
                        {isMod==-1&&localeData&&localeData.PersonalInformationEmptyPer?this.setMessage('PersonalInformationEmptyPer', 'descripts'):
                        (localeData&&localeData.PersonalInformationCancel?this.setMessage('PersonalInformationCancel', 'descripts'):"取消")
                        }
                    </Button>
                    <Button  key="submit" type="primary" onClick={this.handSave} >
                        {isMod==-1&&localeData&&localeData.PersonalInformationsave?this.setMessage('PersonalInformationsave', 'descripts'):
                        (localeData&&localeData.PersonalInformationModifyPer?this.setMessage('PersonalInformationModifyPer', 'descripts'):"修改")
                        }
                    </Button>
                </Col >
            </Row>
        </Form>
        <p style={{fontWeight:"600",fontSize:"14px",marginTop:"12px"}}>{localeData&&localeData.PersonalInformationCurrentUserContactList?this.setMessage('PersonalInformationCurrentUserContactList', 'message'):"当前用户联系方式列表" }</p>
        <Table
            // showHeader={false}
            columns={columns}
            pagination={false}
            // rowClassName={this.setRowClassNames}
            // onRow={this.onClickRightRow}
            dataSource={this.state.typeData && this.state.typeData.length > 0 ? this.state.typeData : []}
            rowKey={(row) => {
                return row.id
            }}
            showHeader={false}
            className="clearBackground"
            bordered
        />
        </div>
      )
    }
  })
export default PerfectingContactWay    