/*
 * Create:      柿子
 * CreateDate:  2022/07/13
 * Describe：   新增验光单
 * */
import React, { Component } from 'react';
import { Modal, Card, Row, Col, Button, Checkbox, Tooltip, Divider, Input, Icon, message } from 'antd';
import { $http } from 'containers/config/https';
import { Util } from 'tools';
import moment from 'moment';
import GetPatientInformation from './GetPatientInformation';
import PublicTablePagination from 'pages/common/PubilcTablePagination.jsx';
import DynamicRenderingForm from 'pages/common/DynamicRenderingForm';
import RangeDatePicker from 'components/rangePicker/index';
import '../style/index.less';
import iconListVisits from 'assets/images/icon_listvisits.png';

class AddOptometrySheet extends Component {
  constructor(props) {
    super(props);
    this.state = {
      areaRoomID: '', // 当前验光室
      visible: false,
      loading: false,
      totalWidth: 950,
      columns: [],
      tableData: [],
      selectData: {},
      otherInfoFormData: [],
      rowData: {},
      evaluationSheetFormData: [],
      inspectFlag: true, // 仅显示检查
      applicationVal: undefined, // 配镜申请单录入过滤
      applicationFormData: [], // 申请单数据
      startDate: moment().format('YYYY-MM-DD'),
      endDate: moment().format('YYYY-MM-DD'),
      historyLoading: false,
      historyOrdersClumns: [],
      historyOrdersTotalWidth: 780,
      rowID: '',
    };
    // 就诊列表
    this.staticColumns = [{
      key: 1,
      title: '病人ID',
      dataIndex: 'patNo',
      align: "center",
      width: 100
    }, {
      key: 2,
      title: '姓名',
      dataIndex: 'patName',
      align: "center",
      width: 100
    }, {
      key: 3,
      title: '性别',
      dataIndex: 'patSexDesc',
      align: "center",
      width: 100
    }, {
      key: 4,
      title: '挂号时间',
      dataIndex: 'reqDate',
      align: "center",
      width: 150
    }, {
      key: 5,
      title: '挂号科室',
      dataIndex: 'ordLocDesc',
      align: "center",
      width: 100
    }, {
      key: 6,
      title: '诊断',
      dataIndex: 'admDiag',
      align: "center",
      width: 100
    }, {
      key: 7,
      title: '挂号医生',
      dataIndex: 'ordDoctor',
      align: "center",
      width: 100
    }];
    // 历史医嘱
    this.staticHistoryColumns = [{
      key: 1,
      title: '状态',
      dataIndex: 'statusDesc',
      align: "center",
      width: 80
    }, {
      key: 2,
      title: '医嘱内容',
      dataIndex: 'ordersContent',
      align: "center",
      width: 150
    }, {
      key: 3,
      title: '实际金额',
      dataIndex: 'price',
      align: "center",
      width: 100
    }, {
      key: 4,
      title: '优惠后金额',
      dataIndex: 'newPrice',
      align: "center",
      width: 100
    }, {
      key: 5,
      title: '收费状态',
      dataIndex: 'ordLocDesc',
      align: "center",
      width: 100
    }, {
      key: 6,
      title: '开单医生',
      dataIndex: 'ordDoctorDesc',
      align: "center",
      width: 100
    }, {
      key: 7,
      title: '执行科室',
      dataIndex: 'recLocDesc',
      align: "center",
      width: 100
    }, {
      key: 8,
      title: '开单时间',
      dataIndex: 'ordDate',
      align: "center",
      width: 150
    }]
  }

  componentDidMount() {
    this.props.onRef && this.props.onRef(this);
  }

  getDefaultData = async () => {
    try {
      let res = await React.$asyncPost(this, '17020015');
      let applicationFormData = JSON.parse(JSON.stringify(res.result?.medList || []));
      this.setState({
        applicationFormData,
        copApplicationFormData: applicationFormData,
        selectData: {
          ...res.result,
          optometryType: [{
            id: 'S',
            descripts: '散瞳验光'
          }, {
            id: 'X',
            descripts: '小瞳验光'
          }]
        }
      })
    } catch (error) {
      console.log(error)
    }
  }

