// 医嘱引用规则
import React from 'react';
import {Select, Input, Table, Button, Card, Row, Col, Form, Checkbox, Divider, message, Popconfirm, Icon, Switch} from 'antd';
import { $http } from 'containers/config/https';
import './style/index.less';

let {Option} = Select;

class OrderReferenceRule extends React.Component {
  constructor() {
    super();
    let userData = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
    this.state = {
      selectData: [],
      leftTableData: [],
      userData,
      leftColumns: [],
      selectedRowKeys: [],
      rightTableData: [],
      rightColumns: [],
      rowData: {},
      hospitalData: [], // 医院下拉框数据
      departmentInformation: [], // 科室下拉数据
    };
  }

  componentDidMount() {
    this.getLeftColumns();
    this.getSelectData();
    this.getRightTableData();
    this.getRightColumns();
    this.loadHospitalMsg();
  }

	// 获取tabs数据
	getSelectData = () => {
		let data = {
			params: [{
				compontName: "EMRCitingResources",
				type: "C",
			}]
		}
		$http.post('urlDeault', this, {
			code: "01040073",
			data: data,
			success: (res) => {
				if (+res.errorCode === 0) {
          let arr = res.result.C.filter(function(item){ return "knowledgeBase" !== item.code && "SpecializedKnowledgeBase" !== item.code});
					this.setState({selectData: arr})
				}
			}
		})
  }

  getLeftColumns = () => {
    let {userData} = this.state;
    let columns = [
      {
        title: '代码',
        dataIndex: 'code',
        align: "center"
      }, 
      {
        title: '描述',
        dataIndex: 'descripts',
        align: "center"
      }, 
      {
        title: userData.language == "EN" ? "descripts" : '是否引用',
        dataIndex: 'isQuote',
        align: "center",
        render: (text, record, index) => {
          return (
            <Checkbox checked={record.isQuote} onChange={() => this.handleIsQuoteChange(record)}></Checkbox>
          )
        },
      }
    ]
    this.setState({leftColumns: columns})
  }

  // 改变引用状态
  handleIsQuoteChange = (record) => {
    let {leftTableData} = this.state;
    for(var i = 0; i < leftTableData.length; i++) {
      if (leftTableData[i].id == record.id) {
        leftTableData[i].isQuote = !leftTableData[i].isQuote;
        break;
      }
    }
    this.setState({leftTableData})
  }

  // 名称
  handleNameIDChange = e => {
    this.props.form.setFieldsValue({
      eMRResourceRuleCode: e
    });
    this.getLeftTableData(e);
  }

  // 过滤数组中相同的元素
  filterTheSameElements = (data1, data2) => {
    let arr =data1.filter(item => !data2.some(ele => ele.id === item.id))
    return arr;
  }

  // 获取左侧列表数据
  getLeftTableData = (e, arr) => {
		let data = {
			params: [{
				compontName: e,
				type: "",
			}]
		}
		$http.post('urlDeault', this, {
			code: "01040073",
			data: data,
			success: (res) => {
				if (+res.errorCode === 0) {
          if (arr&&arr.length > 0) {
            let filterData = this.filterTheSameElements(res.result.C, arr);
            this.setState({leftTableData: arr.concat(filterData)})
          } else {
            for(var i = 0; i < res.result.C.length; i++) {
              res.result.C[i].isQuote = false;
              res.result.C[i].key = i;
            }
            this.setState({leftTableData: res.result.C})
          }
				}
			}
		})
  }

  handleOnKeydown = (e) => {
    var e = window.event || e;
    switch (e.keyCode) {
      case 38: //上
        this.handleUp()
        break;
      case 40: //下
        this.handleDown();
        break;
    }
}
  
  //上移
  handleUp = () => {
    var keys = this.state.selectedRowKeys;
    var data = this.state.leftTableData;
    var newKeys = []
    keys = keys.sort(function (m, n) {
      if (m < n) return -1
      else if (m > n) return 1
      else return 0
    });
    for (var i = 0; i < keys.length; i++) {
      if (keys[i] === 0) {
        newKeys.push(keys[i])
        continue
      }
      var curRowData = data[keys[i]]
      var curRowKey = curRowData.key
      var upRowData = data[keys[i] - 1]
      var upRowKey = upRowData.key
      upRowData.key = curRowKey
      curRowData.key = upRowKey
      data[keys[i]] = upRowData
      data[keys[i] - 1] = curRowData
      newKeys.push(keys[i] - 1)
    }
    this.setState(
      {
        leftTableData: data,
        selectedRowKeys: newKeys
      }
    )
  }

