import React from 'react';
import PropTypes from 'prop-types';
import { $http } from '../../containers/config/https';
import { Util} from '../../tools';
import { Modal, Form, message,DatePicker,Select} from 'antd';
import Moment from 'moment';
const Option = Select.Option;
const FormItem = Form.Item;


const PersonRelatedInvTypeModal=Form.create()(

class  extends React.Component{
    
  //初始化数据
  state = { 
      visible: false ,
      //发票下拉框数组
      invList:[],
      //用户下拉框数组
      userList:[],
      hospID:'',
    };

  

  //加载生命周期函数
  componentDidMount() {
      this.props.onRef(this);
      let sessionInfo = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        this.setState({hospID:sessionInfo.hospID}, () => {
            this.handleInvTypeQuery();
            this.handleHospQuery ();
            this.handleUserQuery();
        });
      }

  componentWillUnmount() {
        this.setState = (state, callback) => {
            return
           }
        }


  //医院下拉框
  handleHospQuery = () => {
    let data = {}
    let sessionInfo = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
    data = {
        params: [{
        hospitalId:"",
        logonGroupID:sessionInfo.groupID,
        logonHospID:sessionInfo.hospID,
        hospRequired:"1",
        }]
    }
    $http.post('urlS', this, {
        code: '01040001',
        data: data,
        success: function (res) {
            if (+res.errorCode === 0 && res.depDoctor) {
                let tempList =[];
                for (var i = 0; i < res.depDoctor.length; i++) {
                    tempList.push(<Option key={res.depDoctor[i].id}>{res.depDoctor[i].descripts}</Option>)
                }
                this.setState({
                hospList: tempList
                })
            } 
        }
    })
}   

  // 发票类型下拉框
  handleInvTypeQuery = () => {
      let data = {}
      data = {
          params: [{
            code: "",
            descripts: ""
          }]
      }
      $http.post('urlS', this, {
          code: '5001',
          data: data,
          success: function (res) {
              if (+res.errorCode === 0 && res.invType) {
                  let tempList = this.state.invList
                  for (var i = 0; i < res.invType.length; i++) {
                      tempList.push(<Option key={res.invType[i].ID}>{res.invType[i].Descripts}</Option>)
                  }
                  this.setState({
                    invList: tempList
                  })
              } 
              /*else {
                  setTimeout(() => {
                      this.setState({ invList: [] })
                  }, 1000)
              }*/
          }
      })
  }   
  /*/ 人员下拉框
  handleUserQuery = () => {
        let data = {}
        data = {
            params: [{
                groupId: '',
            }]
        }
        $http.post('urlS', this, {
            code: '05100027',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0 && res.user) {
                    let tempList = this.state.userList
                    for (var i = 0; i < res.user.length; i++) {
                        tempList.push(<Option key={res.user[i].id} alias={res.user[i].descriptsSPCode}>{res.user[i].descripts}</Option>)
                    }
                    this.setState({
                        userList: tempList
                    })
                } 
              
            }
        })
  }*/


      // 人员下拉框
      handleUserQuery = () => {
        let {hospID} = this.state;
        let data = {}
        data = {
            params: [{
                hospID: hospID,
                locTypeCode:"C",
            }]
        }
        $http.post('urlS', this, {
            code: '05210023',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0 && res.user) {
                    let tempList =[]
                    for (var i = 0; i < res.user.length; i++) {
                        tempList.push(<Option key={res.user[i].id} alias={res.user[i].descriptsSPCode}>{res.user[i].descripts}</Option>)
                    }
                    this.setState({
                        userList: tempList,
                        userData:res.user
                    }            
                    )
                } 
            }
        })
        }
  ///输入框值变化时需要绑定
  onChangeHospID= (value) => {
    this.setState({hospID:value,userList:[]}, () => {
        this.handleUserQuery();
    });
  }


  // 重置表单
  resetFields() {
        this.props.form.resetFields(); //清空所有
      }
  // 供父组件调用
  showModal = () => {
    this.setState({
          visible: true,
      });
    }
  // 关闭弹框
  handleCancel = () => {
    this.setState({
        visible: false,
      });
    }

    
 //增加或更新数据
  handelFunction(code, msg) {
          const { form: { validateFields } } = this.props;
          validateFields((errors, values) => {
            // 验证成功
            if (errors === null) {
                let data = {
                    params: []
                }
                let obj = values;
                if(obj.startDate){obj.startDate=obj.startDate.format('YYYY-MM-DD');}
                if(obj.stopDate){ obj.stopDate=obj.stopDate.format('YYYY-MM-DD');}
                //获取sessionStorage的数据
                let sessionInfo = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
                //obj.hospID =sessionInfo.hospID;
                obj.createUserID=sessionInfo.userID;
                obj.updateUserID=sessionInfo.userID;
                //更新需要父组件的传来的值
                obj.invTypeConUserTypeID= this.props.flag === 'add' ? '' : this.props.userInfo.invTypeConUserTypeID;
                obj.invTypeConUserID= this.props.flag === 'add' ? '' : this.props.userInfo.invTypeConUserID;
                // 处理需要传递的obj
                data.params.push(Util.disposeData(obj));
                $http.post('urlADS', this, {
                    code: code,
                    data: data,
                    success: function (res) { 
                        if (+res.errorCode=== 0) {
                          // 提示
                          message.success(msg + '成功');
                          // 新增或编辑成功重置form表单
                          this.resetFields();
                          // 关闭弹框
                          this.handleCancel();
                          // 刷新列表数据
                          this.props.handelThis.handleQueryBack();
                        }
                    },
                    error:function (error) {
                        message.error(msg + '失败：' + error);
                    }
                })
            }
        });
      }

      // 确定
    handleCreate = () => {
        let { flag } = this.props;
        if (flag === 'add') {
          this.handelFunction('05100038', '新增');
        } else if (flag === 'compile') {
            this.handelFunction('05100039', '编辑');
        }  
      }
      
      // 取消
    handleCancel = () => {
        this.setState({
            visible: false,
        }, () => {
            if (this.props.flag === 'compile') {
                this.props.handelThis.resetUserInfo()
            }
        });
      }



    //渲染界面
    render() {
      const { getFieldDecorator } = this.props.form;
      let userInfo = this.props.userInfo? this.props.userInfo : {}
      return (
        <Modal
          visible={this.state.visible}
          title={this.props.title + '发放发票权限'}
          okText="确定"
          onCancel={this.handleCancel}
          onOk={this.handleCreate}
        >
          <Form layout="vertical">
          
                <FormItem label="医院">
                        {getFieldDecorator('hospID', {
                            initialValue:userInfo.hospID ? String(userInfo.hospID):this.state.hospID,
                            rules: [{ required: true, message: '请选择' }]
                        })(
                         <Select
                          showSearch
                          placeholder="请输入"
                          optionFilterProp="children"
                          onChange={this.onChangeHospID}
                          filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                      >{this.state.hospList}</Select>
                        )}
                  </FormItem>
                <FormItem label="发票类型">
                        {getFieldDecorator('invTypeID', {
                            initialValue:userInfo.invTypeDr ? String(userInfo.invTypeDr):null,
                            rules: [{ required: true, message: '请选择' }]
                        })(
                          <Select
                          showSearch
                          placeholder="请输入"
                          optionFilterProp="children"
                          filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                      >{this.state.invList}</Select>
                        )}
                  </FormItem>
                  <FormItem label="人员类型">
                          {getFieldDecorator('userType', {
                              initialValue:userInfo.userType ? String(userInfo.userType):null,
                              rules: [{ required: true, message: '请选择' }]
                          })(
                         <Select
                            showSearch
                            placeholder="请输入"
                            optionFilterProp="children"
                            filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                         >
                            <Option value="1">管理员</Option>
                            <Option value="2">票据购入员</Option>
                            <Option value="3">收费员</Option>
                        </Select>
                          )}
                  </FormItem>
                  <FormItem label="人员">
                            {getFieldDecorator('userID', {
                                initialValue:userInfo.userDr ? String(userInfo.userDr):null,
                                rules: [{ required: true, message: '请选择' }]
                            })(
                              <Select
                              showSearch
                              placeholder="请输入"
                              optionFilterProp="children"
                              filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                          >{this.state.userList}</Select>
                            )}
                  </FormItem>
                 {/*FormItem label="生效日期">
                            {getFieldDecorator('startDate', {
                                initialValue: userInfo.startDate ? Moment(userInfo.startDate, 'YYYY-MM-DD') : null,
                                rules: [{ required: true, message: '请选择' }],
                                })(<DatePicker style={{width: '100%'}} format="YYYY-MM-DD"  /> )}
                  </FormItem>
                  <FormItem label="失效日期">
                              {getFieldDecorator('stopDate', {
                                  initialValue: userInfo.stopDate ? Moment(userInfo.stopDate, 'YYYY-MM-DD') : null,
                                  rules: [{ required: false, message: '请选择' }],
                              })(<DatePicker style={{width: '100%'}} format="YYYY-MM-DD"  /> )}
                            </FormItem>*/}
              
          </Form>
        </Modal>
      );
    }
  

}
);
//验证父组件出入数据合法性
export default PersonRelatedInvTypeModal; 
PersonRelatedInvTypeModal.propTypes = {
    // 验证userInfo的属性
    userInfo: PropTypes.object
  }