//会诊医嘱项配置
import React from 'react';
import { Card, Row, Col, Icon, Table, Button, Select, Input, message, Pagination,Switch,Divider,Popconfirm } from 'antd';
import { $http } from 'containers/config/https';
import { Util } from '../../tools';
import './style/style.less';
import store from 'store';
import CommonPagination from 'components/pagination/index';

const Option = Select.Option;
let timeout;
let user;
export default class NeedAtentiontable extends React.Component {
    cacheOriginData = {};
    constructor(props) {
        super(props);
        user= window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        this.state = {
            size:'small',
            data: [],//列表数据
            index: '',
            ordDr:'',
            hospID : user.hospID,
            conCreatType:'',
            // 所属医院
            hospitalId: undefined,
            // 科室名称
            locDesc: undefined,
            DepartmentInformation: [], // 科室名称下拉框
            selectData:[],//会诊类型下拉框数据
            CreatTypeData:[],//生成方式下拉框数据
            medData:[],
            hospitalData : [],
            doctorTypeId:'',
            doctorTypeData:[],//医生职称下拉框数据
            loading: false,
            total: 0,//分页数据
            page: 1,
            pageSize: 10,
        }        
       };
       initData () {
        const auditFlag = this.props.flag;
        let columnTitle;
        if (auditFlag === "R") {
          columnTitle = ["是否显示", "启用"];
        } else {
          columnTitle = ["启用", "启用"];
        }
        this.columns = [
            {
                key: 'locID',
                title: '会诊科室',
                dataIndex: 'locID',
                align: "center",
                width: '10%',
                render: (text, record,index) =>
                {
                    if(record.editable){
                   
                        return (
                          <Select style={{ width: 200 }}  showSearch optionFilterProp="title" allowClear value={record.locID} onChange={this.onSelectChange.bind(this,index,"locID")} onFocus={this.onFocusLocDesc}  placeholder="请选择科室名称">
                          {this.state.DepartmentInformation && this.state.DepartmentInformation.map(item => {
                            return <Option key={item.id} value={item.id} title={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>
                          })}
                        </Select>
                          )
                    }
                    return record.locDesc;
                }
            },
            {
                key: 'medID',
                title: '会诊医嘱 ',
                dataIndex: 'medID',
                align: "center",
                width: '10%',
                render: (text, record,index) => {
                    if(record.editable){
                        return (
                            <Select style={{ width: 200 }} 	
                            allowClear
                            showSearch
                            placeholder='请输入医嘱信息检索'
                            optionFilterProp="title" 
                             value={this.state.medData.length===0?record.medDesc:record.medID}
                             onChange={this.onSelectChange.bind(this,index,"medID")}
                             onSearch={this.handleSerach}>
                             {
                                    this.state.medData.map(
                                        (item)=>{
                                            return <Option key={item.id} value={item.id} title={item.descripts + "^"+item.descriptsSPCode}>{item.descripts}</Option>
                                        }
                                    )

                            }
                          </Select>
                        )
                    }
                    return record.medDesc;
                    }
            },
            {
                key: 'conHospTypeID',
                title: '会诊类型',
                dataIndex: 'conHospTypeID',
                align: "center",
                width: '10%',
                render: (text, record, index) => {
                    if(record.editable){
                      return (
                        <Select style={{ width: 200 }} allowClear value={record.conHospTypeID}  onChange={this.onSelectChange.bind(this,index,"conHospTypeID")}>
                        {
                          this.state.selectData.conHospType.map((item) => {
                            return (
                              <Option key={item.id} value={item.id + ""} title={item.descspell} >{item.descripts}</Option>
                            )
                          })
                        }
                      </Select>
                      )
                    }
                    return record.conHospType;
                  },
            },
            {
                key: 'titleID',
                title: '医生职称',
                dataIndex: 'titleID',
                align: "center",
                width: '10%',
                render: (text ,record,index) => {
                    if (record.editable) {
                      
                        return (
                            <Select style={{ width: 200 }} allowClear value={record.titleID} onChange={this.onSelectChange.bind(this,index,"titleID")}>
                            {
                              this.state.selectData.title.map((item) => {
                                return (
                                  <Option key={item.id} value={item.id + ""} title={item.descspell} >{item.descripts}</Option>
                                )
                              })
                            }
                          </Select>
                        )
                    }
                    return record.titleDesc;
                  }
            },
            {
              title: '所属医院',
              dataIndex: 'hospID',
              key: 'hospID',
              width: '10%',
              align: 'center',
              render: (text ,record,index) => {
                if (record.editable) {
                    return (
                      <Select style={{ width: 200 }} allowClear onChange={this.onSelectChange.bind(this,index,'hospID')}>
                        {
                          this.state.hospitalData.map((item) => {
                            return (
                              <Option key={item.id} value={item.id + ""} title={item.descspell} >{item.descripts}</Option>
                            )
                          })
                        }
                      </Select>
                    )
                }
                return record.hospDesc;
              }
            },
            {
                key: 'conCreatTypeID',
                title: '生成方式',
                dataIndex: 'conCreatTypeID',
                align: "center",
                width: '10%',
                render: (text,record,index) => {
                    if (record.editable) {
                      
                        return (
                          <Select style={{ width: 200 }}  allowClear value={record.conCreatTypeID} onChange={this.onSelectChange.bind(this,index,"conCreatTypeID")}>
                          {
                            this.state.selectData.conCreatType.map((item) => {
                              return (
                                <Option key={item.id} value={item.id + ""} title={item.descspell} >{item.descripts}</Option>
                              )
                            })
                          }
                        </Select>
                        )
                    }
                    return record.conCreatType;
                  }
            },
            {
              key: 'conMedStatus',
              //title: '启用',
              title: columnTitle[0],
              dataIndex: 'conMedStatus',
              align: "center",
              width: '130px',
              render: (text, record, index) => {
                if (record.editable) {
                  return (
                    <Switch
                      onClick={this.handleStopPropagation}
                      defaultChecked={(record.conMedStatus == 'N' || record.conMedStatus == '未启用') ? false : true}
                      onChange={(val, e) => this.handleSwitchChange(val, e, 'conMedStatus', record)}
                    // onChange={(e) => this.handleSwitchChange1(e,'conDictItemStatus',record)}
                    />
                  )
                }
                return text;
              }
            },
            {
                title: '操作',          
                dataIndex: 'operation',
                key:'action',
                width: '130px',
                align: "center",
                render: (text, record, index) => {
                  const { loading } = this.state;
                  if(!!record.editable && loading){
                    return null;
                  }
                  if (record.editable) {
                    if (record.isNew) {
                      return (
                        <span>
                            <a onClick={(e) => this.saveRow(e,record.key,"C")}>添加(公共)</a>
                            <Divider type="vertical"/>
                            <a onClick={(e) => this.saveRow(e,record.key,"H")}>添加</a>
                            <Divider type="vertical"/>
                                <a onClick={() => this.cut(record.key)}>删除</a>
                        </span>
                      )
                    }
                    if (record.hospID){
                        return (
                          <span>
                            <a onClick={(e) => this.saveNewRow(e,record,"H")}>保存</a>
                            <Divider type="vertical"/>
                            <a onClick={(e) => this.cancel(e,record)}>取消</a>
                        </span>
                        )
                    }
                    return (
                        <span>
                          <a onClick={(e) => this.saveNewRow(e,record,"C")}>保存(公共)</a>
                          <Divider type="vertical"/>
                          <a onClick={(e) => this.saveNewRow(e,record,"H")}>保存</a>
                          <Divider type="vertical"/>
                          <a onClick={(e) => this.cancel(e,record)}>取消</a>
                        </span>
                      )
                  } 
                  return (
                    <span>
                      <a onClick={(e) => this.toggleEditable(e, record)}>编辑</a>
                      <Divider type="vertical"/>
                      <Popconfirm title="是否要删除此行" onConfirm={() => this.remove(record.conMedID)}>
                        <a>删除</a>
                      </Popconfirm>
                    </span>
                  )
                },
              }];
    }
    componentDidMount() {
        // 初始化设置table的高度以及表体的高度
        document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y + 'px';
        this.handleQuery();
        // 初始化数据
        this.initData();
        this.getHospital();
        this.getAdviceType();
        // this.doctorTypeList();
        // this.getAdviceShe();
        // this.GetMedItem();
        var box = document.querySelector(".department-header");
        if(box){ //此处在加一层判断，更加严密，如果box存在的情况下获取
          this.setState({headerHeight: box.offsetHeight})
        }
   
    }
     
       //医嘱项下拉框
    handleChange = (id)=>{
        this.state.medData.forEach((item)=>{
            if(item.id==id){
                    this.setState({
                    ordDr:item.id,
                
                })
            }
        })
    
    }
  //  // 查询条件 --- 科室名称
	// onChangeLocDesc = (e) => {
	// 	this.setState({ locID: e });
	// }
  onFocusLocDesc = () => {
		if (this.state.hospitalId === undefined) {
			message.info("请先选择所属医院");
		}
	}

    // 阻止默认事件
  handleStopPropagation = (e) => {
    if (typeof e == 'object') {
      e.stopPropagation();
    }
  }
     //获取下拉框数据
     GetMedItem=(value,callback)=>{
      //  console.log(user.hospID);
        if (timeout) {
            clearTimeout(timeout);
            timeout = null;
        }
        function getMedItemData(){
                if(value===""){
                    this.setState({ medData:[]})
                    return 
                }
                let data = {
                    params: [{
                        hospID:user.hospID,
                        findCode:value,
                        // detailFlag:"1"
                    }]
                }
                $http.post('urlS', this, {
                    code: "01010002",
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            callback(res.result.Data)

                        } 
                    }
                })
            }
            timeout = setTimeout(getMedItemData, 1000);
  }
  handleSerach=(value)=>{
        var reg = /\s/g;
        if(reg.test(value)) {
            message.error('不能输入空字符')
            return 
        }
         this.GetMedItem(value,data => this.setState({ medData:data}))
    
 } 
  handleSwitchChange = (val, e, el, record) => {
    this.handleStopPropagation(e)
    record[el] = val ? "Y" : "N";
    this.forceUpdate();
  }
   
    		//获取所属医院
    getHospital () {
		var data = {
			params: [{
				hospID: '', // 医院id
				logonGroupID: user.groupID, //登录角色id
				logonHospID: user.hospID, // 登录医院id
			}]
		}
		$http.post('urlS', this, {
			code: "01040001",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					this.setState({
						hospitalData: res.result,
						// hospitalId: res.depDoctor ? res.depDoctor[0].id : undefined
					})
					var result = res.depDoctor && res.depDoctor.some(item => {
						if (item.id === user.hospID) {
								return true
						}
					})
					if (!result) {
						this.setState({
								hospitalId: undefined
						})
					} else {
						this.setState({hospitalId: user.hospID ? user.hospID : undefined})
						this.getDepartmentInformation(user.hospID)
					}
				}
			}
		});
	}

  // 获取下拉框数据
  getAdviceType() {
		let data = {
			params: [
				{
          hospID:user.hospID,
          locID: user.locID,
          groupID:user.groupID,
          userID: user.userID,
          type: 'apply'
				}
			]
		}
		$http.post('urlS', this, {
			code: "04090011",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					this.setState({ selectData: res.result })
				} else {
					this.setState({ selectData: {} })
				}
			}
		})
	}



         //查询
         handleQuery = () => {
            let { page, pageSize} = this.state;
            let data = {
                params: [{
                    hospID:user.hospID,
                    power: "list",
                }],
                pagination: [{
                    pageSize: pageSize,
                    currentPage: page,
                    sortColumn: 'code',
                    sortOrder: 'asc'
                }]
            }
            $http.post('urlS', this, {
                code: "04090008",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                      // console.log(res)
                      // res.result.Data.map((item,i)=>{
                      //   res.result.Data[i].key = res.result.Data[i].conDictID;
                      //   })
                        this.setState({ data: res.result.Data, total: res.result.TotalCount, loading: false })
                    } else {
                        message.error('查询失败：' + res.errorMessage);
                    }
                }
            })
        }
 
       //新增
    newMember = () => {
        //debugger
        const { data } = this.state;
        const newData = data.map( (item) => ({...item}));
        newData.push({
          key: `NEW_TEMP_ID_${this.state.index}`,
          hospID:user.hospID,
          locID:'',
          conHospType:'',
          conMedStatus:'N',
          conCreatType:'',
          medID:'',
          titleID:'',
          editable : true,
          isNew : true,
        });
        this.setState({ 
            data : newData,
            index: this.state.index + 1,
          });
      }
           //新增
    saveRow(e, key , rank){
        e.persist();
        let data = {
            params : []
        };
        const target = this.getRowByKey(key) || {};
        if(!target.medID || !target.conCreatTypeID ) {
          e.target.focus();
          this.setState(
            {loading : false,}
          )
          message.error('请填写完整配置信息');
          target.hospID = ""
          target.isNew = true;
          return;
        }

        delete target.isNew;
        let obj = JSON.parse(JSON.stringify(target));
        obj.type ='insert';
        obj.updateUserID = user.userID;
        if (rank === "C") {
          obj.hospID = "";
          // obj.locID = "";
        }
        obj.saveType = rank;
        data.params.push(Util.disposeData(obj));
        $http.post('urlADS', this, {
          code: '04090007',
          data: data,
          success : function(res){
            if (+res.errorCode === 0) {
              message.success('新增成功');
              this.handleQuery();
            }else{
              
            }
            
          }
        });
      }
     //更新
     saveNewRow =(e,record,rank) =>{
      // console.log(e,record,rank)
        e.persist();
        //debugger
        let data = {
          params : []
        }; 
        if(!record.medID || !record.conCreatType ) {
         // message.error('请填写完整配置信息');
          e.target.focus();
          this.setState(
            {loading : false,}
          )
        }
        let obj = JSON.parse(JSON.stringify(record));
        obj.type = "update";
        obj.conMedID = record.conMedID;
        obj.updateUserID = user.userID;
        if (rank === "C") {obj.hospID = "";}
        obj.saveType = rank;
        data.params.push(Util.disposeData(obj));
        $http.post('urlADS', this, {
          code: '04090007',
          data: data,
          success : function(res){
            if (+res.errorCode === 0) {
              message.success('更新成功');   
            }
            this.handleQuery();
          }
        });
      }
       

    //下拉框数据修改
    onSelectChange(index, fieldName, value ){ 
        //let fieldName = "hospID" ;
        let {data}=this.state;
        data[index][fieldName] = value;
        this.setState({ data: data });
    }

      
    	// 查询条件 --- 所属医院
	onChangehospitalId = (e) => {
		// console.log(e.target.value)
		this.setState({ hospitalId: e, locDesc: undefined }, () => {
			this.getDepartmentInformation(e)
		}, () =>{
      this.getAdviceType();
      this.doctorTypeList();
      this.getAdviceShe();
      this.handleQuery();
    });
	}
	// 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: [] })
		}
	}
  
      //取消
      cancel(e, record){
        e.preventDefault();
        record.editable=false;
        this.forceUpdate();
      } 
      //获取操作行数据对象
      getRowByKey(key, newData) {
        const { data, } = this.state;
        return (newData || data).filter(item => item.key === key)[0];
      }
        //添加-删除
    cut(key){
        const { data } = this.state;
        const { onChange } = this.props;
        const newData = data.filter(item => item.key !== key);
        this.setState({ data: newData });
        // onChange(newData);
      }
      
      //编辑
    toggleEditable = (e , record) => {
        e.preventDefault();
        record.editable=!record.editable;
        this.forceUpdate();
      }
 
      //删除
    remove(id){
        // debugger
        if (id === "") {
          message.success('请选中删除行');
          return;
        }
        let tempObj = {};
        tempObj.conMedID=id;
        tempObj.updateUserID = user.userID;
        let obj = JSON.parse(JSON.stringify(tempObj));
        let data = {
          params : []
        };
        data.params.push(Util.disposeData(obj));
        $http.post('urlADS',this,{
          code : '04090009',
          data : data,
          success : function(res){
            if (+res.errorCode === 0) {
              message.success('删除成功');
              this.handleQuery();
            }
          },
        });
      }
      // 页码改变的回调，参数是改变后的页码及每页条数 需关注医嘱
      onChange = (page, pageSize) => {
        this.setState({ page: page, pageSize: pageSize }, () => {
            // 重新调用查询方法
           this.handleQuery();
        });
    };

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

    render (){
        return(
          <div style={{ width: '100%', height: '100%',overflow:'hidden'}}>
					<div className="department-header">
						<Row style={{ minHeight: '80px', padding: '24 24px' }}>
							<Col span={24} style={{marginLeft:'20px'}}>
                  <Select style={{ width: 300 }} showSearch optionFilterProp="title" allowClear allowClear value={this.state.hospitalId} onChange={this.onChangehospitalId}  placeholder="请选择所属医院">
											{this.state.hospitalData && this.state.hospitalData.map(item => {
												return <Option key={item.id} value={item.id} title={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>
											})}
										</Select>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        
                    <Button  style={{marginTop:'20px',marginLeft:'10px'}} type="primary" onClick={this.newMember}>新增</Button>&nbsp;&nbsp;
                                           
							</Col>
						</Row>
					</div>
					<div style={{ width: '100%', height: '10px', background: '#f0f2f5' }}></div>
					<div style={{ padding: 24 }}>
            <Table
                    style={{ width: '100%',height: '710px' }}
                    dataSource={this.state.data}
                    columns={this.columns}
                    pagination={false}
                    rowKey={(row) => {
                        return row.conMedID
                    }}
                    //onRow={this.onClickRow}
                    rowClassName={record => (record.editable ? 'record' : '')}
                    loading={this.state.loading}
                    bordered
                />
                  <CommonPagination
                  size={this.state.size} 
                  current={this.state.page}
                  total={this.state.total} 
                  search={this.state.search}
                  onShowSizeChange={this.onShowSizeChange.bind(this)} 
                  complete={true}
                  dataSource={this.state.data}
                  loading={this.state.loading} onChange={this.onChange.bind(this)} />
                      
				  	</div>

				</div>
         
        )
    }
}