/*
 * Creator:     ML
 * CreatDate:   
 * descripts：病人信息列表
 * */
import React from 'react';
import { Form, Row, Col, Input, Select, Button, Table, Spin } from 'antd';
import moment from 'moment';
import { $http } from '../../containers/config/https';
import store from '../../store';
import { Util, dayFormat } from 'tools/index';
import RangeDatePicker from 'components/rangePicker/index';
import ModificationLogModal from './component/ModificationLogModal';
import ModificationPatientInfo from './component/ModificationPatientInfo';
import CommonPagination from 'components/pagination/index';
import './css/error.less';
// import CardTypeRead from 'components/cardType/index';

const FormItem = Form.Item;
const Option = Select.Option;
const userData = sessionStorage.userData ? JSON.parse(sessionStorage.userData) : {}

const formItemLayout = { // label 和input宽度
  labelCol: { span: 8 },
  wrapperCol: { span: 14 },
}

const formItemcardStatus = {
  labelCol: { span: 7 },
  wrapperCol: { span: 16 },
}

const formItemNumber = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
}

const BasicPatientInformation = Form.create()(
  class BasicPatientInformation extends React.Component {
    constructor(props) {
      super(props)
      var updateMessage = JSON.parse(sessionStorage.getItem('updateMessage'))
      var date = new Date();
      this.state = {
        loading: false,
        visible: false,
        logData: [],//日志变更数据
        baseParms: [],//下拉框数据
        total: 0,//表格总数据
        cardData: [],//查询出来的卡数据
        informationData: [],//绑定卡 卡关联数据
        values: {},//查询条件数据
        visibleCardTips: false,//卡操作成功弹窗
        flag: -1,//记录卡操作动作flag
        reciprocal: 2,//2S后关闭弹窗
        nowCost: 0,//卡费
        readLoading: false,//补卡loading
        postLoading: false,//卡操作确认提交
        searchLoading: false,//查询请求
        initpatCardID: '',//绑定卡时类型
        initCard: '',
        rowId: '',//表格行选中 卡关联
        rowIds: '',//表格行选中 页面数据
        bindVail: true,//点击绑定前是否通过验证
        bindLoading: false,//点击绑定loading
        newBindArr: [],//被绑的卡
        lastLight: false,//绑定成功 高亮当前
        bindMoreInfo: false,//绑卡更多信息显示
        bindCardArr: [],//已绑定的卡
        nowReadCard: '',//卡类型设置是否可操作 --卡操作remode
        idCardCodePop: '',//卡操作--身份证code
        repariFeeFlag: 'N',//费用置为0或空
        replenishZero: '',//是否可补0 卡操作
        patReplenishZero: '',//是否可补0 查询
        patCardLength: '',//卡长度 -- 查询
        logInfo: {},//查看日志流水
        showLog: 0,//控制卡操纵流水内容显示
        LogCardType: '',//日志流水选择卡类型
        logBeforeCardTypeID: '',
        logBeforeCardNo: '',
        startNoMessage: '',//开始日期未填写文字提示
        starNoVisible: false,//开始日期消息弹窗
        bindNoMessage: '',//绑定卡号
        patchNoMessage: '',//补卡卡号
        changeNoMessage: '',//换卡卡号
        bindNoVisible: false,//绑定卡号消息弹窗
        headerHeight: '',
        regDateFrom: '',
        regDateTo: '',
        infoDom: true,
        StartDate: moment(date).format(dayFormat),  // //开始日期
        EndDate: moment(date).format(dayFormat),  // //结束日期
        search: '',
        size: 'small',
        agencyArr: [],
        page: 1,
        pageSize: 20,
        updateMessage: updateMessage
      }
      this.bindCardType = React.createRef();
      this.bindCardNu = React.createRef();
      this.bindCardButton = React.createRef();

      this.patchCardNu = React.createRef();
      this.patchCardButton = React.createRef();

      this.changeCardNu = React.createRef();
      this.changeCardButton = React.createRef();

      this.changeOkButton = React.createRef();
      this.patchOkButton = React.createRef();
      this.bindOkButton = React.createRef();
    }
    componentDidMount() {
      // 初始化设置table的高度以及表体的高度
      sessionStorage.removeItem('updateMessage')
      document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y + 92 + 'px';
      let box = document.querySelector('.department-header');
      if (box) { //此处在加一层判断，更加严密，如果box存在的情况下获取
        this.setState({ headerHeight: box.offsetHeight })
      }
      this.getAngcy()
      let data = {}
      data = {
        params: [{
          cardTypeFlag: 1,//卡类型
          credTypeFlag: 1,//证件类型
          occupationFlag: '',	//职业
          socialStatusFlag: 1,//身份标签
          patTypeFlag: 1,	//病人类型
          cardStatusFlag: 1,//卡状态
          cardInfo: {},//点击onRow卡信息
        }]
      }
      $http.post('urlS', this, {
        code: '03030005',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            this.setState({
              baseParms: res,
            })
            this.props.form.setFieldsValue({ payMethods: res.payMethod[0].id });
          } else {

          }
        }
      })
      this.getFindDate()
    }
    //获取登记机构
    getAngcy = () => {
      let data = {}
      data = {
        params: [{

        }],
      }
      $http.post('urlS', this, {
        code: '01040269',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            this.setState({
              agencyArr: res.result && res.result.rows || []
            })
          }
        }
      })
    }
    //隐藏提示
    visibleTip = () => {
      this.setState({
        starNoVisible: false,
        bindNoVisible: false,
        patchNoVisible: false,
        changeNoVisible: false,
      })
    }

    // 修改page和pageSize 跳转至---
    onChange = (e, pageSize) => {
      this.setState({ page: e, pageSize: this.state.pageSize }, () => {
        // 重新调用查询方法
        let { values } = this.state;
        this.getFindDate(values);
      })
    }
    //下拉选择页数
    onShowSizeChange = (page, pageSize) => {
      this.setState({ page: 1, pageSize: pageSize }, () => {
        // 重新调用查询方法
        let { values } = this.state;
        this.getFindDate(values, 'search');
      })
    }
    // 显示分页总条数
    showTotal(total) {
      return `共 ${total} 条`;
    }
    //开始日期
    startChange(date) {
      this.setState({
        StartDate: date,
      })
    }
    //结束日期
    endChange(date) {
      this.setState({
        EndDate: date,
      })
    }
    getValue = (cardType, patCardNo) => {
      this.setState({
        cardType,
        patCardNo,
      })
    }
    //获取查询数据
    getFindDate = (values, e) => {
      var date = new Date();
      if (this.state.total == 0) {
        this.setState({
          searchLoading: true
        })
      }
      let { page, pageSize, cardType, patCardNo } = this.state;
      let data = {}
      data = {
        params: [{
          cardTypeID: cardType,
          cardNo: patCardNo,
          input: values && values.PatientInformation || '',
          socialStatusID: values && values.IdentityTag || '',
          patTypeID: values && values.PatientType || '',
          hospID: values && values.RegistrationBodies || '',
          regDateFrom: this.state.StartDate,
          regDateTo: this.state.EndDate,
        }],
        pagination: [{
          pageSize: pageSize,
          currentPage: page,
        }]
      }
      $http.post('urlS', this, {
        code: '03050086',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0 && res.result) {
            this.setState({
              searchLoading: false,
              rowId: '',
              search: e
            })
            for (var i = 0; i < res.result.Data.length; i++) {
              res.result.Data[i].key = i + 'card'
            }
            this.setState({ cardData: res.result.Data, total: res.result.TotalCount, }, () => {
            })
          } else {
            this.setState({
              searchLoading: false
            })
          }
        },
        error: function () {
          this.setState({
            searchLoading: false
          })
        }
      })

    }
    //点击查询---卡列表
    findCard = () => {
      this.props.form.validateFields((err, values) => {
        if (!err) {
          this.setState({
            values: values,
            flag: -1,
            rowIds: ''
          })
          this.setState({ page: 1, pageSize: this.state.pageSize }, () => {
            let { values } = this.state;
            // this.getFindDate(values)
            this.onShowSizeChange('1', this.state.pageSize)
          })
        }
      })
    }
    handleOk = (e) => {
      this.setState({ loading: true });
      setTimeout(() => {
        this.setState({ loading: false, visible: false });
      }, 3000);
    }
    //绑定弹窗
    showModal = () => {
      this.setState({
        visible: true,
      });
    }
    handleCancel = () => {
      this.visibleTip()
      this.handleRest()
      this.setState({
        visible: false,
        bindMoreInfo: false,
        bindVail: true,
        LogCardType: '',
      });
    }
    //获取日志流水详情
    getLogDeatil = (pD, cD) => {
      let data = {}
      data = {
        params: [{
          patID: pD,
          cardTypeID: cD,
        }],
      }
      $http.post('urlS', this, {
        code: '03030015',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            // console.log(res)
            this.setState({
              logWaterData: res.result
            })
            if (res.result.length == 0) {
              this.setState({
                showLog: 3
              })
            } else {
              this.setState({
                showLog: 2
              })
            }
          }
        }
      })
    }

    //点击绑卡后 进行默认行选中
    setRowClassName = (record) => {
      //  console.log('绑卡后',record)
      return record.cardID === this.state.rowId ? 'clickRowStyle' : '';
    }
    //点击查询后 表格行
    setRowClassNames = (record) => {
      return record.patID === this.state.rowIds ? 'clickRowStyle' : '';
    }
    //点击Row
    onClickRow = (record) => {
      return {
        onClick: () => {
          this.setState({
            parms: record,
          })
          if (this.state.rowId === '') {
            this.setState({
              rowIds: record.patID,
            });
          } else {
            if (this.state.rowId !== record.patID) {
              this.setState({
                rowIds: record.patID,
              });
            } else {
              this.setState({
                rowIds: '',
                detailInfo: {},
              });
            }
          }
        },
      };
    }
    //输入改变时 不可绑定
    closeBindVail = () => {
      this.visibleTip()
      this.setState({
        bindVail: true
      })
    }
    //重置卡操作表单
    handleRest = () => {
      this.props.form.setFieldsValue({ newCard: undefined })
      this.props.form.setFieldsValue({ cardNumber: undefined })
      this.props.form.setFieldsValue({ patchMoney: undefined })
      this.props.form.setFieldsValue({ transactionNo: undefined })
      this.props.form.setFieldsValue({ originalCard: undefined })
      this.props.form.setFieldsValue({ cardBindNo: undefined })
      // this.props.form.setFieldsValue({ cardBindNom: undefined })
      this.setState({
        initpatCardID: '',
        bindCardArr: [],
      })
      for (var j = 0; j < this.state.baseParms.cardType.length; j++) {
        this.state.baseParms.cardType[j]['disabled'] = false
      }
      // this.baseParms.
    }
    //查看日志
    handleLog = (info) => {
      // console.log(info)
      this.setState({
        logInfo: info,
        showLog: 1,
        logBeforeCardTypeID: info.patCardTypeID,
        logBeforeCardNo: info.patCardNo,
      })
      let data = {}
      data = {
        params: [{
          patCardID: info.patCardID,
        }],
      }
      $http.post('urlS', this, {
        code: '03030014',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            //判断接口请求成功数据是否返回成功
            for (var i = 0; i < res.data.length; i++) {
              res.data[i].key = i + 'log'
            }
            this.setState({
              logData: res.data,
            })
          }
        }
      })
    }

    //调用子组件的事件 -- 查看修改日志
    OnChildrefs = (ref) => {
      this.child = ref
    }
    //调用子组件的事件 -- 编辑
    OnChildref = (ref) => {
      this.childModif = ref
    }

    handleBack = () => {
      this.setState({
        infoDom: true
      })
      this.getFindDate(this.state.values);
    }

    handleModif = (record) => {
      this.childModif.showModifDom(record)
      this.setState({
        infoDom: false
      })
    }

    handleLog = (record) => {
      this.child.showModal(record)
    }
    render() {
      var updateMessage = JSON.parse(sessionStorage.getItem('updateMessage'))
      const { getFieldDecorator } = this.props.form;
      const { baseParms, searchLoading, bindLoading, agencyArr } = this.state;
      var date = new Date();
      let searchColConfig = {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
        lg: { span: 5 }
      }
      //病人类型
      let patType = []
      baseParms.patType && baseParms.patType.map(item => {
        patType.push(<Option key={item.id} value={item.id} title={item.descripts}>{item.descripts}</Option>)
      })
      //身份标签
      let socialStatus = []
      baseParms.socialStatus && baseParms.socialStatus.map(item => {
        socialStatus.push(<Option key={item.id} value={item.id} title={item.descripts}>{item.descripts}</Option>)
      })
      //登记机构
      let agency = []
      agencyArr && agencyArr.map(item => {
        agency.push(<Option key={item.id} value={item.id} title={item.descripts}>{item.descripts}</Option>)
      })

      //主页面查询结果表格
      const columns = [{
        title: '登记日期',
        dataIndex: 'regDate',
        width: 120,
        key: 'patName',
        align: "center",
      }, {
        title: '登记机构',
        dataIndex: 'regHospDesc',
        width: 180,
        align: "left",
        key: '1'
      }, {
        title: '病人ID',
        dataIndex: 'patNo',
        width: 100,
        align: "center",
        key: '2'
      }, {
        title: '姓名',
        dataIndex: 'patName',
        width: 140,
        align: "left",
        key: '3'
      }, {
        title: '性别',
        dataIndex: 'patSexDesc',
        width: 100,
        align: "left",
        key: '4'
      }, {
        title: '出生日期',
        dataIndex: 'patBirthDate',
        width: 135,
        align: "center",
        key: '5'
      }, {
        title: '证件类型',
        dataIndex: 'patCredTypeDesc',
        width: 150,
        align: "left",
        key: '6'
      }, {
        title: '证件号码',
        dataIndex: 'patCredNo',
        width: 200,
        align: "left",
        key: '7'
      }, {
        title: '手机号码',
        dataIndex: 'patMobile',
        width: 135,
        align: "center",
        key: '8'
      }, {
        title: '身份标签',
        dataIndex: 'patSocialStatusDesc',
        width: 160,
        align: "left",
        key: '9'
      }, {
        title: '病人类型',
        dataIndex: 'patTypeDesc',
        width: 135,
        align: "left",
        key: '10'
      }, {
        title: '操作',
        dataIndex: 'cardStatus2',
        width: 200,
        align: "center",
        key: '11',
        // disabled={record.allCardTypeFlag == 'Y'}
        // style={{color:(record.allCardTypeFlag == "Y"?'#BFBFBF':"rergb(24, 144, 255)")}} 
        // retrieveFlag 回收
        render: (text, record) => (
          <div style={{ color: '#1890ff', cursor: 'pointer' }}>
            <a
              type="primary"
              style={{ marginRight: "12px" }}
              onClick={() => this.handleModif(record)}>编辑</a>
            <a type="primary" onClick={() => this.handleLog(record)}>查看修改日志</a>
          </div>
        ),
      }];
      return (
        <Spin spinning={bindLoading}>
          <div style={{ padding: '4px 2px', }} className="cardListDom">
            <div style={{ display: (this.state.infoDom ? "block" : "none") }}>
              <div className="department-header">
                <Form>
                  <Row gutter={60} style={{ margin: '0' }}>
                    <Col span={5} style={{ padding: "0", marginRight: "16px" }}>
                      <FormItem label='人员标识' {...formItemNumber}>
                        {getFieldDecorator('PatientInformation', {
                          initialValue: undefined,
                          rules: [{ required: false, message: '' }],
                        })(
                          <Input placeholder='病人ID/姓名/身份证号码/手机号码' allowClear onPressEnter={this.findCard} />
                        )}
                      </FormItem>
                    </Col>
                    {/* <CardTypeRead getValue={this.getValue}></CardTypeRead> */}
                    <Col span={4} style={{ padding: "0" }}>
                      <FormItem label='身份标签' {...formItemcardStatus}>
                        {getFieldDecorator('IdentityTag', {
                          rules: [{ required: false, message: '' }],
                        })(
                          <Select placeholder='请选择身份标签' showSearch allowClear optionFilterProp="title" onSelect={this.handleposTag} style={{ width: '98%' }}>
                            {socialStatus}
                          </Select>
                        )}
                      </FormItem>
                    </Col>
                    <Col span={4} style={{ padding: "0" }}>
                      <FormItem label='病人类型' {...formItemcardStatus}>
                        {getFieldDecorator('PatientType', {
                          rules: [{ required: false, message: '' }],
                        })(
                          <Select placeholder='请选择病人类型' showSearch allowClear optionFilterProp="title" onSelect={this.handleposTag} style={{ width: '98%' }}>
                            {patType}
                          </Select>
                        )}
                      </FormItem>
                    </Col>
                    <Col span={3} style={{ padding: "0" }}>
                      <FormItem label='登记机构' {...formItemcardStatus}>
                        {getFieldDecorator('RegistrationBodies', {
                          rules: [{ required: false, message: '' }],
                          initialValue: userData.hospID
                        })(
                          <Select placeholder='请选择登记机构' showSearch allowClear optionFilterProp="title" onSelect={this.handleposTag} style={{ width: '98%' }}>
                            {agency}
                          </Select>
                        )}
                      </FormItem>
                    </Col>
                    <Col {...searchColConfig} style={{ padding: "4px 0", marginLeft: "26px" }}>
                      <RangeDatePicker label='登记日期：' format='YYYY-MM-DD' width={300}
                        startDate={moment(date).format(dayFormat)} endDate={moment(date).format(dayFormat)}
                        startChange={this.startChange.bind(this)} endChange={this.endChange.bind(this)} />
                    </Col>
                    <Col span={2} style={{ paddingLeft: "0" }}>
                      <FormItem  {...formItemLayout}>
                        {getFieldDecorator('posInp', {
                          initialValue: undefined,
                          rules: [{ required: false, message: '' }],
                        })(
                          <Button type="primary" loading={searchLoading} onClick={this.findCard}>查询</Button>
                        )}
                      </FormItem>
                    </Col>
                  </Row>
                </Form>
              </div>
              <div>
                <Table
                  loading={searchLoading}
                  scroll={{ x: 1735, y: store.getState().tableHeight.y + 146 }}
                  columns={columns}
                  dataSource={this.state.cardData}
                  pagination={false}
                  rowKey={record => record.key}
                  onRow={this.onClickRow}
                  rowClassName={this.setRowClassNames}
                  bordered
                  style={{ height: store.getState().tableHeight.y + 146 + 'px' }}
                // style={{ height: store.getState().tableHeight.y + 88 + 'px', marginTop: '12px', }}
                />
                <CommonPagination size={this.state.size} pageSize={this.state.pageSize} page={this.state.page} current={this.state.page} total={this.state.total} search={this.state.search}
                  onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={this.state.cardData}
                  onChange={this.onChange.bind(this)} />
              </div>
              <ModificationLogModal OnChildrefs={this.OnChildrefs}></ModificationLogModal>
            </div>
            {Util.isEmpty(updateMessage) ? <ModificationPatientInfo handleBack={this.handleBack.bind(this)} OnChildref={this.OnChildref}></ModificationPatientInfo> : null}
          </div>
        </Spin>
      )
    }
  });
export default BasicPatientInformation;