  //下移
  handleDown = () => {
    var keys = this.state.selectedRowKeys;
    var data = this.state.leftTableData;
    var newKeys = []
    keys = keys.sort(function (m, n) {
      if (m < n) return -1
      else if (m > n) return 1
      else return 0
    });
    for (var i = keys.length - 1; i >= 0; i--) {
      if (keys[i] === data.length - 1) {
        newKeys.push(keys[i])
        continue
      }
      var curRowData = data[keys[i]]
      var upRowData = data[keys[i] + 1]
      var curRowKey = curRowData.key
      var upRowKey = upRowData.key
      upRowData.key = curRowKey
      curRowData.key = upRowKey
      data[keys[i]] = upRowData
      data[keys[i] + 1] = curRowData
      newKeys.push(keys[i] + 1)
    }
    this.setState(
      {
        leftTableData: data,
        selectedRowKeys: newKeys
      }
    )
  }

  // 过滤需要引用的数据
  filterQuoteTableData = (data) => {
    let arr = [];
    for(var i = 0; i < data.length; i++) {
      if (data[i].isQuote) {
        arr.push(data[i].id)
      }
    }
    return arr;
  }

  // 根据名称下拉框的code获取到描述
  getDescriptionByCode = (code) => {
    let {selectData} = this.state;
    for(var i = 0; i < selectData.length; i++) {
      if (selectData[i].code === code) {
        return selectData[i].descripts;
      }
    }
  }

  // 保存
  handleSave = () => {
    let {leftTableData, userData, rowData} = this.state;
    this.props.form.validateFields((err, values) => {
      if (!err) {
        let filterArr = this.filterQuoteTableData(leftTableData);
        let data = {
          params: [{
            ...values,
            eMRResourceRuleID: rowData&&rowData.eMRResourceRuleID ? rowData.eMRResourceRuleID : "",
            eMRResourceRuleAvailable: values.eMRResourceRuleAvailable ? "Y" : "N", // 是否生效
            eMRResourceRuleDesc: this.getDescriptionByCode(values.eMRResourceRuleDesc),
            updateUserID: userData&&userData.userID ? userData.userID : '',
            comTableIDs: filterArr
          }]
        }
        console.log(data)
        $http.post('urlDeault', this, {
          code: "06010081",
          data: data,
          success: (res) => {
            if (+res.errorCode === 0) {
              message.success(res.errorMessage);
              this.resetFields();
              this.getRightTableData();
            }
          }
        })
      }
    })
  }

  // 获取右侧表头数据
  getRightColumns = () => {
    const columns = [
      {
        title: '所属医院',
        dataIndex: 'hospDesc',
        align: "center"
      }, 
      {
        title: '所属科室',
        dataIndex: 'locDesc',
        align: "center"
      }, 
      {
        title: '规则代码',
        dataIndex: 'eMRResourceRuleCode',
        align: "center"
      }, 
      {
        title: '规则描述',
        dataIndex: 'eMRResourceRuleDesc',
        align: "center"
      }, 
      {
        title: '是否有效',
        dataIndex: 'eMRResourceRuleAvailable',
        align: "center",
        render(eMRResourceRuleAvailable){
					let config = {
						'Y': '是',
						'N': '否'
					}
					return config[eMRResourceRuleAvailable];
				}
      }, 
      {
			  title: '操作',
			  align: "center",
			  render: (text, record) => (
				<span>
          <Icon type="edit" style={{color: '#108EE9'}}></Icon>
				  <span className='span' onClick={(e) => this.handleCompile(record, e)}>编辑</span>
				  {/* 分割线 */}
				  <Divider type="vertical" />
					<Icon type="delete" style={{color: 'rgba(240,65,52,1)'}}></Icon>
				  <Popconfirm title="删除不可恢复，你确定要删除吗?" onCancel={this.handlePopconfirm} onClick={this.handlePopconfirm} onConfirm={() => this.handleDelete(record)} >
						<span className='span' style={{color: 'rgba(240,65,52,1)'}}>删除</span>
				  </Popconfirm>
				</span>
			  ),
			}
    ];
    this.setState({rightColumns: columns})
  }

