/*
 * Creator:     ML
 * CreatDate:   2019-11-18
 * descripts：  医嘱查询 查找
 * */
import React from 'react';
import moment from 'moment';
import { Form, Row, Col, Select, Button, Table } from 'antd';
import { $http } from 'containers/config/https';
import store from 'store';
import { dayFormat } from 'tools/index';
import RangeDatePicker from 'components/rangePicker/index';
import CommonPagination from 'components/pagination/index';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import OrdersModel from "../../nurse/orders/ordersModel";
import "../style/doctorAdviceFind.less"

const padding = {
  padding: "0px"
}
const formItemLayoutYear = {
  labelCol: { span: 11 },
  wrapperCol: { span: 13 }
}
const formItemLayoutType = {
  labelCol: { span: 10 },
  wrapperCol: { span: 14 }
}
const formItemLayout = { // label 和input宽度
  labelCol: { span: 6 },
  wrapperCol: { span: 17 }
}
const FormItem = Form.Item;
const Option = Select.Option;

const DoctorAdviceFind = Form.create()(
  class DoctorAdviceFind extends React.Component {
    cacheOriginData = {};
    constructor() {
      super()
      var date = new Date();
      var userData = JSON.parse(sessionStorage.getItem('userData'));
      this.state = {
        userData: userData,
        activeKey: "",
        yearArr: [],
        loading: false,
        adviceLogArr: [],
        typeArr: [],
        statusArr: [],
        collArr: [],
        ordTypeID: "10000",
        StartDate: undefined,  // //开始日期
        EndDate: moment(date).format(dayFormat),  // //结束日期
        size: "small",
        search: "",
        page: 1,
        pageSize: 10,
        total: 0,
        collDetail: [],
        columns: [],
        parms: {},
        rowIds: "",
      }
    }

    componentDidMount() {
      // this.props.OnChild(this);
      // console.log("store.getState().tableHeight.y",store.getState().tableHeight.y)
      document.querySelector(".doctorAdviceDom .ant-table-body").style.height = 200 + 'px'
      // var x = document.querySelectorAll(".ant-table-body");
      // for (var i = 0; i < x.length; i++) {
      //   x[1].style.height = 200 + 'px';
      // }
      this.getAllSelect()
      this.getMainTableColumns()
      setTimeout(() => {
        this.findCollCharts()
      }, 600);
    }

    // 修改page和pageSize 跳转至---
    onChange = (e) => {
      this.setState({ page: e, pageSize: this.state.pageSize }, () => {
        // 重新调用查询方法
        let { values } = this.state;
        this.getOrdDate(values);
      })
    }

    //下拉选择页数
    onShowSizeChange = (page, pageSize) => {
      this.setState({ page: 1, pageSize: pageSize }, () => {
        // 重新调用查询方法
        let { values } = this.state;
        // if (this.state.outPatData && this.state.outPatData.length > 0) {
        this.getOrdDate(values, "search");
        // }
      })
    }

    // 显示分页总条数
    showTotal(total) {
      return `共 ${total} 条`;
    }

    //点击查询后 表格行
    setRowClassNames = (record) => {
      return record.ordID === this.state.rowIds ? 'clickRowStyle' : '';
    }

    //点击Row
    onClickRow = (record) => {
      return {
        onClick: () => {
          this.setState({
            parms: record,
          })
          if (this.state.rowIds === "") {
            this.setState({
              rowIds: record.ordID,
            });
          } else {
            if (this.state.rowIds !== record.ordID) {
              this.setState({
                rowIds: record.ordID,
              });
            } else {
              this.setState({
                rowIds: "",
                detailInfo: {},
              });
            }
          }
        },
      };
    }

    onColumnRef = (ref) => {
      this.columnRef = ref;
    }

    onRefs = (ref) => {
      this.childRef = ref
    }

    handleOpen = (e, ordID) => {
      this.childRef.showModal(ordID)
    }

    // 获取主列表columns
    getMainTableColumns = () => {
      let data = {
        params: [{
          compontName: "OrderSearch", // 医嘱查询coll表头
          reactCode: ['OrderSearch'],
          type: 'C',
        }]
      }
      $http.post('urlS', this, {
        code: '01040073',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            let arr = res.result && res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map(item => {
              return {
                align: item.align,
                widthNum: parseInt(item.width),
                width: item.width,
                dataIndex: item.dataIndex,
                title: <div onDoubleClick={() => this.columnRef.onOpenModel()}>{this.state.userData.language == 'EN' ? item.enDescripts : item.title}</div>,
                display: item.display,
                key: item.seqNo,
                render: (text, record) => {
                  // console.log("record", record)
                  if (item.code == "lifeCycle") {
                    return (
                      <span style={{ cursor: "pointer" }} onClick={(e) => this.handleOpen(e, record.ordID)}><span style={{ color: "#096dd9" }}>{record.lifeCycle}</span></span>
                    )
                  }
                  return text
                }
              }
            }) : '';
            let filterArr = arr.filter(function (item) { return item.display === 'Y' });
            this.setState({
              columns: filterArr, widthTotal: res.totalWidth, localeProvider: this.state.userData.language == 'EN' ? res.result.language.EN : res.result.language.CN
            }, () => {
              this.props.getDec(this.state.localeProvider)
            })
            // console.log("res.totalWidth",res.totalWidth)
          }
        }
      })
    }

    //就诊年份 -- 获取就诊记录
    handleYears = (years) => {
      if (years) {
        this.yearsToLog(years)
      } else {
        this.yearsToLog("")
      }
      this.props.form.setFieldsValue({ adviceLog: undefined })
    }

    //就诊记录--自动获取开始医嘱日期
    handleLog = (data, years) => {
      // console.log("---",data)
      this.setState({
        StartDate: "",
      }, () => {
        this.props.form.setFieldsValue({
          adviceYear: years
        })
        this.setState({
          StartDate: data,
        }, () => {
          this.findCollCharts()//选择就诊记录直接调起查询
        })
      })
    }

    //开始日期
    startChange(date) {
      // console.log("s----",date)
      this.setState({
        StartDate: date,
      })
    }

    //结束日期
    endChange(date) {
      this.setState({
        EndDate: date,
      })
    }

    //获取查询条件下拉
    getAllSelect = () => {
      let data = {}
      data = {
        params: [{
          patID: sessionStorage.patientData ? JSON.parse(sessionStorage.patientData).patID : "",
          // patID:"7",
          admYearsFlag: "Y",//就诊年限
          orderTypeFlag: "Y",//医嘱类型
          admRecordFlag: "Y",//就诊记录
          orderStatusFlag: "Y",//医嘱状态
        }],
      }
      $http.post('urlS', this, {
        code: '03050130',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0 && res.result) {
            this.setState({
              yearArr: res.result.admYears,
              adviceLogArr: res.result.admRecord,
              typeArr: res.result.ordPriority,
              statusArr: res.result.ordStatus,
            }, () => {
              res.result.admRecord && res.result.admRecord.map((item, i) => {
                if (sessionStorage.patientData && JSON.parse(sessionStorage.patientData).admID && JSON.parse(sessionStorage.patientData).admID == item.admID) {
                  this.props.form.setFieldsValue({ adviceLog: item.admID, adviceYear: item.years })
                  this.setState({
                    StartDate: item.admDate
                  }, () => {
                    this.yearsToLog(item.years)
                  })
                }
              })
            })
          }
        }
      })
    }

    //选择就诊年份获取急诊记录
    yearsToLog = (years) => {
      let data = {}
      data = {
        params: [{
          patID: sessionStorage.patientData ? JSON.parse(sessionStorage.patientData).patID : "",
          admRecordFlag: "Y",//就诊记录
          years,
        }],
      }
      $http.post('urlS', this, {
        code: '03050130',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0 && res.result) {
            this.setState({
              adviceLogArr: res.result.admRecord,
            }, () => {

            })
          }
        }
      })
    }

    //获取coll详细数据
    getOrdDate = (values, mes) => {
      const { page, pageSize } = this.state
      this.setState({ loading: true });
      let data = {}
      data = {
        params: [{
          years: values && values.adviceYear || "",
          admID: values && values.adviceLog || "",
          formDate: this.state.StartDate,
          toDate: this.state.EndDate,
          ordTypeID: this.state.ordTypeID,
          ordPriority: values && values.adviceType || "",
          ordStatus: values && values.adviceStatus || "",
        }],
        pagination: [{
          pageSize: pageSize,
          currentPage: page,
        }]
      }
      $http.post('urlS', this, {
        code: '03050132',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            for (var i = 0; i < res.result.Data.length; i++) {
              res.result.Data[i].key = i
            }
            this.setState({ collDetail: res.result.Data, total: res.result.TotalCount, search: mes, loading: false })
          } else {
            this.setState({ loading: false });
          }
        },
        error: function () {
          this.setState({
            loading: false,
            searchLoading: false
          })
        }
      })
    }

    //点击查询---coll列表 图表
    findCollCharts = () => {
      this.props.form.validateFields((err, values) => {
        // console.log("values",values)
        if (!err) {
          this.setState({
            values: values,
          }, () => {
            let { values } = this.state;
            this.getFindDate(values)
          })
        }
      })
    }

    //获取查询数据
    getFindDate = (values) => {
      let { page, pageSize, } = this.state;
      var date = new Date();
      this.setState({
        searchLoading: true
      })
      let data = {}
      data = {
        params: [{
          years: values && values.adviceYear || "",
          admID: values && values.adviceLog || "",
          formDate: this.state.StartDate,
          toDate: this.state.EndDate,
          ordPriority: values && values.adviceType || "",
          ordStatus: values && values.adviceStatus || "",
        }],
        pagination: [{
          pageSize: pageSize,
          currentPage: page,
        }]
      }
      $http.post('urlS', this, {
        code: '03050131',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            this.setState({
              searchLoading: false,
              collArr: res.orderType,
              activeKey: ""
            }, () => {
              this.getList("10000")
              this.props.getCharts(res.chart, this.state.localeProvider)
            })
          } else {
            this.setState({
              searchLoading: false
            })
          }
        },
        error: function () {
          this.setState({
            searchLoading: false
          })
        }
      })
    }

    //国际化
    setMessage(name, message) {
      return this.state.localeProvider ? this.state.localeProvider[name][message] : ''
    }

    //切换页签 刷新table
    getList = (id) => {
      const { collArr, values } = this.state
      collArr && collArr.map((item, i) => {
        if (id == item.ordTypeID) {
          this.setState({
            ordTypeID: item.ordTypeID
          }, () => {
            this.onShowSizeChange(1, this.state.pageSize)
          })
        }
      })
    }

    //切换小页签
    handleBlock = (id) => {
      if (id) {
        if (this.state.ordTypeID === "") {
          this.setState({
            ordTypeID: id,

          }, () => {
            this.getList(id)
          });
        } else {
          if (this.state.ordTypeID !== id) {
            this.setState({
              ordTypeID: id,
            }, () => {
              this.getList(id)
            });
          } else {
            this.setState({
              // ordTypeID: "",
              // collDetail: []
            }, () => {
            });
          }
        }
      }
    }

    // handleOpen=()=>{
    //   // var y =document.querySelectorAll(".ant-select-dropdown-menu-item")
    //   // for (var i = 0; i < y.length; i++) {
    //   //   if(y[i].style){
    //   //     y[i].style.textAlign = "left";
    //   //   }
    //   //   // console.log("y",y,"ystyle",y[i].style)
    //   // }
    // }
    render() {
      const { getFieldDecorator } = this.props.form;
      let { collArr, yearArr, adviceLogArr, loading, typeArr, statusArr, columns, widthTotal } = this.state
      var date = new Date();
      // console.log("this.props.modal",this.props.modal)
      let searchColConfig = {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
        lg: { span: this.props && this.props.modal ? 7 : 5 }
      }
      //就诊年份
      let yearOp = []
      yearArr && yearArr.map(item => {
        yearOp.push(<Option key={item.admYears} role={item.admYears + '^' + item.admYears} title={item.admYears} onClick={() => this.handleYears(item.admYears)} value={String(item.admYears)}>{item.admYears}</Option>)
      })
      //就诊记录
      let adviceLogOp = []
      adviceLogArr && adviceLogArr.map(item => {
        adviceLogOp.push(<Option className="DoctorAdviceFind-optionLeft" key={item.admID} role={item.admStr + '^' + item.admStr} onClick={() => this.handleLog(item.admDate, item.years)} title={item.admStr} value={String(item.admID)}>{item.admStr}</Option>)
      })
      //医嘱类型
      let typeOp = []
      typeArr && typeArr.map(item => {
        typeOp.push(<Option key={item.id} title={item.descripts} role={item.descripts + '^' + item.descriptsSPCode} value={String(item.id)}>{item.descripts}</Option>)
      })
      //医嘱状态
      let statusOp = []
      statusArr && statusArr.map(item => {
        statusOp.push(<Option key={item.id} title={item.descripts} role={item.descripts + '^' + item.descriptsSPCode} value={String(item.id)}>{item.descripts}</Option>)
      })
      return (
        <div className="doctorAdviceDom">
          <Form>
            <Row gutter={60} style={{ margin: "0", padding: "14px 0 0 1px" }}>
              <Col span={3} style={padding}>
                <FormItem {...formItemLayoutYear} label={this.setMessage('OrderSearchVisitYear', 'descripts')}>
                  {getFieldDecorator('adviceYear', {
                    initialValue: undefined,
                    rules: [{ required: false, message: '' }],
                  })(
                    <Select
                      style={{ width: "100%" }}
                      allowClear={true}
                      showSearch={true}
                      optionFilterProp="role"
                      onChange={this.handleYears}
                    >
                      {yearOp}
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col span={6} style={padding}>
                <FormItem {...formItemLayout} label={this.setMessage('OrderSearchMedicalRecord', 'descripts')}>
                  {getFieldDecorator('adviceLog', {
                    initialValue: undefined,
                    rules: [{ required: true, message: '请选择需要查询的就诊记录' }],
                  })(
                    <Select
                      className="logDom"
                      style={{ width: "100%", textAlign: "left", }}
                      showSearch={true}
                      optionFilterProp="role"
                      dropdownStyle={{
                        textAlign: "left",
                      }}
                    >
                      {adviceLogOp}
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col {...searchColConfig} style={{ padding: "4px 0" }}>
                <RangeDatePicker isChange={true} label={this.setMessage('OrderSearchMedicalDate', 'descripts')} format='YYYY-MM-DD' width={300}
                  startDate={this.state.StartDate} endDate={this.state.EndDate}
                  startChange={this.startChange.bind(this)} endChange={this.endChange.bind(this)} locale={this.state.userData.language} />
              </Col>
              <Col span={3} style={padding}>
                <FormItem {...formItemLayoutType} label={this.setMessage('OrderSearchTypeOfMedicalOrder', 'descripts')}>
                  {getFieldDecorator('adviceType', {
                    initialValue: undefined,
                    rules: [{ required: false, message: '' }],
                  })(
                    <Select
                      style={{ width: "100%" }}
                      allowClear={true}
                      showSearch={true}
                      optionFilterProp="role"
                    >
                      {typeOp}
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col span={3} style={padding}>
                <FormItem {...formItemLayoutYear} label={this.setMessage('OrderSearchMedicalOrderStatus', 'descripts')}>
                  {getFieldDecorator('adviceStatus', {
                    initialValue: "1",
                    rules: [{ required: false, message: '' }],
                  })(
                    <Select
                      style={{ width: "100%" }}
                      allowClear={true}
                      showSearch={true}
                      optionFilterProp="role"
                    >
                      {statusOp}
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col span={2} style={{ paddingLeft: "16px" }}>
                <FormItem  {...formItemLayout}>
                  {getFieldDecorator('find', {
                    initialValue: undefined,
                    rules: [{ required: false, message: '' }],
                  })(
                    <Button onClick={this.findCollCharts} style={{ background: 'rgba(66,185,131,1)', color: '#fff' }}>{this.setMessage('OrderSearchsearch', 'descripts')}</Button>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row style={{ margin: "0px 12px", position: "relative" }}>
              {/* <span style={{marginRight:"9px"}}>{this.setMessage('OrderSearchItemCategory', 'descripts')}</span> */}
              {
                collArr && collArr.map((item, i) => {
                  return (
                    <Button
                      style={{ marginRight: "12px", background: (this.state.ordTypeID == item.ordTypeID ? "#40a9ff" : ""), color: (this.state.ordTypeID == item.ordTypeID ? "#fff" : "#000000d9") }}
                      onClick={() => this.handleBlock(item.ordTypeID)}>{item.ordTypeDesc}
                    </Button>
                  )
                })
              }
              {
                collArr && collArr.map((item, i) => {
                  return (
                    (<span style={{ marginRight: "2px", display: (this.state.ordTypeID == item.ordTypeID ? "inline-block" : "none"), position: "absolute", right: "14px", lineHeight: "36px" }}>
                      <span style={{ fontWeight: "600" }}>{item.ordTypeDesc}</span>
                      {"("}{item.priceType + "￥"}
                      <span style={{ color: "rgb(48, 173, 105)" }}>{item.totalPrice}</span>
                      {")"}
                    </span>)
                  )
                })
              }
            </Row>
            {/* <Row style={{paddingLeft:"6px"}}>
            {/* <span style={{marginRight:"4px"}}>记录条数/已结算金额：</span> 
              {
                collArr && collArr.map((item, i) => {
                  return (
                      (<span style={{marginRight:"2px"}}>
                <span style={{fontWeight:"600"}}>{item.ordTypeDesc}</span>
                        {"(记录:"}
                        <span style={{ color: "rgb(48, 173, 105)", margin: "0 2px" }}>{item.totalCount}</span>
                        {"条;"}{item.priceType + "￥"}
                        <span style={{ color: "rgb(48, 173, 105)" }}>{item.totalPrice}</span>
                        {")"}
                      </span>)
                  )
                })
              }
            </Row> */}
            <Row style={{ padding: '0 12px 12px 12px' }} className="table-body-height">
              <Table
                loading={loading}
                scroll={{ x: (columns && columns.length > 0 ? widthTotal : 4000), y: store.getState().tableHeight.y - (this.props.tabHeight ? this.props.tabHeight + 50 : 458) }}
                columns={columns && columns.length > 0 ? columns : []}
                dataSource={this.state.collDetail}
                pagination={false}
                rowKey={record => record.key}
                onRow={this.onClickRow}
                rowClassName={this.setRowClassNames}
                bordered
                style={{ height: store.getState().tableHeight.y - (this.props.tabHeight || 408) + 'px', marginTop: '12px', }}
              />
              <CommonPagination size={this.state.size} current={this.state.page} total={this.state.total} search={this.state.search}
                onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={this.state.collDetail}
                onChange={this.onChange.bind(this)} />
            </Row>
          </Form>
          <ColumnAuthoritysModel
            clientWidth='800px'
            compontName='OrderSearch'
            configType="C"
            onRef={this.onColumnRef}
            reloadData={this.getMainTableColumns}
          />
          <OrdersModel onRefs={this.onRefs}></OrdersModel>
        </div>
      )
    }
  })
export default DoctorAdviceFind