// 门诊配药
import React from 'react';
import { Card, Row, Col, Select, Button, Input, DatePicker, Switch, Modal, Table, Checkbox, Icon, Form, message } from 'antd';
import store from 'store';
import { $http } from 'containers/config/https';
import CommonPagination from 'components/pagination/index';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import Moment from 'moment';
import './style/outpha.less';
import {$PrintLabel, $PrintPresc, $PrintPYD} from "./common/Print";

const { Option } = Select;
let autoamticTimer = null;
let autoamticTimeP = null;
let timer = null;

class Dispensing extends React.Component {

    constructor(props) {
        super(props);
        var userData = JSON.parse(sessionStorage.getItem('userData'));
        this.state = {
            userInfo: JSON.parse(window.sessionStorage.userData),
            windowDomData: [],
            windowVisible: true, //显示窗口
            cardSlectData:[], //下拉
            detailData: [],
            radioWindowData: {},
            pageSize: 20,
            page: 1,
            total:0,
            loading:false,
            patID: '', // 病人Id
            pat: '', // 回车保存的病人id
            patNo: undefined, // 病人
            cardType: undefined, // 卡类型
            cardNo: undefined, // 卡号
            defaultValue: '', // 默认卡类型
            dispRecFlag: false,
            prescNo: '',//行处方号
            detailsListData: [], //药品详情列表
            outpatientID: '', //配药id
            whether: false,
            buttonStatus: 'end',//自动配药识别
            initData: {}, //自动配药秒数
            selectpharmacy: false,
            determineSelect: false,
            modalColumns: [], //表头数据
            listLength: '', //长度
            topLength: '',
            Columns: [],
            parameterCode: '',
            selectAllData: [],//选中的配药列表数据
            selectedRowKeys:[],
            DispensingFlag:null,//根据查询状态显示配药按钮
            dispID: '',//配药列表id
            mainInfo:{},
            usageData: [], //Rp数据
            leftID:'',
            shortKey: '', //快捷键配药
            authorityStatus:false,
            userData:userData,
            autoDispensingFlag:'',//配置是否一进来就启动自动配药
        };
        this.columns = [
            { title: '配药状态', dataIndex: 'prepFlag', key: '1', width: '100px', align: "center"},
            { title: '收费日期', dataIndex: 'payDate', key: '2', width: '100px', align: "center"},
            { title: '登记号', dataIndex: 'patNo', key: '3', width: '100px', align: "center"},
            { title: '处方', dataIndex: 'prescNo', key: '4', width: '100px', align: "center"},
            { title: '姓名', dataIndex: 'patName', key: '5', width: '100px', align: "center"},
            { title: '性别', dataIndex: 'patSex', key: '6', width: '100px', align: "center"},
            { title: '年龄', dataIndex: 'age', key: '7', width: '100px', align: "center"},
            { title: '收据号', dataIndex: 'dateTime', key: '8', width: '100px', align: "center"},
            { title: '处方金额', dataIndex: 'preAmt', key: '9', width: '100px', align: "center"},
            { title: '费别', dataIndex: 'admReason', key: '10', width: '100px', align: "center"},
            { title: '发药窗口', dataIndex: 'dispWin', key: '11', width: '100px', align: "center"},
            { title: '科室', dataIndex: 'loc', key: '12', width: '100px', align: "center"},
            { title: '取号', dataIndex: 'dateTime', key: '13', width: '100px', align: "center"},
            { title: '发药机', dataIndex: 'dateTime', key: '14', width: '100px', align: "center"},
            { title: '剂数', dataIndex: 'dateTime', key: '15', width: '100px', align: "center"},
            { title: '煎药类型', dataIndex: 'dateTime', key: '16', width: '100px', align: "center"},
            { title: '电话', dataIndex: 'mobile', key: '17', width: '100px', align: "center"},
            { title: '诊断', dataIndex: 'admDiag', key: '18', width: '100px', align: "center"},
        ];
        this.detailColumns = [
            { title: '药品名称', dataIndex: 'ordMedDesc', key: '1', width: '100px', align: "center"},
            { title: '数量', dataIndex: 'qty', key: '2', width: '100px', align: "center"},
            { title: '单位', dataIndex: 'baseUnitDesc', key: '3', width: '100px', align: "center"},
            { title: '用法', dataIndex: 'ordUsageDesc', key: '4', width: '100px', align: "center"},
            { title: '剂量', dataIndex: 'ordDoseUnitDesc', key: '5', width: '100px', align: "center"},
            { title: '频次', dataIndex: 'ordFreqDesc', key: '6', width: '100px', align: "center"},
            { title: '疗程', dataIndex: 'ordDurationDesc', key: '7', width: '100px', align: "center"},
            { title: '单价', dataIndex: 'sp', key: '8', width: '100px', align: "center"},
            { title: '金额', dataIndex: 'spAmt', key: '9', width: '100px', align: "center"},
            { title: '状态', dataIndex: 'ordStatus', key: '10', width: '100px', align: "center"},
            { title: '医师', dataIndex: 'ordDoctor', key: '11', width: '100px', align: "center"},
            { title: '产地', dataIndex: 'manfDesc', key: '12', width: '100px', align: "center"},
            { title: '货位', dataIndex: 'stockBin', key: '15', width: '100px', align: "center"},
        ];
        this.myRef1 = React.createRef();
    }

    componentDidMount() {
        let topList = document.querySelectorAll('.table-scroll-height  .ant-table-body');
        if(topList.length>0){
            topList[0].style.height = store.getState().tableHeight.y+82 + 'px';
        }
        let bottomList = document.querySelectorAll('.table-detail-height  .ant-table-body');
        if(bottomList.length>0){
            bottomList[0].style.height = store.getState().tableHeight.y+82 + 'px';
        }
        this.getPharmacyWindowData();
        this.getCardSelectData();
        window.addEventListener('beforeunload', this.beforeunload);
        this.getDetailListTableColumns();
        this.getListTableColumns();
        window.addEventListener("keydown", this.onKeyDown)
    }

