import React from 'react';
import { Modal, Tabs, Form, Row, Col, Card, Radio, Input, Table, Button, Pagination } from 'antd';
import moment from 'moment';
import { $http } from 'containers/config/https';
import store from 'store';
import './style.less';
const { TextArea } = Input;
const TabPane = Tabs.TabPane;
var newArr = []
let user, patientData;
const ConsultationCenterModel = Form.create()(
  class extends React.Component {
    constructor(props) {
      user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
      patientData = JSON.parse(sessionStorage.getItem('patientData'));
      super(props);
      this.state = {
        visible: false,
        value: 1,
        activeKey: 'QuoteResourcesOrder',
        selectData: [],
        data: [],//医嘱
        dataSource: [],//中草药
        tableData: [],//生命体征
        orderAryColumn: [],//医嘱页签表头
        orderAryButton: [],//医嘱页签按钮
        middleHerbalAryColumn: [],//中草药页签表头
        temperatureAryColumn: [],//生命体征页签表头
        temperatureAryButton: [],//生命体征页签按钮
        rowId: "",//表格行id 设置颜色
        indexID: '',//行id
        // 主菜单分页数据
        total: 0,
        page: 1,
        pageSize: 10,
        detailTotal: 0, // 中草药分页数据
        page2: 1,
        pageSize2: 10,
        detail: 0, // 生命体征分页数据
        page3: 1,
        pageSize3: 10,
        // 表格loading
        loading: true,
        buttonArr: [],
        dataTitle: '',
        rowData: [],
        rowDataID: [],
        changeData: "",
        QROrder: '',
        areaData: "",
        ApplyData: "",
      }
    }
    componentDidMount() {
      let leftList = document.querySelectorAll('.orderHeight  .ant-table-body');
      if (leftList.length > 0) {
        leftList[0].style.height = store.getState().tableHeight.y + 230 + 'px';
      }
      this.quoteResourcesTime();
      this.props.onRef(this);
      // this.loadColumn("QuoteResourcesOrder", "orderAry");//查询列头数据
      // this.handleQuery("QuoteResourcesOrder");
      this.setState({
        showLoading: false
      })
    }
    quoteResourcesTime = () => {
      let data = {
        params: [{
          type: "quoteResourcesTime",
        }]
      }
      $http.post('urlS', this, {
        code: "04090020",
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            this.setState({
              selectData: res.result.Data,
              dataTitle: res.result.TimeIterval
            })
          }
        }
      })
    }
    //3.18.28.查询引用资源列表接口
    handleQuery = (activeKey, code) => {
      //console.log(activeKey,'1324694564654',code)
      // console.log("-----",this.state.activeKey)
      this.setState({ QROrder: activeKey })
      let { page, pageSize, page2, pageSize2, page3, pageSize3 } = this.state;
      let data = {
        params: [{
          hospID: user.hospID,//医院ID
          admID: this.props.admID,//就诊号
          type: activeKey == "QuoteResourcesOrder" ? "order" : (activeKey == "QuoteResourcesMiddleHerbal" ? "middleHerbal" : (activeKey == "QuoteResourcesTemperature") ? "temperature" : "order"),//order:医嘱;middleHerbal：中草药;temperature：生命体征
          orderPriority: code ? code : undefined,//S:长期;NORM:临时;OUT:出院带药
          timeIterval: this.state.dataTitle ? this.state.dataTitle : 'currentDay',//currentDay:当天;fiveDay:五日;sevenDay:七日;currentWeek:本周;"currentAdm":本次就诊
        }],
        pagination: [{
          pageSize: pageSize,
          currentPage: page,
          sortColumn: 'ordStartDate',
          sortOrder: 'asc'
        }]
      }
      $http.post('urlS', this, {
        code: "04090019",
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            this.setState({ data: res.result.Data, total: res.result.TotalCount, loading: false })
          } else {
            message.error('查询失败：' + res.errorMessage);
          }
        }
      })
    }
    //医嘱按钮点击
    handleClick = (code) => {
      //console.log(code);
      this.setState({ dataTitle: '' }, () => {
        this.handleQuery('QuoteResourcesOrder', code)
      })

    }
    //生命体征按钮点击
    timeIterval = (res) => {
      // console.log('youbian sange', res);
      // newArr = [];
      this.setState({ dataTitle: res }, () => {
        this.handleQuery('QuoteResourcesTemperature')
      })

    }
    //查询列头数据
    loadColumn = (compontName, columnName) => {
      //console.log("0-0-0-0-0",compontName,columnName);
      let data = {
        params: [{
          compontName: compontName,
          type: "",
        }]
      }
      $http.post('urlDeault', this, {
        code: "01040073",
        data: data,
        success: (res) => {
          if (+res.errorCode === 0) {
            // console.log("按钮",res.result.B)
            this.setState({
              orderAryButton: res.result.B,
              temperatureAryButton: res.result.B,
              [columnName + "Button"]: res.result.B,
              [columnName + "Column"]: res.result.C,
            })
          }
        }
      })
    }

    onChange = e => {
      this.setState({
        value: e.target.value,
      });
    }
    //显示弹框
    showModal = () => {
      this.setState({
        visible: true,
      });
    };
    //确认
    handleOk = e => {
      // console.log(e);
      this.props.handthis.addData(this.state.areaData);
      this.props.handleOk();
      // this.setState({
      //   visible: false,
      // });
    };
    //取消
    handleCancel = e => {
      // console.log(e);
      this.setState({
        visible: false,
      });
    }
    // 导航栏切换
    callback = (key) => {
      // console.log(".....",key)

      let columnFlag = "";
      // newArr = [];
      this.setState({ activeKey: key, rowId: '' }, () => {
        ///"QuoteResourcesOrder","QuoteResourcesMiddleHerbal","QuoteResourcesTemperature"
        switch (key) {
          case "QuoteResourcesOrder":
            columnFlag = "orderAry";
            break;
          case "QuoteResourcesMiddleHerbal":
            columnFlag = "middleHerbalAry";
            break;
          case "QuoteResourcesTemperature":
            columnFlag = "temperatureAry";
            break;
        }
        this.loadColumn(key, columnFlag);
      })

      this.handleQuery(key);
      // if (this.state[columnFlag + "Column"]&&this.state[columnFlag + "Column"].length === 0) {

      // }
      // this.loadColumn(key, columnFlag);//查询列头数据
    }
    // 页码改变的回调，参数是改变后的页码及每页条数 医嘱分页
    onChange = (page, pageSize) => {
      this.setState({ page: page, pageSize: pageSize }, () => {
        // 重新调用查询方法
        this.handleQuery("this.state.activeKey");
      });
    };

    onShowSizeChange = (current, size) => {
      this.setState({ page: 1, pageSize: size }, () => {
        // 重新调用查询方法
        this.handleQuery("this.state.activeKey");
      })
    };
    // 页码改变的回调，参数是改变后的页码及每页条数 中草药
    onChange2 = (page, pageSize) => {
      this.setState({ page2: page, pageSize2: pageSize }, () => {
        // 重新调用查询方法
        this.handleQuery("this.state.activeKey");
      });
    };

    onShowSizeChange2 = (current, size) => {
      this.setState({ page2: 1, pageSize2: size }, () => {
        // 重新调用查询方法
        this.handleQuery("this.state.activeKey");
      })
    };
    // 页码改变的回调，参数是改变后的页码及每页条数 生命体征
    onChange3 = (page, pageSize) => {
      this.setState({ page3: page, pageSize3: pageSize }, () => {
        // 重新调用查询方法
        this.handleQuery("this.state.activeKey");
      });
    };

    onShowSizeChange3 = (current, size) => {
      this.setState({ page3: 1, pageSize3: size }, () => {
        // 重新调用查询方法
        this.handleQuery("this.state.activeKey");
      })
    };
    // 显示分页总条数
    showTotal(total) {
      return `共 ${total} 条`;
    }

    //显示按钮
    onCheckChange = (tableData, key, e) => {
      tableData[key].value = e.target.value;
      this.setState({ tableData: tableData })
    }
    componentWillReceiveProps(nextProps) {
      if (nextProps.visible !== this.props.visible && nextProps.visible) {
        newArr = [];
        this.setState({
          areaData: nextProps.parData,
          rowData: [],
          rowDataID: [],
        }, () => {
          //console.log("-------",this.state.activeKey)
          let arrName = this.state.activeKey === 'QuoteResourcesOrder' ? 'orderAry' : 'temperatureAry';
          this.handleQuery(this.state.activeKey);
          this.loadColumn(this.state.activeKey, arrName);//查询列头数据
        })

      }
    }

    //过滤
    filterRowData = (obj) => {
      let columnFlag = "";
      switch (this.state.activeKey) {
        case "QuoteResourcesOrder":
          columnFlag = "orderAry";
          break;
        case "QuoteResourcesMiddleHerbal":
          columnFlag = "middleHerbalAry";
          break;
        case "QuoteResourcesTemperature":
          columnFlag = "temperatureAry";
          break;
      }
      let str = this.state.areaData;
      let column = this.state[columnFlag + "Column"];
      for (var i = 0; i < column.length; i++) {
        let cObj = column[i];
        if ((obj[cObj.dataIndex]) && (obj[cObj.dataIndex] !== "")) {
          str += ` ${obj[cObj.dataIndex]} `
        }
      }
      this.setState({
        areaData: str
      })
      // console.log("表头", column, "SUOYOU", this.state.areaData)
    }

    /** 去重*/
    unique5(arr) {
      var x = new Set(arr);
      return [...x];
    }
    //点击行，渲染当前行样式
    onClickRow = (record) => {
      // console.log('...record', record)
      return {
        onClick: () => {
          let rowDataID = this.state.rowDataID;
          rowDataID.push(record.indexID);
        //   let oldLen = rowDataID.length;
          rowDataID = this.unique5(rowDataID);
        //   let newLen = rowDataID.length;

        //   if (newLen == oldLen) {
            this.filterRowData(record);
            newArr.push(record)
        //   }
          this.setState({
            rowId: record.indexID,
            rowData: newArr,
            rowDataID: rowDataID,
          });

        },
      };
    }

    //设置点击row颜色 --左侧表格
    setRowClassName = (record) => {
      return record.ordID === this.state.rowId ? 'clickRowStyle' : '';
    }

    // 編輯刪除
    handleonChange = (e, value) => {
      this.setState({ areaData: e.target.value, rowData: [] });
      newArr = [];
    }

    render() {
      let { orderAryButton, temperatureAryButton } = this.state;
      let btnArr = []
      // orderAryButton && orderAryButton.map((item, i) => {
      //   btnArr.push(<Button value={item.descripts} key={item.orderPriority} code={item.orderPriority} onClick={(e) => this.handleClick(e)}>{item.descripts}</Button>)
      // })
      let radio = []
      temperatureAryButton && temperatureAryButton.map((item, i) => {
        radio.push(<Button type="primary" code={item.timeIterval} key={item.timeIterval} onClick={this.timeIterval.bind(this, item.code)}>{item.descripts}</Button>)
      })

      let text = this.state.areaData;
      this.state.rowData && this.state.rowData.map((item, i) => {

        //text += `${item.ordDate} ${item.ordTime} ${item.medDesc} ${item.ordDose} ${item.ordDoseUnitDesc} ${item.ordUsageDesc} ${item.ordFreqDesc}`
        // text.push( <ul>
        //   <li key={i}>
        //   {console.log(item)}
        //   {'第' + (i + 1) + '条'}
        //   <li style={{ margin: '0 10px' }}>{item.ordDate}</li>
        //   <li style={{ margin: '0 10px' }}>{item.ordTime}</li>
        //   <li style={{ margin: '0 10px' }}>{item.medDesc}</li>
        //   <li style={{ margin: '0 10px' }}>{item.ordDose}</li>
        //   <li style={{ margin: '0 10px' }}>{item.ordDoseUnitDesc}</li>
        //   <li style={{ margin: '0 10px' }}>{item.ordUsageDesc}</li>
        //   <li style={{ margin: '0 10px' }}>{item.ordFreqDesc}</li>
        //   <li style={{ margin: '0 10px' }}>{item.ordStopDate}</li>
        //   <li style={{ margin: '0 10px' }}>{item.ordStopTime}</li>
        //   <li style={{ margin: '0 10px' }}>{item.prescInfo}</li>
        //   <li style={{ margin: '0 10px' }}>{item.ordDosc}</li>
        //   <li style={{ margin: '0 10px' }}>{item.ordUsageDesc}</li>
        //   <li style={{ margin: '0 10px' }}>{item.prescTypeDesc}</li>
        //   <li style={{ margin: '0 10px' }}>{item.date}</li>
        //   <li style={{ margin: '0 10px' }}>{item.time}</li>
        //   <li style={{ margin: '0 10px' }}>{item.temperature}</li>
        //   <li style={{ margin: '0 10px' }}>{item.SBP}</li>
        //   <li style={{ margin: '0 10px' }}>{item.DBP}</li>
        //   <li style={{ margin: '0 10px' }}>{item.Barthel}</li>
        //   <li style={{ margin: '0 10px' }}>{item.pulse}</li>
        // </li>
        //   </ul>
        //   )
      })

      return (
        <Modal
          title="引用"
          width={'70%'}
          visible={this.props.visible}
          onOk={this.handleOk}
          onCancel={this.props.handleOk}
        >
          <div className="new-department" style={{ border: '1px solid #CCCCCC' }}>
            <Row gutter={12}>
              <Col span={8}>
                <Card title="文本编辑" style={{ height: '650px' }}>

                  <TextArea
                    style={{ height: '440px', fontWeight: 'bold', fontsize: '14px', color: '#333', border: '1px solid #CCCCCC', padding: '0 24px 24px 0' }}
                    placeholder="请输入文本编辑"
                    name={'textarea'}
                    value={`${text}`}
                    autosize={{ minRows: 2, maxRows: 6 }}
                    onChange={this.handleonChange}
                  />

                </Card>
              </Col>
              <Col span={16}>
                <Card title="引用资源">
                  <Tabs
                    activeKey={this.state.activeKey}
                    onChange={this.callback}
                    tabPosition="right"
                    type="card"
                    className="new_department_tabs"
                    style={{ width: '100%' }}
                  >
                    <TabPane tab="医嘱" key="QuoteResourcesOrder">
                      <Row>
                        <Col span={24} style={{ marginBottom: '15px', zIndex: '99999' }}>
                          {this.state.orderAryButton && this.state.orderAryButton.map((item, i) => {
                            return (<Button type="primary" value={item.descripts} key={item.orderPriority} onClick={this.handleClick.bind(this, item.code)}>{item.descripts}</Button>)
                          })}
                          {/* {btnArr} */}
                        </Col>
                        <Col>
                          <Table
                            scroll={{ x: 1000, y: store.getState().tableHeight.y - 150 }}
                            style={{ height: store.getState().tableHeight.y - 190 + 'px', marginTop: '41px' }}
                            dataSource={this.state.data}
                            columns={this.state.orderAryColumn}
                            rowKey={(row) => {
                              return row.indexID
                            }}
                            onRow={this.onClickRow}
                            rowClassName={this.setRowClassName}
                            pagination={false}
                            bordered
                          />
                          {/* 分页: total--总条数  defaultCurrent--默认的当前页 hideOnSinglePage--只有一页时隐藏分页器 */}
                          <Pagination
                            showTotal={() => this.showTotal(this.state.total)}
                            size="small"
                            showQuickJumper
                            showSizeChanger
                            defaultCurrent={1}
                            current={this.state.page}
                            total={this.state.total ? this.state.total : 0}
                            onChange={this.onChange}
                            onShowSizeChange={this.onShowSizeChange}
                            style={{ textAlign: "right", marginTop: '13px' }}
                          />
                        </Col>
                      </Row>

                    </TabPane>
                    <TabPane tab="中草药" key="QuoteResourcesMiddleHerbal">
                      <Row>
                        <Col>
                          <Table
                            scroll={{ x: 1000, y: store.getState().tableHeight.y - 150 }}
                            style={{ height: store.getState().tableHeight.y - 190 + 'px', marginTop: '41px' }}
                            dataSource={this.state.data}
                            columns={this.state.middleHerbalAryColumn}
                            rowClassName="editable-row"
                            onRow={this.onClickRow}
                            rowKey={(row) => {
                              return row.indexID
                            }}
                            pagination={false}
                            bordered
                          />
                          {/* 分页: total--总条数  defaultCurrent--默认的当前页 hideOnSinglePage--只有一页时隐藏分页器 */}
                          <Pagination
                            showTotal={() => this.showTotal(this.state.total)}
                            size="small"
                            showQuickJumper
                            showSizeChanger
                            defaultCurrent={1}
                            current={this.state.page2 ? this.state.page2 : 1}
                            total={this.state.detailTotal ? this.state.detailTotal : 0}
                            onChange={this.onChange2}
                            onShowSizeChange={this.onShowSizeChange2}
                            style={{ textAlign: "right" }}
                          />
                        </Col>
                      </Row>
                    </TabPane>
                    <TabPane tab="生命体征" key="QuoteResourcesTemperature">
                      <Row>
                        <Col span={24} style={{ marginBottom: '15px', zIndex: '99999' }}>
                          {radio}
                        </Col>

                        <Col>
                          <Table
                            scroll={{ x: 1000, y: store.getState().tableHeight.y - 150 }}
                            style={{ height: store.getState().tableHeight.y - 190 + 'px', marginTop: '41px' }}
                            dataSource={this.state.data}
                            onRow={this.onClickRow}
                            rowKey={(row) => {
                              return row.indexID
                            }}
                            columns={this.state.temperatureAryColumn}
                            rowClassName="editable-row"
                            pagination={false}
                            bordered
                          />
                          {/* 分页: total--总条数  defaultCurrent--默认的当前页 hideOnSinglePage--只有一页时隐藏分页器 */}
                          <Pagination
                            showTotal={() => this.showTotal(this.state.total)}
                            size="small"
                            showQuickJumper
                            showSizeChanger
                            defaultCurrent={1}
                            current={this.state.page ? this.state.page : 1}
                            total={this.state.total ? this.state.total : 0}
                            onChange={this.onChange3}
                            onShowSizeChange={this.onShowSizeChange3}
                            style={{ textAlign: "right" }}
                          />
                        </Col>
                      </Row>
                    </TabPane>
                  </Tabs>
                </Card>
              </Col>
            </Row>
          </div>
        </Modal>
      )
    }
  }
)
export default ConsultationCenterModel;