//发票类型弹出框的模型
import React from 'react';
import PropTypes from 'prop-types';
import { $http } from '../../containers/config/https';
import { Util} from '../../tools';
import { Modal, Form, Input, message,Select} from 'antd'
const FormItem = Form.Item;
const Option = Select.Option;




const InvPurChaseModal = Form.create()(
    // eslint-disable-next-line
    class extends React.Component {
      state = { visible: false,userList:[],invList:[] ,invTypeID:"",hospID:"",hospList:[]};

      componentDidMount() {
        this.props.onRef(this);
        let sessionInfo = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        this.setState({hospID:sessionInfo.hospID}, () => {
            this.handleHospQuery ();
            this.handleUserQuery();
            this.handleInvTypeQuery();
        });
      
      }
      componentWillUnmount() {
        this.setState = (state, callback) => {
            return
           }
        }

      // 显示弹出层
      showModal = () => {
        this.setState({
            visible: true,
        });
      }

      // 取消
      handleCancel = () => {
        this.setState({
            visible: false,
        }, () => {
            if (this.props.flag === 'compile') {
                this.props.handelThis.resetUserInfo()
            }
        });
      }
      
      // 重置表单
      resetFields() {
        this.props.form.resetFields(); //清空所有
      }
      
    
     // 发票类型下拉框
    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)
              }*/
          }
      })
  }
  
     // 查询条件 --- 类型
     onChangeInvType = (value) => {
        this.setState({ invTypeID: value, userList: [] },()=>{this.handleUserQuery();});
    }
     ///输入框值变化时需要绑定
     onChangeHospID = (value) => {
        this.setState({ hospID: value, userList: []},()=>{this.handleUserQuery();});
    }
    // 人员下拉框
    handleUserQuery = () => {
        let {invTypeID,hospID} = this.state;
        //获取sessionStorage的数据
        let sessionInfo = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        let data = {}
        data = {
            params: [{
                hospID:hospID,
                userType:"2",
                invTypeID: invTypeID
            }]
        }
        $http.post('urlS', this, {
            code: '05100053',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0 && res.invUserInfo) {
                    let tempList =[]
                    for (var i = 0; i < res.invUserInfo.length; i++) {
                        tempList.push(<Option key={res.invUserInfo[i].id} alias={res.invUserInfo[i].descriptsSPCode}>{res.invUserInfo[i].descripts}</Option>)
                    }
                    this.setState({
                        userList: tempList
                    })
                } 
                /*else {
                    setTimeout(() => {
                        this.setState({userList: [] })
                    }, 1000)
                }*/
            }
        })
    }   

    //医院下拉框
    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
                    })
                }
            }
        })
    }
      handelFunction(code, msg) {
        const { form: { validateFields } } = this.props;
        let sessionInfo = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        validateFields((errors, values) => {
            // 验证成功
            if (errors === null) {
                let data = {
                    params: []
                }
                let obj = values;
                if(obj.stDate){obj.stDate=obj.stDate.format('YYYY-MM-DD');}
                if(obj.stopDate){ obj.stopDate=obj.stopDate.format('YYYY-MM-DD');}
                obj.createUserID =sessionInfo.userID
                obj.updateUserID =sessionInfo.userID
                //obj.hospID=sessionInfo.hospID
                //obj.id= this.props.flag === 'add' ? '' : this.props.userInfo.ID;
                // 处理需要传递的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('5015', '新增');
        } 
      }

      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):null,
                      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.InvTypeID? String(userInfo.InvTypeID):null,
                      rules: [{ required: true, message: '请选择' }]
                  })(
                    <Select
                    showSearch
                    placeholder="请输入"
                    optionFilterProp="children"
                    onChange={this.onChangeInvType}
                    filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                >{this.state.invList}</Select>
                  )}
                  </FormItem>
                <FormItem label="起始号">
                    {getFieldDecorator('startNo', {
                        initialValue:userInfo.StartNo,
                        rules: [{ required: true, message: '请选择' }]
                    })(
                        <Input />
                    )}
                </FormItem>
                <FormItem label="结束号">
                    {getFieldDecorator('endNo', {
                        initialValue:userInfo.EndNo,
                        rules: [{ required: true, message: '请选择' }]
                    })(
                        <Input />
                    )}
                </FormItem>
                <FormItem label="前缀">
                    {getFieldDecorator('prefix', {
                        initialValue:userInfo.Prefix,
                        rules: [{ message: '请选择' }]
                    })(
                        <Input />
                    )}
                </FormItem>
                <FormItem label="购入人员">
                  {getFieldDecorator('userID', {
                      initialValue:userInfo.userID,
                      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>
               
            </Form>
          </Modal>
        );
      }
    }
  );
export default InvPurChaseModal;

InvPurChaseModal.propTypes = {
  // 验证userInfo的属性
  userInfo: PropTypes.object
}