    componentWillUnmount() {
        // 组件销毁前将静止让setState修改state的状态
        clearInterval(autoamticTimer);
        clearInterval(autoamticTimeP);
        this.setState = (state,callback)=>{ return; }
        window.removeEventListener('beforeunload', this.beforeunload);
        window.removeEventListener("keydown", this.onKeyDown)
    }

    //判断医生有没有审核权限
    authorityManagement=()=>{
        let data = {
            params: [{
                userID:this.state.userData.userID,
                locID:this.state.userData.locID,
                authDesc:'PrepAuth'
            }]
        }
        $http.post('urlS', this, {
            code: "02030082",
            data: data,
            success: function (res) {
                if (+res.errorCode == '02010015' ) {
                    // message.error(res.errorMessage);
                    this.setState({authorityStatus: true})
                } else {
                    this.setState({authorityStatus: false})
                }
            }
        })
    };

    onKeyDown = (e) => {
        var keyCode = e.key;
        if(this.state.shortKey && keyCode && this.state.DispensingFlag == 0 ){
            if(keyCode == this.state.shortKey) {
                this.getOutpatient();
            }
        }
    };
    // 获取主列表头数据
    getListTableColumns = () => {
        let {userInfo} = this.state;
        let data = {
            params: [{
                compontName: 'OutpatientDispensing',
                type: 'C',
            }]
        }
        $http.post('urlS', this, {
            code: '01040073',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    let arr = res.result.C&&res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map((item, index) => {
                        return  {
                            ...item,
                            key: index + 1,
                            title: <div onDoubleClick={() => {this.setState({parameterCode: 'OutpatientDispensing'},()=>{
                                this.columnRef.onOpenModel();
                            })}}>{userInfo.language== 'EN' ? item.enDescripts : item.title}</div>
                        }
                    }) : '';
                    let filterArr = arr.filter(function(item){ return item.display === 'Y'});
                    this.setState({Columns: filterArr, topLength: res.totalWidth})
                }
            }
        })
    };

    // 获取明系列表头数据
    getDetailListTableColumns = () => {
        let {userInfo} = this.state;
        let data = {
            params: [{
                compontName: 'OutpatientDispensingDetail',
                type: 'C',
            }]
        }
        $http.post('urlS', this, {
            code: '01040073',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    let arr = res.result.C&&res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map((item, index) => {
                        return  {
                            ...item,
                            key: index + 1,
                            title: <div onDoubleClick={() => {this.setState({parameterCode: 'OutpatientDispensingDetail'},()=>{
                                this.columnRef.onOpenModel();
                            })}}>{userInfo.language== 'EN' ? item.enDescripts : item.title}</div>
                        }
                    }) : '';
                    let filterArr = arr.filter(function(item){ return item.display === 'Y'});
                    this.setState({modalColumns: filterArr, listLength: res.totalWidth})
                }
            }
        })
    };

    beforeunload = (event) => {
        if(this.state.buttonStatus == 'start') {
            //用户点击浏览器右上角关闭按钮或是按alt+F4关闭
            if(event.clientX>document.body.clientWidth&&event.clientY<0||event.altKey)
            {
                let confirmationMessage = '离开本页面自动配药将会停止! 是否要离开?';
                (event || window.event).returnValue = confirmationMessage;
                return confirmationMessage;
            }
            //用户点击任务栏，右键关闭。s或是按alt+F4关闭
            else if(event.clientY > document.body.clientHeight || event.altKey)
            {
                let confirmationMessage = '离开本页面自动配药将会停止! 是否要离开?';
                (event || window.event).returnValue = confirmationMessage;
                return confirmationMessage;
            }
            //其他情况为刷新
            else
            {
                let confirmationMessage = '刷新本页面自动配药将会停止! 是否要离开?';
                (event || window.event).returnValue = confirmationMessage;
                return confirmationMessage;
            }
        }
    }
    // 获取卡类型下拉框数据
    getCardSelectData = () => {
        let data = {
            params: [{}]
        }
        $http.post('urlS', this, {
            code: '02030052',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    let defaultValue = '';
                    for(var i = 0; i < res.result.length; i++) {
                        if (res.result[i].defaultFlag === 'Y') {
                            defaultValue = res.result[i].id;
                        }
                    }
                    this.setState({cardSlectData: res.result, cardType: defaultValue, defaultValue: defaultValue})
                }
            }
        });
        $http.post('urlS', this, {
            code: '02030073',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({parameterSetting: res, startDate: res.startDate, endDate: res.endDate, shortKey: res.shortKey,autoDispensingFlag:res.autoDispensingFlag});

                }
            }
        })
    }

    // 获取取药窗口信息
    getPharmacyWindowData = (flag) => {
        let data = {
            params: [],
        }
        $http.post('urlS', this, {
            code: "02030029",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({windowDomData: res.result[0].rows});
                }else {
                    this.setState({windowDomData: []});
                }
            }
        })
    }
