// 医嘱项参数配置
import React from 'react';
import { Table, Button, Input, message, Modal, Form, Switch, Row, Col, Divider, Card } from 'antd';
import { $http } from 'containers/config/https';
import moment from 'moment';
moment.locale('zh-cn');
import store from 'store';
import ShowCommonTableModal from 'pages/workstation/component/ShowCommonTableModal';
import CommonPagination from 'components/pagination/index';
const FormItem = Form.Item;

class FormModal extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      locPropTypeOptID: '', //参数类型默认id
    }
  }

  saveData = () => {
    this.props.form.validateFields((error, values) => {
      if (error) {

      }
      this.props.saveData(values);
    });
    this.props.cancel();
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const { formList } = this.props;
    const formStyle = {
      labelCol: {
        xs: { span: 9 },
        sm: { span: 10 },
        md: { span: 9 }
      },
      wrapperCol: {
        xs: { span: 15 },
        sm: { span: 14 },
        md: { span: 15 }
      },
    };
    // formList.sort((a, b) => a.seqNo > b.seqNo);
    return (
      <Form layout={'horizontal'}>
        <Modal
          visible={this.props.visible}
          onCancel={this.props.cancel}
          okText={'保存'}
          onOk={this.saveData}
          width={1000}
        >
          <Divider />
          <Row>
            {formList && formList.length > 0 && formList[0].setting.map((value, index) => {
              return <Col key={value.propID} span={8}>
                <Form.Item label={value.propDesc} {...formStyle}>
                  {value.fieldType == 'Checkbox' ? (getFieldDecorator(String(value.propID), {
                    valuePropName: 'checked',
                    initialValue: value && (value.value === "Y" || value.value == 1) ? true : false
                  })(<Switch onChange={(e) => this.props.handleInputChange(e, index, "switch")} />))
                    :
                    (getFieldDecorator(String(value.propID), {
                      initialValue: value && value.value ? value.value : undefined
                    })(<Input onChange={(e) => this.props.handleInputChange(e, index, "input")} />))
                  }
                </Form.Item>
              </Col>
            })}
          </Row>
        </Modal>
      </Form>
    );
  }
}

const ModalForm = Form.create()(FormModal)
/// 医嘱项参数设置
class OrderItemParametersToConfigure extends React.Component {
  constructor(props) {
    super(props);
    var userData = JSON.parse(sessionStorage.getItem('userData'))
    this.values = {};
    this.state = {
      tableData: [],
      userData,
      formList: [],
      rowId: '',
      rowData: {},
      pagination: {
        current: 1,
        pageSize: 10
      },
      columns: [],
      loading: false,
      tablePage: 1,
      tablePageSize: 20,
      tableTotal: 0
    }
  }

  componentDidMount() {
    this.getPropSetting();
  }

  // 新增医嘱项参数
  addOneData = () => {
    let { rowId, rowData } = this.state;
    let formList = [];
    formList.push(rowData)
    if (rowId === "" || rowId === undefined) {
      this.getPropSetting("add")
    } else {
      if (this.modalForm) {
        this.modalForm.resetFields();
      }
      this.setState({ modalVisible: true, formList });
    }
  }

  // 保存
  saveData = () => {
    let { formList } = this.state;
    let data = {
      params: formList
    }
    $http.post("", this, {
      code: '03100213',
      data,
      success: function (res) {
        if (res.errorCode == 0) {
          message.success(res.errorMessage);
          this.getPropSetting();
        }
      }
    })
  }

  // 获取列表数据
  getPropSetting = (flag) => {
    let { rowMedID, tablePageSize, tablePage } = this.state;
    if (flag === "add") {
      if (!rowMedID) {
        message.warning("请先选择医嘱项");
        return;
      }
    }
    var data = {
      params: [{
        medID: flag === "add" ? rowMedID : undefined
      }],
      pagination: [{
        pageSize: tablePageSize,
        currentPage: tablePage,
        sortOrder: "asc"
      }],
    }
    $http.post("", this, {
      code: '03100214',
      data: data,
      success: function (res) {
        if (res.errorCode == 0) {
          let tableData = res.result && res.result.data ? res.result.data : [];
          if (flag === "add") { // 新增
            if (this.modalForm) {
              this.modalForm.resetFields();
            }
            this.setState({ modalVisible: true, formList: tableData && tableData.length > 0 ? tableData : [] });
          } else {
            if (res.columns.length > 0) {
              let columns = [{
                title: "医嘱项",
                key: 'medDesc',
                dataIndex: 'medDesc',
                width: '100px',
                align: 'center'
              }];
              res.columns.sort((a, b) => a.seqNo > b.seqNo);
              res.columns.map((value, index) => {
                let obj = {}
                if (value.fieldType == 'Checkbox') {
                  obj = {
                    title: value.desc,
                    key: value.id,
                    dataIndex: value.id,
                    width: '100px',
                    align: 'center',
                    render: (text, record) => {
                      return <Switch disabled checked={this.getInputValue(value.code, record.setting, "switch")} />
                    }
                  }
                } else {
                  obj = {
                    title: value.desc,
                    key: value.id,
                    dataIndex: value.id,
                    width: '100px',
                    align: 'center',
                    render: (text, record) => {
                      return this.getInputValue(value.code, record.setting, "")
                    }
                  }
                }
                columns.push(obj);
              });
              this.setState({ columns: columns });
            }
            if (tableData && tableData.length > 0) {
              // message.success(res.errorMessage);
              this.setState({ tableData, tableTotal: res.result.totalCount });
            } else {
              this.setState({ tableData: [], tableTotal: 0 });
              message.warning("未查询到数据");
            }
            this.setState({ rowId: '' });
          }

        }
      }
    });
  }

