// 病历章节维护
import React from 'react';
import {Popconfirm, Icon, Table, Form, message, Input, Select, Modal} from 'antd';
import { $http } from 'containers/config/https';
import './style/index.less';
import ElectronicCaseTemplate from 'pages/common/ElectronicCaseTemplate.jsx';
import EMRToolLibrary from './component/EMRToolLibrary.jsx';

let {Option} = Select;

class ChapterMaintenance extends React.Component {
  constructor() {
    super();
    let userData = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
    this.state = {
      userData,
      dataSource: [],
      userInfo: {},
      visible: false,
      flag: "add",
      hospitalSelectData: [], // 医院下拉框数据
    };
    this.columns = [
      {
        title: '代码',
        dataIndex: 'eMRChapterCode',
        align: "center",
        key: '1',
      },
      {
        title: '描述',
        dataIndex: 'eMRChapterDesc',
        align: "center",
        key: '2',
      },
      {
        title: '所属医院',
        dataIndex: 'eMRChapterHospDesc',
        align: "center",
        key: '3',
      },
    ]
  }

  componentDidMount() {
    this.getTableData(); // 获取列表数据
  }
  
  // 获取医院下拉数据
  getHostSelectData = () => {
    let {userData} = this.state;
		var data = {
			params: [{
				hospID: '', // 医院id
				logonGroupID: userData&&userData.groupID ? userData.groupID : '', //登录角色id
				logonHospID: userData&&userData.hospID ? userData.hospID : '', // 登录医院id
			}]
		}
		$http.post('urlS', this, {
			code: "01040001",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					this.setState({
						hospitalSelectData: res.depDoctor,
          })
				}
			}
		});
  }

  // 获取章节列表数据
  getTableData = (_rowId) => {
    let data = {
      params: [{}]
    }
    $http.post('urlDeault', this, {
      code: "06010085",
      data: data,
      success: (res) => {
        if (+res.errorCode === 0) {
          for(var i = 0; i < res.result.length; i++) {
            res.result[i].key = i;
          }
          this.setState({dataSource: res.result, userInfo: {}, rowId: ""}, () => {
            if (_rowId) {
              for(var i = 0; i < this.state.dataSource.length; i++) {
                if (this.state.dataSource[i].eMRChapterID === _rowId) {
                  this.setState({userInfo: this.state.dataSource[i], rowId: _rowId});
                  break;
                }
              }
            }
          })
        }
      }
    })
  }

  // 保存
  handleSave = () => {
    this.caseTemplateChild.clearChapterStyle(false); // 章节名称不可删除
    const { form: { validateFields } } = this.props;
    validateFields((errors, values) => {
      // 验证成功
      if (errors === null) {
        let data = {
          params: []
        }
        let obj = JSON.parse(JSON.stringify(values));
        let _rowId = JSON.parse(JSON.stringify(this.state.rowId));
        if (_rowId) {
          let xmlStrAndDataSource = this.caseTemplateChild.getTemplateXml();
          obj.eMRChapterContent = xmlStrAndDataSource.xmlStr;
        } else {
          obj.eMRChapterContent = "";
        }
        obj.eMRChapterID = _rowId ? _rowId : '';
        // 处理需要传递的obj
        data.params.push(obj);
        $http.post('urlADS', this, {
          code: "06010083",
          data: data,
          success: function (res) { 
            if (+res.errorCode === 0) {
              // 成功提示
              message.success(res.errorMessage);
              // 新增或编辑成功重置form表单
              this.resetFields();
              // 关闭弹框
              this.handleCancel();
              // 刷新列表数据
              this.getTableData(_rowId ? _rowId : "");
            }
          }
        })
      }
    })
  }

  // 新增/编辑
  handleShowModal = (flag) => {
    if (flag === "add") {
      this.setState({rowId: "", userInfo: {}})
    }
    this.setState({visible: true, flag}, () => {
      if (!(this.state.hospitalSelectData&&this.state.hospitalSelectData > 0)) {
        this.getHostSelectData();
      }
    })
  }

  // 删除
  handleDelete = () => {
    let {userInfo} = this.state;
    let data = {
      params: [{
        eMRChapterID: userInfo.eMRChapterID,
      }]
    }
    $http.post('urlDeault', this, {
      code: "06010084",
      data: data,
      success: (res) => {
        if (+res.errorCode === 0) {
          message.success(res.errorMessage);
          this.getTableData();
        }
      }
    })
  }

  handleCaseTemplateRef = ref => {
    this.caseTemplateChild = ref;
  }

  // 关闭弹窗
  handleCancel = () => {
    this.setState({visible: false}, () => {
      if(this.state.flag === "compile") {
        this.resetFields();
      }
    })
  }

  // 重置表单
  resetFields = () => {
    this.props.form.resetFields();
  }

  // 表格行操作
  handleOnRow = (record) => {
    return {
			// 单击行选中
			onClick: () => {
				if (this.state.rowId === '') {
					// 保存行数据以及ID
					this.setState({rowId: record.eMRChapterID, userInfo: record}, () => {
            this.handleLoadingDocuments()
          })
				} else {
					if (this.state.rowId !== record.eMRChapterID) {
						this.setState({rowId: record.eMRChapterID, userInfo: record}, () => {
              this.handleLoadingDocuments()
            })
					}
				}
      },
      onDoubleClick: () => {
        console.log("onDoubleClick");
      }
		}
  }

  // 选中行操作 --- 左侧列表
  setRowClassName = (record) => {
    return record.eMRChapterID === this.state.rowId ? 'clickRowStyle' : '';
  }

  // 获取需要加载的模板路径
	handleLoadingDocuments = () => {
    let caseTemplateThis = this.caseTemplateChild ? this.caseTemplateChild : {}; // 公共病历组件this
		let data = {
			params: [{
				eMRChapterID: this.state.rowId, // 模板版本ID
			}]
		}
		$http.post('urlS', this, {
			code: "06010086",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					this.setState({templatePath: res.result.templatePath}, () => {
            let dataSource = res.result&&res.result.dataSource ? res.result.dataSource : [];
            this.state.templatePath ? caseTemplateThis.setElementTextByID(this.state.templatePath, dataSource, "N", "boolTrue") :caseTemplateThis.NewFile();
					})
				}
			}
		})
	}

  render() {
    let {dataSource, visible, userInfo, flag, hospitalSelectData} = this.state;
    const { getFieldDecorator } = this.props.form;
    let param = {
      setChapter: "show"
    }
    let caseTemplateThis = this.caseTemplateChild ? this.caseTemplateChild : {}; // 公共病历组件this
    
    let hospOption = hospitalSelectData&&hospitalSelectData.map((item, index) => {
      return (<Option key={item.id} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
    })
    return (
      <div className="emr-style">
				<div style={{width: "310px", height: '100%', display: 'inline-block', overflow: 'hidden'}}>
          <div style={{textAlign: "center", height: '34px', lineHeight: '34px', fontWeight: 900, fontSize: "14px", background: "#fafafa", borderBottom: "1px solid #e8e8e8"}}>病历章节维护</div>
          <div className="navigation-operation-icon" style={{background: "#fafafa"}}>
            <span 
              style={{
                color: "#1999db",
                cursor: "pointer",
              }}
              onClick={() => this.handleShowModal("add")}
            >
              <Icon type="plus" />新增
            </span>
            <span 
              style={{ 
                color:"#1890ff",
                cursor: "pointer",
              }}
              onClick={() => this.handleShowModal("compile")}
            >
              <Icon type="edit" />修改
            </span>
            <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={this.handleDelete} >
							<span style={{
                color: "rgb(240, 65, 52)", 
                cursor: "pointer",
              }} >
                <Icon type="delete" />
                删除
              </span>
						</Popconfirm>
          </div>
          <div style={{padding: "12px"}}>
            <Table 
              dataSource={dataSource} 
              columns={this.columns}
              onRow={this.handleOnRow}
              bordered
              pagination={false}
              rowClassName={this.setRowClassName}
            />
          </div>
        </div>
        <div style={{width: "calc(100% - 620px)", height: '100%', display: 'inline-block', overflow: 'auto'}}>
					<div style={{padding: '0 6px', position: 'relative', height: '100%' }}>
						<ElectronicCaseTemplate 
							param={param}
							onRef={this.handleCaseTemplateRef}
							handleSave={this.handleSave} // 保存
						/>
						<div style={{width: '6px', background: 'rgba(240, 242, 245, 1)', position: 'absolute', top: 0, left: 0, height: '100%'}}></div>
						<div style={{width: '6px', background: 'rgba(240, 242, 245, 1)', position: 'absolute', top: 0, right: 0, height: '100%'}}></div>
					</div>
				</div>
        <div style={{width: "310px", height: '100%', display: 'inline-block', overflow: 'hidden'}}>
          <EMRToolLibrary caseTemplateThis={caseTemplateThis} />
        </div>
        <Modal
          visible={visible}
          title={flag === 'add' ? '新增章节' : '修改章节'}
          okText="保存"
          onCancel={this.handleCancel}
          onOk={this.handleSave}
          width={600}
        >
          <Form>
            <Form.Item label="代码：">
              {getFieldDecorator('eMRChapterCode', {
                initialValue: userInfo.eMRChapterCode ? userInfo.eMRChapterCode: undefined,
                rules: [{ required: true, message: '代码不能为空' }]
              })(
                <Input placeholder="请输入" />
              )}
            </Form.Item>
            <Form.Item label="名称：">
              {getFieldDecorator('eMRChapterDesc', {
                initialValue: userInfo.eMRChapterDesc ? userInfo.eMRChapterDesc: undefined,
                rules: [{ required: true, message: '名称不能为空' }]
              })(
                <Input placeholder="请输入" />
              )}
            </Form.Item>
            <Form.Item label="所属医院：">
              {getFieldDecorator('hospID', {
                initialValue: userInfo.hospID ? userInfo.hospID: "",
              })(
                <Select disabled={userInfo&&userInfo.eMRChapterID ? true : false}>
                  {hospOption}
                </Select>
              )}
            </Form.Item>
          </Form>
        </Modal>
      </div>
    )
  }
};
const ChapterMaintenanceForm = Form.create()(ChapterMaintenance);
export default ChapterMaintenanceForm;