// 关闭弹窗
    handleCancel = () => {
        this.setState({windowVisible:false})
    };
    // Checkbox的onChange事件
    compileChecked = (item, index) => {
        let windowDomData = [...this.state.windowDomData];
        for(var i = 0; i < windowDomData.length; i++) {
            let indexChecked = windowDomData[index].checked;
            windowDomData[i].checked = false;
            windowDomData[index].checked = indexChecked;
            if (windowDomData[i] === item) {
                windowDomData[i].checked = !windowDomData[i].checked;
            }
        }
        this.setState({windowDomData: windowDomData,radioWindowData:item,selectpharmacy:item.checked},()=>{
            if(!this.state.selectpharmacy){
                this.setState({determineSelect: false})
            }
        })
    };

    // 切换窗口 --- 确定
    windowHandleOk = () => {
        if(this.state.selectpharmacy){
            this.getOutpatientDetailList();
            this.setState({windowVisible: false,determineSelect: true});
            this.myRef1.current.focus();
            let secondTime = this.state.initData.RefreshTime ? (this.state.initData.RefreshTime)*1000 : 5000;
            autoamticTimeP =  setInterval(() => {
                this.getOutpatientDetailList();
            }, secondTime);
            this.authorityManagement();
            if(this.state.autoDispensingFlag=='Y'){
                this.setState({whether: true},()=>{
                    this.automaticOutpatient();
                });

            }
        }else {
            message.error('请选择配药窗口')
        }
    };
    // 查询配药列表
    getOutpatientList = (id) => {
        if(!id){
            this.setState({leftID: ''})
        }
        if(!this.state.radioWindowData.prepWinID){
            message.error('请选择配药窗口');
            return
        }
        let { startDate, endDate, radioWindowData} = this.state;
        let data = {
            params: [
                {
                    prepWinID: radioWindowData&&radioWindowData.prepWinID ? radioWindowData.prepWinID : undefined, // 发药窗口ID
                    startDate: startDate ? Moment(startDate).format('YYYY-MM-DD') : Moment().format('YYYY-MM-DD'), // 开始日期
                    endDate: endDate ? Moment(endDate).format('YYYY-MM-DD') : Moment().format('YYYY-MM-DD'), // 截止日期
                    patID: id ? id : this.state.patID ,
                    dispRecFlag:this.state.dispRecFlag,
                }
            ],
            pagination: [
                {
                    pageSize:this.state.pageSize,
                    currentPage:this.state.page,
                    sort:"ID",
                    dir:"asc",
                }
            ]
        }
        $http.post('urlS', this, {
            code: "02030070",
            data: data,
            success: function (res) {
                let arr = [];
                if (+res.errorCode === 0 && res.rows && res.rows.length>0) {
                    for (var i = 0; i < res.rows.length; i++) {
                        res.rows[i].key = i+1;
                        arr[i] = i+1;
                    }
                    this.setState({detailData: res.rows,total: res.total, selectedRowKeys: arr, selectAllData: res.rows,DispensingFlag: res.dispRecFlag, patNo: '',patID: '',prescNo: res.rows[0].prescNo,dispID: res.rows[0].id,outpatientID: res.rows[0].key},()=>{
                        this.getPrescriptionDetailList();
                    });
                }else {
                    this.setState({detailData:[],total: 0, selectedRowKeys: [],selectAllData:[],DispensingFlag:null,patID:'', patNo: '',mainInfo:{}});
                    message.error('没数据');
                }
            }
        })
    };