  // 点击删除时阻止事件冒泡
  handlePopconfirm = (e) => {
    e.stopPropagation();
  };

  // 3.5.13.查询电子病历应用资源引用规则列表
  getRightTableData = () => {
    let data = {
      params: [{
        eMRResourceRuleID: "",
      }]
    }
    $http.post('urlDeault', this, {
      code: "06010079",
      data: data,
      success: (res) => {
        if (+res.errorCode === 0) {
          this.setState({rightTableData: res.result})
        }
      }
    })
  }

  // 编辑
  handleCompile = (record, e) => {
    console.log(record)
    e.stopPropagation();
    this.resetFields();
    let arr = record&&record.comTable ? JSON.parse(JSON.stringify(record.comTable)).map((item) => {
      return {
        isQuote: true,
        code: item.comTableCode,
        descripts: item.comTableDesc,
        id: item.comTableID
      }
    }) : [];
    this.setState({rowData: record}, () => {
      this.getLeftTableData(this.state.rowData.eMRResourceRuleCode, arr);
      this.getDepartmentInformation(this.state.rowData.hospID)
    })
  }

  // 3.5.12.删除电子病历引用资源引用规则
  handleDelete = (record) => {
    if (this.state.rowData&&this.state.rowData.eMRResourceRuleID === record.eMRResourceRuleID) {
      this.resetFields();
    }
    let data = {
      params: [{
        eMRResourceRuleID: record.eMRResourceRuleID,
      }]
    }
    $http.post('urlDeault', this, {
      code: "06010080",
      data: data,
      success: (res) => {
        if (+res.errorCode === 0) {
          message.success(res.errorMessage);
          this.getRightTableData();
        }
      }
    })
  }