  // 获取输入域对应的value值
  getInputValue = (dataIndex, dataList, type) => {
    if (dataList && dataList.length > 0) {
      for (var i = 0; i < dataList.length; i++) {
        if (dataList[i].propCode === dataIndex) {
          if (type === "switch") {
            return dataList[i].value === "Y" || dataList[i].value == 1 ? true : false;
          } else {
            return dataList[i].value
          }
        }
      }
    }
  }

  onRef = (ref) => {
    this.childRef = ref;
  }

  //回车检索费用项目
  getItem = () => {
    this.setState({
      isShowCommonTableModal: true,
      rowMedID: "",
      search: "search",
      page: 1
    }, () => {
      this.loadSelectData()
      this.childRef.showModal();
    })
  }

  handleOnKeydown(e) {
    var e = window.event || e;
    let scroll_height = 50;
    let id = '';
    let oneArr = this.state.itemArr && this.state.itemArr.length > 0 ? this.state.itemArr : [];
    switch (e.keyCode) {
      case 13:
        if (this.state.rowMedID) {
          let obj = {}
          for (var i = 0; i < oneArr.length; i++) {
            if ((oneArr[i].id) === this.state.rowMedID) {
              obj = i > 0 ? oneArr[i] : oneArr[0];
              break;
            }
          }
          this.rowClick(obj);
        } else {

        }
        break;
      case 38: //上
        if (this.state.rowMedID) {
          for (var i = 0; i < oneArr.length; i++) {
            if (oneArr[i].id === this.state.rowMedID) {
              id = i > 0 ? oneArr[i - 1].id : oneArr[0].id;
              break;
            }
          }
          this.setState({ rowMedID: id }, () => {
            var orderItem = document.getElementById("orderItem");
            orderItem.scrollTop = orderItem.scrollTop - scroll_height;
          })
        } else {
          this.setState({ rowMedID: oneArr[0] ? oneArr[0].id : '' })
        }
        break;
      case 40: //下
        if (this.state.rowMedID) {
          for (let i = 0; i < oneArr.length; i++) {
            if (oneArr[i].id === this.state.rowMedID) {
              id = i + 1 >= oneArr.length ? oneArr[oneArr.length - 1].id
                : oneArr[i + 1].id;
              break;
            }
          }
          this.setState({ rowMedID: id }, () => {
            var orderItem = document.getElementById("orderItem");
            orderItem.scrollTop = orderItem.scrollTop + scroll_height;
          })
        } else {
          this.setState({ rowMedID: oneArr[0] ? oneArr[0].id : '' })
        }
        break;
    }
  }

  setRowClassNamePublic = (record) => {
    return (record.id || record.id) === this.state.rowMedID ? 'clickRowStyle' : '';
  }

  onClickRowPublic = (record) => {
    // console.log("onClickRowPublic", record)
    return {
      onClick: () => {
        this.setState({
          rowMedID: record.id
        })
      },
      onDoubleClick: () => {
        this.rowClick(record)
      }
    }
  }

  rowClick = (record) => {
    this.setState({
      rowMedID: record.id
    }, () => {
      this.props.form.setFieldsValue({ getItem: record.descripts })
      this.childRef.handleCancel();
    })
  }

  //隐藏弹出框
  hideModal(name) {
    this.setState({
      [name]: false,//将所有参数置为false
    });
  }

  //分页切换
  changePageSize(current, pageSize) {
    this.setState({ pageSize, page: current }, () => {
      this.loadSelectData();
    });
  }

