/**
 * 检查医嘱关联处理方法
 */
import React from 'react';
import { Form, Input, Select, Button, message, Row, Icon, Divider, Popconfirm, DatePicker, Col } from 'antd';
import { $http } from 'containers/config/https';
import moment from 'moment';
import '../style/childStyle.less';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';

const { Option } = Select;

class OLDoseConversionUnit extends React.Component {
  constructor() {
    super();
    var userData = JSON.parse(sessionStorage.getItem('userData'));
    this.state = {
      allergens: [],
      selectData: {}, // 下拉框数据
      tableData: [], // 列表数据
      total: 0,
      page: 1,
      pageSize: 10,
      rowData: {}, // 编辑回显数据
      user: userData,
      medID: '',
    };
    this.columns = [
      {
        key: 1,
        title: '序号',
        dataIndex: 'key',
        align: "center",
        width: 50,
        render:(text,record,index)=>{
          return this.state.tableData.findIndex((value,index)=>{
            return value===record;
          })+1;
        }
      },
      {
        key: 2,
        title: '处理方法',
        dataIndex: 'methodIDDesc',
        align: "center",
        width: 150
      },
      {
        key: 4,
        title: '生效日期',
        dataIndex: 'startDate',
        align: "center",
        width: 80
      },
      {
        key: 5,
        title: '失效日期',
        dataIndex: 'stopDate',
        align: "center",
        width: 80
      },
      {
        title: '操作',
        key: 7,
        align: "center",
        width: 80,
        render: (text, record) => (
          <span>
            <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
            <span className='span' onClick={() => this.handleCompile(record)}>编辑</span>
            {/* 分割线 */}
            <Divider type="vertical" />
            <Icon type="delete" style={{ color: 'rgba(240,65,52,1)' }}></Icon>
            <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleDelete(record)} >
              <span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
            </Popconfirm>
          </span>
        ),
      }
    ];
  }

  componentDidMount() {
    this.getSelectData();
    if ((this.props.medData && this.props.medData.medID ? this.props.medData.medID : '') !== this.state.medID) {
      this.setState({ medID: this.props.medData.medID }, () => {
        this.handleQuery();
      })
    } else {
      this.child.handleLoading();
    }
  }

  componentWillReceiveProps(nextProps) {
    if ((nextProps.medData && nextProps.medData.medID ? nextProps.medData.medID : '') !== this.state.medID) {
      this.setState({ medID: nextProps.medData.medID }, () => {
        this.handleQuery();
      })
    }
  }

  // 调用子组件的连接事件
  onRef = (ref) => {
    this.child = ref
  }

  // 获取下拉框数据
  getSelectData = () => {
    let data = {
      params: [{
      }]
    }
    $http.post('urlS', this, {
      code: "03010067",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0 && res.result) {
          this.setState({ selectData: { ...this.state.selectData, ...{ method: res.result } } });
        }
      }
    })
  }

  // 请求列表数据
  getTableData() {
    let { page, pageSize, medID } = this.state;
    let data = {
      params: [{
        medItemID: medID // 医嘱项id
      }],
      pagination: [{
        pageSize: pageSize,
        currentPage: page,
        sortColumn: "Describe",
        sortOrder: "asc"
      }]
    }
    $http.post('urlS', this, {
      code: "03010068",
      data: data,
      success: function (res) {
        if (res.errorCode == 0) {
          this.setState({ tableData: res.rows, total: res.total }, () => {
            // 数据加载成功关闭loading
            this.child.handleLoading();
          })
        } else {
          this.setState({ tableData: [], total: 0 }, () => {
            // 数据加载成功关闭loading
            this.child.handleLoading();
          })
        }
      },
      error: function () {
        this.setState({ tableData: [], total: 0 }, () => {
          // 数据加载成功关闭loading
          this.child.handleLoading();
        })
      }
    })
  }

  // 查询
  handleQuery = () => {
    this.setState({ page: 1, pageSize: 10 }, () => {
      this.getTableData();
    })
  }

  // 保存
  handleSave = () => {
    const { rowData, user, medID } = this.state;
    this.props.form.validateFields((errors, values) => {
      if (errors) {
        return;
      }
      let data = {
        params: []
      };

      let obj = {};
      obj.medItemID = medID; // 医嘱项id
      obj.methodID = values.methodID || '';
      obj.startDate = values.startDate ? moment(values.startDate).format("YYYY-MM-DD") : '';
      
      if (rowData.id){
        obj.id = rowData && rowData.id ? rowData.id : undefined;
        obj.stopDate = values.stopDate ? moment(values.stopDate).format("YYYY-MM-DD") : '';
      }else{

      }

      data.params.push(obj);
      $http.post('urlADS', this, {
        code: '03010069',
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            message.success(res.errorMessage);
            this.handleQuery();
            this.resetFields();
          }else{
            message.error(res.errorMessage);
          }
        }
      })
    })
  }

  // 重置
  resetFields = () => {
    this.props.form.resetFields(); //清空所有
    this.setState({
      rowData: {}
    })
  }

  // 编辑
  handleCompile = record => {
    this.resetFields();
    this.setState({ rowData: record });
  }

  // 删除
  handleDelete = record => {
    let data = {
      params: [{
        id: record.id,
      }]
    }
    $http.post('urlADS', this, {
      code: '03010070',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          message.success('删除成功');
          // 刷新列表数据
          this.getTableData();
        }
      }
    })
  }

  render() {
    const { selectData, tableData, total, page, rowData } = this.state;

    const { getFieldDecorator } = this.props.form;
    // 组件所需参数
    const param = {
      // 表头配置
      columns: this.columns,
      // 表格数据
      data: tableData,
      // 数据总条数
      total: total,
      // 当前页数
      page: page,
      // 表格的宽度
      x: 900,
      y: 360,
      height: '400px'
    };

    const formLayout = {
      labelCol: { span: 10 },
      wrapperCol: { span: 14 },
    }

    // 检查注意事项
    let methodOpt = [];
    selectData.method && selectData.method.map((item, index) => {
      methodOpt.push(<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
    });

    return (
      <div>
        <Form layout={'horizontal'}>
          <Row>
            <Col span={7}>
              <Form.Item label="处理方法" {...formLayout}>
                {getFieldDecorator('methodID', {
                  initialValue: rowData.methodID ? rowData.methodID : undefined,
                  rules: [{ required: true, message: '不能为空' }]
                })(
                  <Select showSearch optionFilterProp="seatchprop" allowClear style={{ width: '100%' }} placeholder="请选择">
                    {methodOpt}
                  </Select>
                )}
              </Form.Item>
            </Col>
            <Col span={5}>
              <Form.Item label='生效日期' {...formLayout}>
                {getFieldDecorator('startDate', {
                  initialValue: rowData && rowData.startDate ? moment(rowData.startDate, "YYYY-MM-DD") : moment(),
                  rules: [{ required: false, message: '' }],
                })(
                  <DatePicker style={{ width: '100%' }} placeholder={'请选择生效日期'} disabledDate={(curDate) => {
                    return curDate && curDate > moment().endOf('day');
                  }} />
                )}
              </Form.Item>
            </Col>
            <Col span={5}>
              <Form.Item label='失效日期' {...formLayout}>
                {getFieldDecorator('stopDate', {
                  initialValue: rowData && rowData.stopDate ? moment(rowData.stopDate, "YYYY-MM-DD") : undefined,
                  rules: [{ required: false, message: '' }],
                })(
                  <DatePicker style={{ width: '100%' }} placeholder={'请选择失效日期'} disabledDate={(curDate) => {
                    return curDate && curDate < moment().startOf('day');
                  }} />
                )}
              </Form.Item>
            </Col>
            <Col span={3}>
              <Button style={{ margin: '3px 0 0 10px' }} type="primary" disabled={this.state.medID ? false:true} onClick={this.handleSave}>{rowData.id ? '修改' : '保存'}</Button>
            </Col>
          </Row>
        </Form>
        <div>
          <PubilcTablePagination param={param} handelThis={this} onRef={this.onRef} />
        </div>
      </div>
    )
  }
};
const OLDoseConversionUnitForm = Form.create()(OLDoseConversionUnit);
export default OLDoseConversionUnitForm;