// 查询待配药列表
    getOutpatientDetailList = () => {
        let { startDate, endDate, radioWindowData} = this.state;
        let data = {
            params: [
                {
                    prepWinID: radioWindowData&&radioWindowData.prepWinID ? radioWindowData.prepWinID : undefined, // 发药窗口ID
                    startDate: startDate ? Moment(startDate).format('YYYY-MM-DD') : Moment().format('YYYY-MM-DD'), // 开始日期
                    endDate: endDate ? Moment(endDate).format('YYYY-MM-DD') : Moment().format('YYYY-MM-DD'), // 截止日期
                    patID: this.state.patID
                }
            ]
        }
        $http.post('urlS', this, {
            code: "02030074",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0 && res.rows) {
                    for (var i = 0; i < res.rows.length; i++) {
                        res.rows[i].key = i;
                    }
                    this.setState({detailsListData: res.rows})
                }else {
                    this.setState({detailsListData: []})
                    // message.error('没数据')
                }
            }
        })
    };
    // 配药
    getOutpatient = () => {
        if(this.state.selectAllData.length>0 ){
            let arr = this.state.selectAllData.map((item)=>{
                return {
                    prescNo:item.prescNo,
                    patNo: item.patNo
                }
            });
            let data = {
                params: arr.length>0 ? arr : ''
            }
            $http.post('urlS', this, {
                code: "02030071",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        message.success(res.errorMessage);
                        this.setState({patNo: '',patID: ''},()=>{
                            this.myRef1.current.focus();
                            this.getOutpatientList();
                        });
                    }
                }
            })
        }else {
            message.error('请选择配药信息')
        }

    };

    // 3.2.1.3.13.根据卡号取病人信息
    getPatientInformation = (flag) => {
        let data = {
            params: [{
                number: this.state.patNo, // 病人登记号/证件号
                cardTypeID: flag === 'readCard' ? this.state.cardType : undefined, // 卡类型id
                cardNo: this.state.cardNo, // 卡号
            }]
        }
        $http.post('urlS', this, {
            code: '03040004',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    let cardNo = flag === "readCard"&&res.data&&res.data.patCardNo ? res.data.patCardNo : undefined; // 给卡号赋值
                    this.setState({patID: res.data&&res.data.patID ? res.data.patID : '', cardNo: res.data.patCardNo, patNo: res.data.patNo},()=>{
                        this.getOutpatientList();
                    })
                }else if (res.errorFlag === 'N') {
                    this.setState({tableData: [], total: 0, patID: 'aaaaa', patNo: ''})
                    message.error(res.errorMessage)
                }
            }
        })
    };
    // 病人id
    handlePatientOnChange = (e) => {
        if (!e.target.value) {
            this.setState({patID: ''})
        }
        this.setState({patNo: e.target.value})
    };
    // 查询病人id
    handlePatient = (e, name) => {
        if (!e.target.value) {
            this.setState({patID: ''})
            return;
        }
        this.setState({cardNo: undefined, cardType: this.state.defaultValue}, () => {
            this.getPatientInformation('patient');
        })
    }

    handleReadCardOnBlur = (e) => {
        if (!e.target.value) {
            this.setState({patID: ''})
            return;
        }
        this.setState({patNo: undefined}, () => {
            this.getPatientInformation('readCard');
        })
    }
    // 获取表格数据
    handleQuery = () => {
        this.setState({ page: 1, pageSize: 10, rowId: '', prescNo: '', detailsListData: [], detailData: [],cardNo: '', patNo: '', dispRecFlag: false})
    };
    // 关闭弹窗
    handleCancel = () => {
        if(this.state.determineSelect){
            this.setState({
                windowVisible: false,
            });
        }

    };
    // 页码改变的回调，参数是改变后的页码及每页条数 采购单
    onChange = (page, pageSize) => {
        this.setState({page: page, pageSize: this.state.pageSize}, () => {
            // 重新调用查询方法
            this.getOutpatientList();
        });
    };

    onShowSizeChange = (current, size) => {
        this.setState({page: current, pageSize: size}, () => {
            // 重新调用查询方法
            this.onChange(current,size);
        })
    };
    switchingWindow=()=>{
        this.setState({windowVisible:true})
    };

    // 查询条件 --- 开始日期
    handleStartDate = (e) => {
        this.setState({ startDate: e });
    };

    // 查询条件 --- 截止日期
    handleEndDate = (e) => {
        this.setState({ endDate: e });
    };

    //是否配药
    onChangeDispRecFlag = (e) => {
        this.setState({ dispRecFlag: e.target.checked });
    };
    // 卡号
    handleCardNoChange = (e) => {
        if (!e.target.value) {
            this.setState({patID: ''})
        }
        this.setState({cardNo: e.target.value})
    };
    // 卡类型
    handleCardTypeOnChange = (e) => {
        this.setState({cardType: e})
    };
    filterDspInfo = (data) => {
        let rowsData = data[0].rows;
        let obj = {};
        let batInfo = [];
        let filterBatInfo = [];
        for(var i = 0; i < rowsData.length; i++) {
            batInfo = batInfo.concat(rowsData[i].batInfo)
        }
        for(var i = 0; i < batInfo.length; i++) {
            if (!obj[batInfo[i].batNo]) {
                obj[batInfo[i].batNo] = batInfo[i].batNo;
                filterBatInfo.push(batInfo[i]);
            } else {
                for(var j = 0; j < filterBatInfo.length; j++) {
                    if (filterBatInfo[j].batNo === batInfo[i].batNo) {
                        filterBatInfo[j].qty += batInfo[i].qty;
                    }
                }
            }
        }
        let dspInfo = [];
        rowsData[0].batInfo = filterBatInfo
        let batInfoObj = {
            rows: rowsData
        }
        dspInfo.push(batInfoObj);
        return dspInfo
    }

    //处方筏
    getPrescriptionDetailList=()=>{
        let data = {
            params: [{
                ordPrescNo:this.state.prescNo,
                dispID: this.state.dispID,
            }]
        }
        $http.post('urlS', this, {
            code: '02030040',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    let detailInfo = res.result[0] ? JSON.parse(JSON.stringify(res.result[0].detailInfo)) : [];
                    let usageData = detailInfo&&detailInfo.length > 0 ? JSON.parse(JSON.stringify(detailInfo[0].rows)) : [];
                    for (var i = 0; i < usageData.length; i++) {
                        usageData[i].visible = false;
                        usageData[i].filterDd = usageData[i].ordQty;
                        usageData[i].dspInfo = this.filterDspInfo(usageData[i].dspInfo)
                    }
                    this.setState({
                        mainInfo: res.result[0] ? res.result[0].mainInfo : [],
                        usageData: usageData,
                    })
                }
            }
        })
    };
    // 操作行 --- 左侧列表待发药
    onClickRowLeftTable = (record) => {
        return {
            // 单击行选中
            onClick: () => {
                if (this.state.outpatientID === '') {
                    // 保存行数据以及ID
                    this.setState({prescNo: record.prescNo, outpatientID: record.key, dispID: record.id}, () => {
                        this.getPrescriptionDetailList();
                    })
                } else {
                    if (this.state.outpatientID !== record.key) {
                        this.setState({prescNo: record.prescNo, outpatientID: record.key,dispID: record.id}, () => {
                            this.getPrescriptionDetailList();
                        })
                    }else {
                        this.setState({prescNo: '',  outpatientID: '',dispID: '',mainInfo:{},usageData:[]})
                    }
                }
            }
        }
    }

    // 选中行操作 --- 左侧列表
    setRowClassNameLeftTable = (record) => {
        return record.patID === this.state.leftID ? 'clickRowStyle' : '';
    };
    // 选中行操作 --- 左侧列表
    setRowClassNameTable = (record) => {
        return record.key === this.state.outpatientID ? 'clickRowStyle' : '';
    };
    //自动配药
    automaticOutpatient=()=>{
        if(this.state.whether){
            let secondTime = this.state.initData.RefreshTime ? (this.state.initData.RefreshTime)*1000 : 5000;
            this.automaticDispensingPort('outpatient');
            this.setState({buttonStatus:'start'})
            autoamticTimer =  setInterval(() => {
                this.automaticDispensingPort('outpatient');
            }, secondTime);
        }else {
            //结束自动配药
            clearInterval(autoamticTimer);
            this.setState({buttonStatus:'end'})
        }

    };
    automaticDispensingPort=(v)=>{
        if(this.state.radioWindowData.prepWinID){
            let data = {
                params: [
                    {
                        prepWinID: this.state.radioWindowData.prepWinID,
                    }
                ]
            }
            $http.post('urlS', this, {
                code: "02030031",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0 && res.result &&res.result[0]&& res.result[0].rows&&res.result[0].rows.length>0) {
                        this.handlePrintPresc(res.result[0]&&res.result[0].rows);
                    }else {
                        if(v == 'Manual'){
                            message.error('没有打印数据')
                        }
                    }
                }
            })
        }else {
            message.error('请选择配药窗口')
        }

    };

    // 打印已配药单
    handleReprint = () => {
        // if(this.state.DispensingFlag !==1 ){
        //     message.error('只能打印已配药单据');
        //     return
        // }
        // console.log('selectAllData',this.state.selectAllData);
        let arr = [];
        for(var i=0; i<this.state.selectAllData.length; i++){
            arr[i] =this.state.selectAllData[i].prescNo
        }
        if(this.state.DispensingFlag == 0){
            let data = {
                params: [
                    {
                        prescno: arr,
                    }
                ]
            }
            $http.post('urlS', this, {
                code: "02030076",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0 ) {
                        arr = [];
                    }else {
                        arr = [];
                    }
                }
            })
        }
        let {parameterSetting} = this.state;
        this.state.selectAllData&&JSON.parse(JSON.stringify(this.state.selectAllData)).map(item => {
            let params = {
                dispID:item.id,
                prescno:item.prescNo,
                phFlag:1,
            }
            if (parameterSetting.PrintLabel === '1') {
                $PrintLabel(params);
            }
            if (parameterSetting.PrintPYD === '1') {
                $PrintPYD(params);
            }
            if (parameterSetting.PrintPresc === '1') {
                $PrintPresc(params);
            }
        })
    }

    //打印处方
    handlePrintPresc = (notPrintData) => {
        let {parameterSetting} = this.state;
        if (!(notPrintData&&notPrintData.length > 0)) {
            return;
        }
        for (let i = 0; i < notPrintData.length; i++) {
            let params = {
                dispID:notPrintData[i].dispID,
                prescno:notPrintData[i].ordPrescNo,
                phFlag:1,
            }
            if (parameterSetting.PrintLabel === '1') {
                $PrintLabel(params);
            }
            if (parameterSetting.PrintPYD === '1') {
                $PrintPYD(params);
            }
            if (parameterSetting.PrintPresc === '1') {
                $PrintPresc(params);
            }
        }
    };
    //组件权限编辑器
    onColumnRef = (ref) => {
        this.columnRef = ref;
    };
    // 西药时需要处理关联医嘱
    processAssociatedData = (data) => {
        let tempArr = [];
        let afterData = [];
        if (!(data&&data.length > 0)) {
            return afterData;
        }
        for (let i = 0; i < data.length; i++) {
            if (tempArr.indexOf(data[i].ordMainID) === -1) {
                afterData.push({
                    ordMainID: data[i].ordMainID,
                    children: [data[i]]
                });
                tempArr.push(data[i].ordMainID);
            } else {
                for (let j = 0; j < afterData.length; j++) {
                    if (afterData[j].ordMainID == data[i].ordMainID) {
                        afterData[j].children.push(data[i]);
                        break;
                    }
                }
            }
        }
        // console.log(afterData);
        return afterData;
    };
    inciseData = () => {
        var {usageData} = this.state
        var result = [];
        for(var i = 0, len=usageData.length; i < len; i+=3){
            result.push(usageData.slice(i,i+3));
        }
        return result
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        let {windowDomData , windowVisible, cardSlectData, detailData, radioWindowData, patNo, detailsListData, modalColumns, listLength, topLength, Columns, mainInfo, usageData, userData} = this.state;
        let mainInfoObj = mainInfo&&mainInfo.length > 0 ? mainInfo[0] : {};
        let colTop = {
            xs: {span: 12},
            sm: {span: 12},
            md: {span: 10},
            lg: {span: 10},
            xl: {span: 10},
            xxl: {span: 10}
        };
        let colBottom = {
            xs: {span: 12},
            sm: {span: 12},
            md: {span: 14},
            lg: {span: 14},
            xl: {span: 14},
            xxl: {span: 14}
        }
        // 审核状态
        // let auditStatus = cardSlectData.a && cardSlectData.a.map((item, index) => {
        //     return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        // })
        // 卡类型
        let cardTypeOption = cardSlectData && cardSlectData.map((item, index) => {
            return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        })

        let windowDom = (
            windowDomData&&windowDomData.map((item, index) => {
                return (
                    <div key={index} style={{margin: (index + 1) % 5 == 0 ? '0 0 20px 0' : '0 20px 20px 0'}}>
                        <div className="check-box">
                            <div className="prep-win-desc" style={{background: item.checked ? '#1890FF' : '#69C0FF'}}>{item.prepWinDesc}</div>
                            <div className="presc-num" style={{color: item.checked ? '#1890FF' : '#69C0FF'}}>{item.prescNum}</div>
                            <span>
                                <Checkbox checked={item.checked} onChange={() => this.compileChecked(item, index)} />
                            </span>
                        </div>
                        {/*<Row className="check-row">*/}
                        {/*<Switch checkedChildren="有人" unCheckedChildren="无人" checked={item.statusID === 'O' ? true : false} onChange={(e) => this.handleSwitch(item, e)} />*/}
                        {/*</Row>*/}
                    </div>
                )
            })
        );
        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({selectAllData:selectedRows,selectedRowKeys});
            },
        };
        let medicalAdviceDom = (
            <div>
                <div style={{borderBottom: '1px solid #ccc'}}>
                    <h1 style={{textAlign: 'center', position: 'relative', fontSize: '24px', marginBottom: '24px'}}>
                        {mainInfoObj.hospName ? mainInfoObj.hospName : userData&&userData.hospDesc ? userData.hospDesc : ""}处方笺
                        <span style={{position: 'absolute', right: '10px', top: '10px', fontSize: '14px', fontWeight: 100, textAlign: 'right', color:'rgba(153,153,153,1)'}}>
                            <Row>{mainInfoObj.prescType}</Row>
                            {/*<Row>处方号：{mainInfoObj.ordPrescNo}</Row>*/}
                        </span>
                    </h1>
                    <div style={{padding: '0 48px 12px', fontSize: '14px'}}>
                        <Row>
                            <Col span={8}>
                              费别：{mainInfoObj.admReasonDesc}
                            </Col>
                            <Col span={8}>
                               处方号：{mainInfoObj.ordPrescNo}
                            </Col>
                            <Col span={8}>
                              开具日期：{mainInfoObj.ordDate}
                            </Col>

                        </Row>
                        <Row style={{margin: '4px 0'}}>
                            <Col span={8}>
                               患者：{mainInfoObj.patName}
                            </Col>
                            <Col span={8}>
                               性别：{mainInfoObj.patSexDesc}
                            </Col>
                            <Col span={8}>
                                年龄：{mainInfoObj.patAge}
                            </Col>
                        </Row>
                        <Row>
                            <Col span={8}>
                                登记号：{mainInfoObj.patNo}
                            </Col>
                            <Col span={8}>
                              科室：{mainInfoObj.ordLocDesc}
                            </Col>
                            <Col span={8}>
                               发药科室：{mainInfoObj.drugLoc}
                            </Col>
                        </Row>

                        <Row style={{margin: '4px 0'}}>
                            电话/地址：{mainInfoObj.phoneAddress}
                        </Row>
                        <Row>
                           临床诊断：{mainInfoObj.admDiag}
                        </Row>
                    </div>
                </div>
                <div
                    style={{
                        borderBottom: '1px solid #ccc', padding: '0 24px',
                        height: store.getState().tableHeight.y - 104 + 'px', overflow: 'auto'
                    }}
                    className="pr-style prescription-bar"
                >
                    <h1 style={{fontSize: '20px'}}>Rp:</h1>
                    {mainInfoObj.cmPrescFlag === '1'? <div className="marginRight">
                        <div>
                            {this.inciseData().map((data, key) => {
                                return (
                                    <Row key={key}>
                                        {data&&data.map((item, index) => {
                                            return (
                                                <Col span={8} key={index} style={{marginBottom: '20px'}}>
                                                    <span style={{fontWeight: 900}}>
                                                        {item.medDesc}
                                                    </span>
                                                    <span style={{marginLeft: '8px', position: 'relative', display: 'inline-block', fontWeight: 900}}>
                                                        {item.ordQty + item.ordUnitDesc}
                                                        {item.ordCMNote ? <b style={{position: 'absolute', top: '-8px', right: '-30px', fontWeight: 900, fontSize: '12px', color: 'blue'}}>{'(' + item.ordCMNote + ')'}</b> : ''}
                                                    </span>
                                                    <div style={{marginLeft: '10px', fontSize: '12px'}}>
                                                        {item.stkInfo[0]&&item.stkInfo[0].rows.length > 1 ? item.stkInfo[0].rows.map((child, childIndex) => {
                                                            return (
                                                                <div key={childIndex}>
                                                                    {child.stockDesc}
                                                                    <span style={{marginLeft: '8px'}}>{child.qty + child.baseUnitDesc}</span>
                                                                </div>
                                                            )
                                                        }) : ''}
                                                    </div>
                                                </Col>
                                            )
                                        })}
                                    </Row>
                                )
                            })}
                        </div>
                        <div style={{textAlign: 'center', paddingRight: '150px'}}>
                            --------------------------------------------------
                            <span style={{fontWeight: '900'}}>(以下空白)</span>
                            --------------------------------------------------
                        </div>
                        <Row style={{fontWeight: '900', }}>
                            用法：{mainInfoObj.cmFreqDesc + '，' + mainInfoObj.cmExplainDesc + '，' + mainInfoObj.cmUsageDesc}
                            <span style={{margin: '0 15px'}}>{'共：' + mainInfoObj.cmFac + "剂"}</span>
                            {mainInfoObj.cmCookTypeDesc}
                        </Row>
                    </div> :  <div>
                        <ul style={{fontSize: '14px', padding: '0 24px'}}>
                            {this.processAssociatedData(usageData).map((item, index) => {
                                let num = item.children&&item.children.length ? item.children.length : 0;
                                return (
                                    <li key={index} id={'usage' + index} style={{position: 'relative'}}>
                                        <div style={{paddingLeft: "24px", position: 'relative'}} className="prescription-list">
                                            <span style={{position: "absolute", left: 0, top: 0, display: 'inline-block', lineHeight: "30px"}}>{index + 1}、</span>
                                            {item.children&&item.children.map((childItem, childIndex) => {
                                                return (
                                                    <div key={childIndex} style={{lineHeight: "30px", height: "30px"}}>
                                                        <div style={{float: "left", width: "300px"}} className="ellipsis-nowrap-scroll-no">
                                                            {childItem.medDesc}
                                                            <span>
                                                                ({childItem.dspInfo&&childItem.dspInfo[0]&&childItem.dspInfo[0].rows[0]&&childItem.dspInfo[0].rows[0].batInfo.map((batInfoItem, index) => {
                                                                return (
                                                                    <span key={index} style={{marginLeft: "4px", fontSize: "12px"}} title={batInfoItem.batNo + "：" + batInfoItem.qty}>
                                                                            {batInfoItem&&batInfoItem.batNo ? (batInfoItem.batNo + "：" + batInfoItem.qty + " ") : ""}
                                                                        </span>
                                                                )
                                                            })})
                                                            </span>
                                                        </div>
                                                        <div style={{float: "left", width: "260px", margin: "0 50px 0 12px", textAlign: "right", height: "30px"}}>
                                                            {childItem.medSpec}
                                                            <span style={{margin: '0 6px'}}>x</span>
                                                            {childItem.partDispFlag > 0 ? <Input
                                                                value={childItem.filterDd}
                                                                style={{
                                                                    width: '40px',
                                                                    background: mainInfoObj&&mainInfoObj.backGroupColor ? mainInfoObj.backGroupColor : '#fff'
                                                                }}
                                                                className="input-botder-bottom"
                                                            /> : childItem.filterDd}
                                                            {childItem.partDispFlag > 0 ? <span>({"总数："+childItem.totalOrdQty})</span> : ''}
                                                            {childItem.ordUnitDesc}
                                                            {childItem.partDispFlag > 0 ? <span onClick={() => this.handleISModal(childItem)} className="span" style={{marginLeft: '12px'}} title='点击可选需要给药的数量'><Icon style={{color: '#999'}} type={childItem.visible ? 'caret-down' : 'caret-left'} /></span> : ''}
                                                        </div>
                                                        <div style={{display: num > 1 ? "inline-block" : "none", float: "left", width: "60px", textAlign: "right", borderRight: '1px solid #333', paddingRight: '10px'}}>
                                                            {childItem.ordDoseUnitDesc}
                                                        </div>
                                                        <div style={{display: num > 1 ? "inline-block" : "none", float: "left"}} className={num > 1 ? "show-last-span" : ""}>
                                                            <span style={{margin: "0 10px"}}>X</span> {childItem.ordDurationDesc}
                                                        </div>
                                                    </div>
                                                )
                                            })}
                                        </div>
                                        <Row className="marginRight">用法：{
                                            (item&&item.children&&item.children.length > 1 ? '' : item.children[0].ordDoseUnitDesc) +  ' ' +
                                            (item&&item.children&&item.children[0]&&item.children[0].ordFreqDesc ? item.children[0].ordFreqDesc : "") + ' ' +
                                            (item&&item.children&&item.children[0]&&item.children[0].ordUsageDesc ? item.children[0].ordUsageDesc : "")+ ' ' +
                                            (item&&item.children&&item.children.length > 1 ? '' :  item.children[0].ordDurationDesc)}
                                            <span style={{marginLeft: '50px'}}>
                                                {item&&item.children&&item.children.length > 1 ? '' : item.children[0].note}
                                            </span>
                                            <span style={{marginLeft: '20px'}}>
                                                {item&&item.children&&item.children.length > 1 ? '' : item.children[0].skinTestWayDesc}
                                            </span>
                                        </Row>
                                    </li>
                                )
                            })}
                        </ul>
                        <div className="diagonal"></div>
                    </div>}
                </div>
                <div style={{padding: '12px'}}>
                    <Row style={{marginBottom: '4px'}}>
                        <Col span={8}>
                            <Row>
                                <Col {...colTop} className="alignRight">医生签名：</Col>
                                <Col {...colBottom}>{mainInfoObj.ordDocDesc}</Col>
                            </Row>
                        </Col>
                        <Col span={8}>
                            <Row>
                                <Col {...colTop} className="alignRight">审核：</Col>
                                <Col {...colBottom}>{mainInfoObj.auditUserName}</Col>
                            </Row>
                        </Col>
                        <Col span={8}>
                            <Row>
                                <Col {...colTop} className="alignRight">金额：</Col>
                                <Col {...colBottom}>{mainInfoObj.prescAmt}</Col>
                            </Row>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={8}>
                            <Row>
                                <Col {...colTop} className="alignRight">调配：</Col>
                                <Col {...colBottom}>{mainInfoObj.prepUserName}</Col>
                            </Row>
                        </Col>
                        <Col span={8}>
                            <Row>
                                <Col {...colTop} className="alignRight">核对：</Col>
                                <Col {...colBottom}>{mainInfoObj.printUserName}</Col>
                            </Row>
                        </Col>
                        <Col span={8}>
                            <Row>
                                <Col {...colTop} className="alignRight">发药：</Col>
                                <Col {...colBottom}>{mainInfoObj.dispUserName}</Col>
                            </Row>
                        </Col>
                    </Row>
                </div>
            </div>
        )
        return (
            <div className="outpatentNew">
                <Row id="outpha-dispensing-basic" style={{padding: '0 24px'}}>
                    <Col span={15} className="input-padding-right">
                        <Row style={{marginBottom: '8px'}}>
                            <Select value={this.state.cardType} onChange={this.handleCardTypeOnChange} showSearch optionFilterProp="seatchprop" allowClear placeholder="居民健康卡" style={{width: '150px', margin: '8px 8px 0 0'}}>
                                {cardTypeOption}
                            </Select>
                            <Input value={this.state.cardNo} allowClear onChange={this.handleCardNoChange} onBlur={(e) => this.handleReadCardOnBlur(e)} onPressEnter={(e) => this.handleReadCardOnBlur(e)} placeholder="请输入卡号(Enter)" style={{width: '150px', marginTop: '8px', borderRight: '0'}} />
                            <Button style={{marginRight: '12px', background: 'rgba(77,193,130,1)', color: '#fff'}} onClick={this.handleReadCard}>读卡</Button>
                            <Input
                                title="回车触发病人ID查询"
                                allowClear
                                placeholder="病人ID/证件号(Enter)"
                                ref={this.myRef1}
                                style={{width: '160px', margin: '8px 20px 0 0'}}
                                value={patNo}
                                onBlur={(e) => this.handlePatient(e, 'blur')}
                                onChange={this.handlePatientOnChange}
                                onPressEnter={(e) => this.handlePatient(e, 'enter')}
                            />
                            <div style={{display: 'inline-block'}}>
                                收费日期：<DatePicker onChange={this.handleStartDate} value={Moment(this.state.startDate)} style={{width: '150px', marginTop: '8px'}} placeholder="开始日期" />
                                <span style={{display: 'inline-block', margin: '0 5px'}}>到</span>
                                <DatePicker onChange={this.handleEndDate} value={Moment(this.state.endDate)} style={{width: '150px', marginRight: '8px'}} placeholder="结束日期" />
                                <span>
                                    <Checkbox value={this.state.dispRecFlag} onChange={this.onChangeDispRecFlag}>已配药</Checkbox>
                                </span>
                                <Button style={{marginTop: '8px', marginLeft: '15px'}} onClick={()=>{this.getOutpatientDetailList();this.getOutpatientList();}}>查询</Button>
                            </div>
                        </Row>
                    </Col>
                    <Col span={5} style={{paddingTop: '8px'}}>
                        <Button
                            type="danger"
                            ghost
                            onClick={()=>{this.handleReprint()}}
                            style={{color: '#1890FF', borderColor: '#1890FF'}}
                        >打印</Button>
                        <Button
                            type="danger"
                            onClick={this.getOutpatient}
                            style={{margin: '0 15px'}}
                            disabled={this.state.DispensingFlag == 0 || !this.state.authorityStatus ? false : true}
                        >配药</Button>
                        <Button
                            type="primary"
                            onClick={()=>{
                                this.setState({whether: !this.state.whether},()=>{
                                    this.automaticOutpatient();
                                })
                            }}
                            disabled={this.state.authorityStatus}
                        >{this.state.whether ? '取消自动配药' : '自动配药'}</Button>
                        <Button
                            type="danger"
                            ghost
                            onClick={this.handleQuery}
                            style={{marginLeft: '15px', color: '#1890FF', borderColor: '#1890FF'}}
                        >清屏</Button>
                    </Col>
                    <Col span={4} style={{paddingTop: '8px', textAlign: 'right'}}>
                        <span style={{ fontSize: '15px', fontWeight:'700'}}>
                            当前窗口：{radioWindowData&&radioWindowData.prepWinDesc ? radioWindowData.prepWinDesc :
                            "未选择窗口"}
                            <Button type="dashed" style={{marginLeft: '20px', fontSize:'15px'}} onClick={this.switchingWindow}>切换窗口</Button>
                        </span>
                    </Col>
                </Row>
                <Row>
                    <Col span={4}>
                        <Card
                            size="small"
                            title={<div className="card-title-left-icon"><div></div>待配药</div>}
                            className="dispensing-list"
                            extra={<span style={{color: '#666'}} className='span' onClick={() => {this.setState({parameterCode: 'OutpatientDispensingDetail'},()=>{
                                this.columnRef.onOpenModel();
                            })}}><Icon type="setting" title='列权限设置' /></span>}
                        >
                            <Table
                                columns={modalColumns.length>0 ? modalColumns : this.detailColumns}
                                dataSource={detailsListData}
                                bordered
                                pagination={false}
                                scroll={{x: listLength? listLength:1500, y: store.getState().tableHeight.y+82 + 'px'}}
                                onRow={(record)=>{
                                    return {
                                        // 单击行选中
                                        onClick: () => {
                                            if (this.state.leftID === '') {
                                                // 保存行数据以及ID
                                                this.setState({leftID: record.patID}, () => {
                                                    this.getOutpatientList(record.patID);
                                                })
                                            } else {
                                                if (this.state.leftID !== record.patID) {
                                                    this.setState({leftID: record.patID}, () => {
                                                        this.getOutpatientList(record.patID);
                                                    })
                                                }else {
                                                    this.setState({leftID:'',detailData:[],total: 0, selectedRowKeys: [],selectAllData:[],DispensingFlag:null,mainInfo:{},usageData:[]})
                                                }
                                            }
                                        }
                                    }
                                }}
                                rowClassName={this.setRowClassNameLeftTable}
                                className="table-detail-height"
                            />
                        </Card>
                    </Col>
                    <Col span={8}>
                        <Card
                            size="small"
                            title={<div className="card-title-left-icon"><div></div>配药列表</div>}
                            extra={<span style={{color: '#666'}} className='span' onClick={() => {this.setState({parameterCode: 'OutpatientDispensing'},()=>{
                                this.columnRef.onOpenModel();
                            })}}><Icon type="setting" title='列权限设置' /></span>}
                        >
                            <div>
                                <Table
                                    rowSelection={rowSelection}
                                    selectedRowKeys={this.state.selectedRowKeys}
                                    columns={Columns.length>0 ? Columns : this.columns}
                                    dataSource={detailData}
                                    bordered
                                    pagination={false}
                                    scroll={{x: topLength? topLength : 1800, y: store.getState().tableHeight.y +44 + 'px'}}
                                    onRow={this.onClickRowLeftTable}
                                    rowClassName={this.setRowClassNameTable}
                                    className="table-scroll-height"
                                />
                                <CommonPagination pageSize="20" size='small' current={this.state.page} total={this.state.total} search= 'search'
                                                  onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={detailData}
                                                  loading={this.state.loading} onChange={this.onChange.bind(this)}  />
                            </div>
                        </Card>
                    </Col>
                    <Col span={12}>
                        <div style={{paddingLeft: '6px', position: 'relative'}}>
                            <Card
                                size="small"
                                title="处方笺"
                                // extra={<a href="#">More</a>}
                                className="catd-head-bg-img prescription"
                            >
                                <div className="prescription-bar" style={{
                                    height: store.getState().tableHeight.y + 153 + 'px',
                                    overflow: 'auto',
                                    background: mainInfoObj&&mainInfoObj.backGroupColor ? mainInfoObj.backGroupColor : '#fff'
                                }}>
                                    <p style={{textAlign: 'center', display: !(mainInfo&&mainInfo.length > 0) ? 'block' : 'none', textDecoration: 'underline'}}>选择左侧处方来查看处方单</p>
                                    <div style={{
                                        width: '100%',
                                        height: '100%',
                                        display: mainInfo&&mainInfo.length > 0 ? 'block' : 'none',
                                    }}>
                                        {medicalAdviceDom}
                                    </div>
                                </div>
                            </Card>
                            <div style={{width: '6px', background: 'rgba(240, 242, 245, 1)', position: 'absolute', top: 0, left: 0, height: '100%'}}></div>
                        </div>
                    </Col>
                </Row>
                <Modal
                    title={<div><div className="modal-title-top"></div>选择窗口</div>}
                    visible={windowVisible}
                    style={{minWidth: '680px'}}
                    className="modal-header-line modal-body-padding"
                    onCancel={() => this.handleCancel()}
                    footer={
                        <div>
                            <Button style={{marginRight: '8px'}} onClick={() => this.handleCancel()}>取消</Button>
                            <Button onClick={this.windowHandleOk} style={{backgroundColor: '#1890ff', borderColor: '#1890ff', color: '#fff'}}>确认</Button>
                        </div>
                    }
                >
                    <div style={{color: '#F5222D', fontSize: '4px', background: '#FFF1F0', height: '32px', lineHeight: '32px', paddingLeft: '24px'}}>
                        <Icon type="exclamation-circle" style={{marginRight: '4px'}} />切换窗口时请选择需要切换的窗口并点击确定按钮。
                    </div>
                    <Form style={{padding: '0 24px'}}>
                        <Form.Item label="请选择窗口：">
                            {getFieldDecorator('window', {
                                rules: [{ required: true }],
                            })(
                                <Row className="ad-window li-window" style={{padding: '0 20px'}}>
                                    {windowDom}
                                </Row>
                            )}
                        </Form.Item>
                    </Form>
                </Modal>
                <ColumnAuthoritysModel
                    clientWidth='800px'
                    compontName={ this.state.parameterCode}
                    configType="C"
                    onRef={this.onColumnRef}
                    reloadData={() => {
                        if (this.state.parameterCode == 'OutpatientDispensing') {
                            this.getListTableColumns()
                        }else if(this.state.parameterCode == 'OutpatientDispensingDetail'){
                            this.getDetailListTableColumns()
                        }
                    }
                    }
                />
            </div>
        )
    }
};
const DispensingForm = Form.create()(Dispensing);
export default DispensingForm;