  //获取所属医院
	loadHospitalMsg() {
    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({
						hospitalData: res.depDoctor,
          })
          if (userData&&userData.hospID) {
            // this.props.form.setFieldsValue({
            //   hospID: userData.hospID
            // });
            this.getDepartmentInformation(userData.hospID);
          }
				}
			}
		});
  }
  
	// 3.13.23.获取科室信息
	getDepartmentInformation(id) {
		if (id) {
			let data = {
				params: [
					{ hospID: id}
				]
			}
			$http.post('urlS', this, {
				code: "04020008",
				data: data,
				success: function (res) {
					if (+res.errorCode === 0) {
						this.setState({ departmentInformation: res.result.Data})
					} else {
						this.setState({ departmentInformation: [] })
					}
				}
			})
		} else {
			this.setState({ departmentInformation: [] })
		}
  }
  
  // 选择医院查询科室
  handleHospIDChange = e => {
    this.props.form.setFieldsValue({
      locID: undefined
    });
    this.getDepartmentInformation(e);
  }

	onFocusLocDesc = () => {
    let hospID = this.props.form.getFieldValue("hospID");
		if (!hospID) {
			message.info("请先选择所属医院");
		}
	}
		
  // 重置表单
  resetFields = () => {
    this.setState({rowData: {}, leftTableData: [], selectedRowKeys: []});
    this.props.form.resetFields();
  }

  render() {
    let {selectData, leftTableData, leftColumns, selectedRowKeys, rightColumns, rightTableData, rowData, hospitalData, departmentInformation, userData} = this.state;
    const { getFieldDecorator } = this.props.form;
    
		const rowSelection = {
			selectedRowKeys: selectedRowKeys,
			onChange: (selectedRowKeys, selectedRows) => {
        this.setState({selectedRowKeys: selectedRowKeys})
			}
    };

    // 名称
    let nameOption = selectData&&selectData.map((item, index) => {
      return (<Option key={index} value={item.code} title={item.descripts} seatchprop={item.descripts}>{item.descripts}</Option>)
    })

    // 医院
    let hospOption = hospitalData&&hospitalData.map((item, index) => {
      return (<Option key={item.id} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
    })

    // 科室
    let locOption = departmentInformation&&departmentInformation.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="order-reference-rule">
         <div style={{padding: "8px 24px"}}>
          <Form className="form-flex">
            <Form.Item label="所属医院：" className="rules-position">
              {getFieldDecorator('hospID', {
                initialValue: rowData.hospID ? rowData.hospID : "",
                // rules: [{ required: true, message: '所属医院不能为空' }]
              })(
                <Select style={{width: "150px"}} showSearch disabled={rowData&&(rowData.hospID === "") ? true : false}
                  optionFilterProp="seatchprop" allowClear placeholder="请选择" onChange={this.handleHospIDChange}
                >
                  {hospOption}
                </Select>
              )}
            </Form.Item>
            <Form.Item label="科室名称：" className="rules-position">
              {getFieldDecorator('locID', {
                initialValue: rowData.locID ? rowData.locID : "",
                // rules: [{ required: true, message: '科室名称不能为空' }]
              })(
                <Select style={{width: "150px"}} showSearch disabled={rowData&&(rowData.hospID === "") ? true : false}
                  optionFilterProp="seatchprop" allowClear placeholder="请选择" onFocus={this.onFocusLocDesc}
                >
                  {locOption}
                </Select>
              )}
            </Form.Item>
            <Form.Item label="名称：" className="rules-position">
              {getFieldDecorator('eMRResourceRuleDesc', {
                initialValue: rowData.eMRResourceRuleCode ? rowData.eMRResourceRuleCode : undefined,
                rules: [{ required: true, message: '名称不能为空' }]
              })(
                <Select style={{width: "150px"}} disabled={rowData&&rowData.eMRResourceRuleID ? true : false} showSearch 
                  optionFilterProp="seatchprop" allowClear placeholder="请选择" onChange={this.handleNameIDChange}
                >
                  {nameOption}
                </Select>
              )}
            </Form.Item>
            <Form.Item label="代码：" className="rules-position">
              {getFieldDecorator('eMRResourceRuleCode', {
                initialValue: rowData.eMRResourceRuleCode ? rowData.eMRResourceRuleCode : "",
              })(
                <Input style={{width: "150px"}} placeholder="请输入" disabled />
              )}
            </Form.Item>
            <Form.Item label="是否生效：" className="rules-position">
              {getFieldDecorator('eMRResourceRuleAvailable', {
                valuePropName: 'checked',
                initialValue: rowData.eMRResourceRuleAvailable === "N" ? false : true,
              })(
                <Switch checkedChildren="是" unCheckedChildren="否" />
              )}
            </Form.Item>
            <Button type="primary" style={{margin: '0 12px 0 20px'}} onClick={this.handleSave}>保存</Button>
            <Button onClick={this.resetFields}>重置</Button>
          </Form>
        </div>
        <div style={{height: '6px', background: 'rgba(240, 242, 245, 1)', width: '100%'}}></div>
        <div style={{height: "calc(100% - 62px)", overflow: "auto"}}>
          <Row style={{height: '100%'}}>
            <Col span={12} style={{height: '100%'}}>
              <div 
                tabIndex={1}
                onKeyDown={this.handleOnKeydown}
                style={{outline: 'none', paddingRight: '6px', position: 'relative', height: '100%'}}
              >
                <Card
                  size="small"
                  title={<div className="card-title-left-icon">
                    <div></div>
                    引用规则维护
                    <div style={{float: "right"}}>
                      <span style={{cursor: "pointer"}} onClick={this.handleUp}>上移</span>
                      <Divider type="vertical" />
                      <span style={{cursor: "pointer"}} onClick={this.handleDown}>下移</span>
                    </div>
                  </div>}
                >
                  <Table
                    style={{minHeight: "230px"}}
                    rowSelection={rowSelection}
                    columns={leftColumns}
                    dataSource={leftTableData}
                    bordered
                    pagination={false}
                  />
                </Card>
                <div style={{width: '6px', background: 'rgba(240, 242, 245, 1)', position: 'absolute', top: 0, right: 0, height: '100%'}}></div>
              </div>
            </Col>
            <Col span={12}>
              <Card
                size="small"
                title={<div className="card-title-left-icon">
                  <div></div>
                  引用规则列表
                </div>}
              >
                <Table
                  style={{minHeight: "230px"}}
                  columns={rightColumns}
                  dataSource={rightTableData}
                  bordered
                  pagination={false}
                />
              </Card>
            </Col>
          </Row>
        </div>
      </div>
    )
  }
};
const OrderReferenceRuleForm = Form.create()(OrderReferenceRule);
export default OrderReferenceRuleForm;