  // 修改弹窗状态
  modifyVisible = (visible, areaRoomID = '') => {
    let { columns, historyOrdersColumns, copApplicationFormData } = this.state;
    if (!(columns && columns.length > 0) && visible) {
      this.getColumnsData();
    }
    if (!(copApplicationFormData && copApplicationFormData.length > 0) && visible) {
      this.getDefaultData();
    }
    if (!(historyOrdersColumns && historyOrdersColumns.length > 0) && visible) {
      this.getHistoryOrdersColumnsData();
    }
    this.setState({ visible, areaRoomID });
  }

  getColumnsData = async () => {
    try {
      let data = {
        params: [{
          compontName: 'AddOptometrySheet',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result && res.result.C && res.result.C.length > 0 ? res.result.C.map((item, index) => {
        return {
          ...item,
          index,
          render: (text, record) => {
            if (item.dataIndex === '') {
              return (
                <Tooltip title={text}>
                  <span className="ellipsis" style={{ width: '100%', display: 'block' }}>{text}</span>
                </Tooltip>
              );
            } else {
              return text;
            }
          }
        }
      }) : [];
      if (columns && columns.length > 0) {
        this.setState({
          columns,
          totalWidth: res.totalWidth
        })
      }
      // 表单操作数据
      let otherInfoFormData = res.result?.formData || [];
      if (otherInfoFormData && otherInfoFormData.length > 0) {
        for (var i = 0; i < otherInfoFormData.length; i++) {
          if (otherInfoFormData[i].dataIndex === 'stockDesc') { // 散瞳药物
            otherInfoFormData[i].descindex = 'codeAndDesc';
            // otherInfoFormData[i].oldValueindex = 'stockID';
            // otherInfoFormData[i].valueindex = 'stockID';
          }
        }
        this.setState({ otherInfoFormData });
      }
    } catch (error) {
      console.log(error)
    }
  }

  getHistoryOrdersColumnsData = async () => {
    try {
      let data = {
        params: [{
          compontName: 'AddOptometrySheetHistoryOrders',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result && res.result.C && res.result.C.length > 0 ? res.result.C.map((item, index) => {
        return {
          ...item,
          index,
          render: (text, record) => {
            return (
              <Tooltip title={text}>
                <span className="ellipsis" style={{ width: '100%', display: 'block' }}>{text}</span>
              </Tooltip>
            );
          }
        }
      }) : [];
      if (columns && columns.length > 0) {
        this.setState({
          historyOrdersClumns: columns,
          historyOrdersTotalWidth: res.totalWidth
        })
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 查询
  handleQuery = () => {
    this.setState({ loading: true });
    let { startDate, endDate } = this.state;
    let patID = this.patientRef && this.patientRef.getPatientID();
    if (!patID) {
      message.error('请先输入人员标识查找患者！');
      this.setState({ loading: false })
      return;
    }
    let data = {
      params: [{
        patID,
        startDate,
        endDate
      }],
    }
    $http.post('urlS', this, {
      code: '17020012',
      data: data,
      success: function (res) {
        this.setState({ loading: false })
        if (res.errorCode === '0') {
          let tableData = Util.addKeyValueToDataSource(res.result?.rows || []);
          if (tableData && tableData.length > 0) {
            this.state.rowID = tableData[0]?.admID || '';
          }
          this.setState({ tableData }, () => {
            tableData && tableData.length > 0 ? this.getDetailData() : this.handleResetFields();
          })
        }
      },
      error: function () {
        this.setState({ loading: false })
      }
    })
  }

  // 操作行
  onClickRowPublic = (record) => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.rowID === '' || (this.state.rowID && (this.state.rowID !== record.admID))) {
          this.setState({ rowID: record.admID }, () => {
            this.getDetailData();
          })
        } else {
          this.handleResetFields();
        }
      }
    }
  }

  // 选中行操作
  setRowClassNamePublic = (record) => {
    return record.admID === this.state.rowID ? 'clickRowStyle' : '';
  }

  handleResetFields = () => {
    this.setState({ rowID: '', historyOrdersTableData: [], evaluationSheetFormData: [] });
  }

  // 根据就诊获取明细数据
  getDetailData = async () => {
    try {
      let { rowID, inspectFlag } = this.state;
      this.setState({ historyLoading: true });
      let data = {
        params: [{
          checkFlag: inspectFlag ? 'Y' : 'N', // 默认只查检查/Y
          admID: rowID
        }]
      }
      let res = await React.$asyncPost(this, '17020013', data);
      let feildList = res.result?.feildList || [];
      let evaluationSheetFormData = feildList && feildList.length > 0 ? feildList[0].field : [];
      let applicationFormData = JSON.parse(JSON.stringify(res.result?.medchild || []));
      evaluationSheetFormData = evaluationSheetFormData && evaluationSheetFormData.map((item, index) => {
        return {
          index,
          dataIndex: item?.dataIndex || item.code,
          typeCode: item?.fieldTypeCode || 'Input',
          detailItem: item?.fieldDataList || [],
          title: item?.descripts || '',
          defaultValue: item?.value || undefined,
          disabled: item?.disabled || 'Y',
          col: item?.col || 8,
          labelCol: item?.labelCol || 10,
          wrapperCol: item?.wrapperCol || 14,
        }
      })
      this.setState({
        historyLoading: false,
        historyOrdersTableData: Util.addKeyValueToDataSource(res.result?.ordList || []),
        applicationFormData,
        copApplicationFormData: applicationFormData,
        evaluationSheetFormData,
      });
    } catch (error) {
      this.setState({
        historyLoading: false,
        historyOrdersTableData: [],
        applicatinFormData: [],
        evaluationoSheetFormData: []
      });
    }
  }

  // 确认
  handleOk = async () => {
    try {
      let { rowID, applicationFormData, areaRoomID } = this.state;
      let otherVal = await this.otherInfoFormRef.handleSave();
      let copyRowID = rowID;
      let medchild = applicationFormData && applicationFormData.filter(item => item.checked === 'Y');
      if (!rowID) {
        message.error('请先选择患者挂号记录！');
        return;
      }
      if (otherVal.error) {
        message.error('请完善必填信息！');
        return;
      }
      if (!(medchild && medchild.length > 0)) {
        message.error('请先选择至少一个申请单项目！');
        return;
      }
      let data = {
        params: [{
          triageFlag: this.props.triageFlag || 'Y', // 是否分诊标志
          admID: rowID,
          medchild,
          areaRoomID, // 不分诊需传入诊室
          ...otherVal
        }]
      }
      let res = await React.$asyncPost(this, '17020014', data);
      message.success(res?.errorMessage || '新增成功');
      this.setState({ applicationVal: undefined });
      this.modifyVisible(false);
      this.handleResetFields();
      this.evaluationSheetFormRef && this.evaluationSheetFormRef.resetFields();
      this.props.handleQuery && this.props.handleQuery(copyRowID, 'N');
    } catch (error) {
      console.log(error);
    }
  }

  // 修改操作框数据
  handleModifyInputValue = (e, dataIndex, isQuery) => {
    this.state[dataIndex] = e;
    this.setState({}, () => {
      isQuery !== 'N' ? this.handleQuery() : '';
      dataIndex === 'inspectFlag' ? this.getDetailData() : ''; // 查询明细数据
    })
  }

  // 修改申请单选中数据
  handleModifyApplicationData = (checked, index) => {
    let { applicationFormData } = this.state;
    applicationFormData[index].checked = checked ? 'Y' : 'N';
    this.setState({});
  }

  // 过滤检查项目
  handleApplicationPressEnter = () => {
    let { applicationVal, copApplicationFormData } = this.state;
    this.setState({ applicationFormData: copApplicationFormData && copApplicationFormData.filter(item => item.medItemDesc.indexOf(applicationVal) > -1) });
  }

  render() {
    let { cardType, cardSelectData } = this.props;
    let { visible, loading, columns, totalWidth, tableData, inspectFlag, historyOrdersTotalWidth, historyOrdersTableData, historyOrdersClumns, otherInfoFormData, rowData, evaluationSheetFormData, applicationVal, startDate,
      endDate, selectData, applicationFormData, historyLoading
    } = this.state;

    return (
      <Modal
        width="66vw"
        title="新增验光检查单"
        className="add-optometry-sheet"
        visible={visible}
        destroyOnClose={true}
        onOk={this.handleOk}
        onCancel={() => this.modifyVisible(false)}
      >
        <div className="flex-align-items" style={{ padding: '12px 24px' }}>
          <GetPatientInformation cardType={cardType} cardSelectData={cardSelectData} onRef={ref => this.patientRef = ref} handleQuery={this.handleQuery} />
          <RangeDatePicker
            width="300px"
            format="YYYY-MM-DD"
            label="就诊日期："
            isChange={true}
            endDate={endDate}
            startDate={startDate}
            endChange={(e) => this.handleModifyInputValue(e, 'endDate')}
            startChange={(e) => this.handleModifyInputValue(e, 'startDate')}
          />
          <Button style={{ marginLeft: '15px' }} type="primary" onClick={this.handleQuery}>查询</Button>
        </div>
        <div style={{ height: '8px' }} className="common-query-split-line"></div>
        <Row>
          <Col span={17}>
            <div className="table-body-height" style={{ width: '100%', padding: 12 }}>
              <PublicTablePagination
                param={{
                  loading,
                  y: 100,
                  height: 150,
                  x: totalWidth,
                  data: tableData,
                  componentName: 'AddOptometrySheet',
                  columns: columns && columns.length > 0 ? columns : this.staticColumns,
                }}
                getColumns={this.getColumnsData}
                onClickRowPublic={this.onClickRowPublic}
                setRowClassNamePublic={this.setRowClassNamePublic}
              />
            </div>
            <div style={{ height: '8px' }} className="common-query-split-line"></div>
            <Card
              size="small"
              bordered={false}
              className="aos-evaluation-sheet"
              title={(
                <div className="card-title-left-icon">
                  <div></div>
                  科室检查
                </div>
              )}
            >
              <div style={{ maxHeight: '162px', overflow: 'auto' }}>
                <div style={{ paddingRight: '24px' }}>
                  <DynamicRenderingForm
                    formItemCol={{ labelCol: 9, wrapperCol: 15 }}
                    rowData={rowData}
                    selectData={selectData}
                    formData={evaluationSheetFormData && evaluationSheetFormData.length > 0 ? evaluationSheetFormData : []}
                    onRef={ref => this.evaluationSheetFormRef = ref}
                  />
                </div>
              </div>
              {evaluationSheetFormData && evaluationSheetFormData.length > 0 ? <Divider style={{ margin: '6px 0' }} /> : ''}
              <DynamicRenderingForm
                formItemCol={{ labelCol: 9, wrapperCol: 15 }}
                rowData={rowData}
                selectData={selectData}
                formData={otherInfoFormData && otherInfoFormData.length > 0 ? otherInfoFormData : []}
                onRef={ref => this.otherInfoFormRef = ref}
              />
            </Card>
            <div style={{ height: '8px' }} className="common-query-split-line"></div>
            <Card
              bordered={false}
              size="small"
              title={(
                <div className="card-title-left-icon">
                  <div></div>
                  验配申请单录入
                </div>
              )}
              className="aos-application-card"
              extra={(
                <Input
                  style={{ width: '200px' }}
                  prefix={<Icon type="search" />}
                  value={applicationVal}
                  placeholder="请输入名称后回车查询"
                  onChange={(e) => this.handleModifyInputValue(e.target.value, 'applicationVal', 'N')}
                  onPressEnter={this.handleApplicationPressEnter}
                />
              )}
            >
              <div className="aos-application-card-content">
                {applicationFormData && applicationFormData.map((item, index) => {
                  return (
                    <Checkbox
                      key={index}
                      disabled={item.disabled === 'Y' ? true : false}
                      checked={item.checked === 'Y' ? true : false}
                      onChange={(e) => this.handleModifyApplicationData(e.target.checked, index)}
                    >
                      {item.medItemDesc}
                    </Checkbox>
                  )
                })}
              </div>
            </Card>
          </Col>
          <Col span={7}>
            <div
              className="table-body-height"
              style={{ position: 'relative', height: '100%', paddingLeft: '8px' }}
            >
              <Card
                size="small"
                bordered={false}
                title={(
                  <div className="card-title-left-img">
                    <img src={iconListVisits} alt="" />
                    历史医嘱
                  </div>
                )}
                extra={(
                  <Checkbox checked={inspectFlag} onChange={(e) => this.handleModifyInputValue(e.target.checked, 'inspectFlag', 'N')}>仅显示检查</Checkbox>
                )}
              >
                <PublicTablePagination
                  param={{
                    loading: historyLoading,
                    y: 500,
                    height: 550,
                    x: historyOrdersTotalWidth,
                    data: historyOrdersTableData,
                    componentName: 'AddOptometrySheetHistoryOrders',
                    columns: historyOrdersClumns && historyOrdersClumns.length > 0 ? historyOrdersClumns : this.staticHistoryColumns,
                  }}
                  getColumns={this.getHistoryOrdersColumnsData}
                />
              </Card>
              <div className="common-card-left-split-line" style={{ width: 8 }}></div>
            </div>
          </Col>
        </Row>
      </Modal>
    );
  }
};

export default AddOptometrySheet;