  // 获取医嘱项弹窗列表数据
  loadSelectData = () => {
    let { userData, page, pageSize } = this.state;
    let data = {
      params: [{
        hospID: userData.hospID, // 医院id
        findCode: this.props.form.getFieldValue("getItem")//医嘱项搜索名称
      }],
      pagination: [{
        pageSize,
        currentPage: page,
      }]
    }
    $http.post('urlS', this, {
      code: "01010002",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({
            itemArr: res.result.Data, //  费用项目
            rowMedID: res.result.Data ? res.result.Data[0].ID : '',
            total: res.result.TotalCount
          })
        }
      }
    });
  }

  handleTableOnRow = (record, index) => {
    return {
      onClick: (event) => {
        if (this.state.rowId !== index) {
          this.setState({ rowId: index, rowData: record })
        } else {
          this.setState({ rowId: '' })
        }
      },
      onDoubleClick: (event) => {
        this.setState({ rowId: index, rowData: record }, () => {
          this.addOneData()
        });
      }
    }
  }

  handleInputChange = (e, index, type) => {
    let { formList } = this.state;
    formList[0].setting[index].value = type === "switch" ? (e ? "Y" : "N") : e.target.value;
    this.setState({ formList })
  }

  handlePageChange = (page, pageSize) => {
    this.setState({ tablePage: page, tablePageSize: pageSize }, () => {
      // 重新调用查询方法
      this.getPropSetting();
    });
  };

  handlePageSizeChange = (current, size) => {
    this.setState({ tablePage: 1, tablePageSize: size }, () => {
      // 重新调用查询方法
      this.getPropSetting();
    })
  };

  render() {
    let { isShowCommonTableModal, itemArr, search, page, total, tableData, tablePage, tableTotal } = this.state;
    const { getFieldDecorator } = this.props.form;
    const formItemLayoutType = {
      labelCol: { span: 5 },
      wrapperCol: { span: 19 }
    }

    let column = [{
      key: '1',
      title: '医嘱项代码',
      dataIndex: 'code',
      width: 100,
      align: "center",
    }, {
      key: '2',
      title: '医嘱项描述',
      dataIndex: 'descripts',
      width: 160,
      align: 'center'
    }]

    let param = {
      width: '96vh',
      // height: 300,
      top: "18%",
      left: "6%",
      columns: column,
      data: itemArr,
      isOnRow: true,
      TableClassName: 'tab-placeholder',
      rowClassName: true,
      showPagination: true,
      search,
      page,
      total,
    }
    return (
      <div className={'LocPropSetting'}>
        <Card size={'small'} title='医嘱项参数维护'>
          <Form style={{ marginTop: '18px', marginLeft: '10px' }}>
            <Row>
              <Col span={6}>
                <FormItem {...formItemLayoutType} label='医嘱项'>
                  {getFieldDecorator('getItem', {
                    initialValue: undefined
                  })(
                    <Input placeholder="输入首拼回车检索项目" allowClear onPressEnter={this.getItem}></Input>
                  )}
                </FormItem>
              </Col>
              <Col span={6} style={{ textAlign: "center", marginTop: "5px" }}>
                <Button onClick={this.getPropSetting} style={{ marginRight: "12px" }}>查询</Button>
                <Button type={'primary'} onClick={this.addOneData}>{this.state.rowId !== "" ? '修改' : '添加'}</Button>
              </Col>
            </Row>
          </Form>
        </Card>
        <Card title='参数明细' size={'small'}>
          <Table
            bordered
            columns={this.state.columns}
            dataSource={tableData}
            style={{ height: store.getState().tableHeight.y + 10 }}
            rowKey={(record, index) => index + (this.state.pagination.current - 1) * this.state.pagination.pageSize}
            rowClassName={(record, index) => {
              return index === this.state.rowId ? 'clickRowStyle' : '';
            }}
            scroll={{ x: 1000, y: store.getState().tableHeight.y - 35 }}
            pagination={false}
            className="table-body-height"
            onRow={this.handleTableOnRow}
          />
          <CommonPagination size='small' current={tablePage} total={tableTotal} search='search' pageSize="20"
            onShowSizeChange={this.handlePageSizeChange} complete={true} dataSource={tableData}
            loading={this.state.loading} onChange={this.handlePageChange} />
          <ModalForm
            ref={(el) => this.modalForm = el}
            saveData={this.saveData}
            data={this.state.tableData[this.state.rowId] ? this.state.tableData[this.state.rowId] : {}}
            formList={this.state.formList}
            visible={this.state.modalVisible}
            cancel={() => { this.setState({ modalVisible: false }) }}
            handleInputChange={this.handleInputChange} />
        </Card>
        <div className='doctor-advice-common-modal'
          tabIndex={1}
          onKeyDown={this.handleOnKeydown.bind(this)}
          style={{ outline: 'none' }}
        >
          <ShowCommonTableModal
            onClickRowPublic={this.onClickRowPublic}
            setRowClassNamePublic={this.setRowClassNamePublic}
            isShow={isShowCommonTableModal}
            // handleFocus={this.handleFocus.bind(this)}
            onHide={this.hideModal.bind(this, 'isShowCommonTableModal')}
            param={param}
            onRef={this.onRef}
            search={search}
            id="orderItem"
            compilePage={this.changePageSize.bind(this)}
          >
          </ShowCommonTableModal></div>
      </div>
    );
  }
}
const OrderItemParametersToConfigureForm = Form.create()(OrderItemParametersToConfigure);
export default OrderItemParametersToConfigureForm;
