// 执行医嘱停用
import React from 'react';
import { Card, Row, Col, Form, Select, Button, Table, Checkbox, message, Input, notification } from 'antd';
import { $http } from 'containers/config/https';
import { Util, dayFormat } from 'tools/index';
import { $loadTemplate } from '../../lodop/Common/Print.js';
import Moment from 'moment';
import store from 'store';
import RangeDatePicker from 'components/rangePicker/index';
import CommonPagination from 'components/pagination/index';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import GetPatientInformation from 'pages/optometry/component/GetPatientInformation';
import './style/index.less';

let userData;

const Discontinue = Form.create()(
    class extends React.Component {
        constructor() {
            userData = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
            super();
            this.state = {
                getDepartmentInformation: [], // 科室下拉框
                pageSize: 50,
                page: 1,
                total: 0,
                columns: [],
                columnsWidth: '',
                tableData: [],
                data: [],
                selectedRowKeys: [],
                selectedRows: [],
                ENObj: {},
                CNObj: {},
                languageObj: {},
                ordExecBilled: [], // 账单状态
                admTypeData: [], // 就诊状态，
                exportStatus: false, // 导出中状态
                sessionObj: {}, // session对象
                ipconfigObj: {}, // ipconfig对象
                selectData: {},
                queryParams: {
                    MedicalNo: undefined, // 住院号
                    admTypeCode: undefined,
                    ordStartDate: Moment().format(dayFormat),
                    ordEndDate: Moment().format(dayFormat),
                    ordStatusDesc: 'N', // 已执行医嘱
                },
                loading: false
            }
        }

        componentDidMount() {
            const sessionObj = sessionStorage.userData ? JSON.parse(sessionStorage.userData) : {};
            const ipconfigObj = sessionStorage.ipConfig ? JSON.parse(sessionStorage.ipConfig) : {};
            this.setState({ sessionObj, ipconfigObj });
            // 初始化数据
            this.getAdmTypeData();
            this.getTableColumns();
            this.getDepartmentInformation();
            this.patientRef && this.patientRef?.getCardSelectData();
            let self = this
            document.addEventListener('keydown', function (e) {
                self.KeyDowns(e)
            })
            setTimeout(() => { this.input && this.input.focus() }, 1000)
        }

        componentWillUnmount() {
            setTimeout(() => {
                window.removeEventListener('keydown', this.KeyDowns())
            }, 1000);
            // 组件销毁前将静止让setState修改state的状态，防止内存泄漏
            this.setState = (state, callback) => { return; }
        }

        KeyDowns = (e) => {
            if (e && e.keyCode) {
                let self = this
                let currKey = 0;
                e = e || window.event;
                currKey = e.keyCode || e.which || e.charCode;
                //快捷键保存  shilt/alt/ctrl + s 
                if (currKey == 83 && e.ctrlKey) {
                    self.getOrdID('F')
                    e.preventDefault();
                    return false;
                }
            }
        }

        hex2int = (hex) => {
            var len = hex.length, a = new Array(len), code;
            for (var i = 0; i < len; i++) {
                code = hex.charCodeAt(i);
                if (48 <= code && code < 58) {
                    code -= 48;
                } else {
                    code = (code & 0xdf) - 65 + 10;
                }
                a[i] = code;
            }
            return a.reduce(function (acc, c) {
                acc = 16 * acc + c;
                return acc;
            }, 0);
        }

        //获取列表头数据
        getTableColumns = () => {
            const { queryParams } = this.state;
            let data = {
                params: [{
                    reactCode: ['MedicalTechnology'],
                    compontName: 'MedicalTechnology',
                    type: 'C',
                }]
            }
            let that = this;
            $http.post('urlS', this, {
                code: '01040073',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let column = res.result.C;
                        if (userData.language == 'EN') {
                            for (let i = 0; i < column.length; i++) {
                                column[i].title = column[i].enDescripts
                            }
                        }
                        var columns = []
                        if (userData.hospID == '62') {
                            var caseNO = column.filter((item) => {
                                return item.dataIndex == 'caseNo';
                            })
                            if (caseNO.length == 0) {
                                if (queryParams.admTypeCode && queryParams.admTypeCode == 'I') {
                                    {
                                        var caseNoArr = column.splice(1, 0,
                                            {
                                                align: 'center',
                                                dataIndex: 'caseNo',
                                                title: '住院号',
                                                width: '100px'
                                            });
                                    }
                                }
                            }
                        }

                        if (!Util.isEmpty(column)) {
                            for (var i = 0; i < column.length; i++) {
                                if (column[i].dataIndex == 'medDesc') {
                                    columns.push({
                                        title: column[i].title,
                                        dataIndex: column[i].dataIndex,
                                        width: parseInt(column[i].width),
                                        align: column[i].align || 'center',
                                        render: (text, data) => {
                                            var color = '#000';
                                            if (data.containerColor != '') {
                                                var containerColor = data.containerColor.replace('#', '');
                                                var grayLevel = 255;
                                                if (containerColor.length == 6) {
                                                    grayLevel = that.hex2int(containerColor.substring(0, 2)) * 0.299 + that.hex2int(containerColor.substring(2, 4)) * 0.587 + that.hex2int(containerColor.substring(4, 6)) * 0.114;
                                                } else {
                                                    grayLevel = that.hex2int(containerColor.substring(0, 1)) * 0.299 + that.hex2int(containerColor.substring(1, 2)) * 0.587 + that.hex2int(containerColor.substring(2, 3)) * 0.114;
                                                }
                                                if (grayLevel <= 192) {
                                                    color = '#fff';
                                                }
                                            }
                                            return <div style={{ background: data.containerColor, width: '100%', height: '100%', color: color }}>{data.medDesc}</div>
                                        }
                                    })
                                } else {
                                    columns.push(column[i])
                                }
                            }
                        }
                        this.setState({
                            columns: columns,
                            columnsWidth: res.totalWidth,
                            ENObj: res.result.language.EN,
                            CNObj: res.result.language.CN,
                        }
                            , () => {
                                setTimeout(() => { this.handleQuery() }, 500)
                            })
                    }
                }
            });
        };

        onColumnRef = (ref) => {
            this.columnRef = ref;
        }

        getOrdID = (flag, e) => {
            var orderIDs = []
            for (var i = 0; i < this.state.selectedRows.length; i++) {
                orderIDs.push(this.state.selectedRows[i].ordID)
            }
            if (orderIDs.length <= 0) { message.error('请选择需要操作的记录'); return }
            let data = {
                params: [{
                    ordIDs: orderIDs,//医嘱数组
                    date: '',
                    time: '',
                    userID: userData.userID,
                    code: flag,
                    locID: userData.locID,
                }]
            };
            $http.post('urlS', this, {
                code: '04030003',
                data: data,
                success: function (res) {
                    let errorCode = res.errorCode;
                    if (errorCode === '0') {
                        //message.success('成功');
                        if (!Util.isEmpty(res.errorArr)) {
                            message.error((res.errorArr).join(','))
                        } else {
                            message.success('操作成功！')
                        }
                        this.setState({
                            data: res.result,
                            selectedRowKeys: [],
                            selectedRows: [],
                        })

                    } else {
                        this.setState({
                            data: [],
                        })
                    }
                    this.handleQuery()
                    setTimeout(() => { this.input && this.input.focus() }, 1000)
                }
            });
        }

        // 打印
        print = () => {
            var orderIDs = [];
            for (var i = 0; i < this.state.selectedRows.length; i++) {
                orderIDs.push(this.state.selectedRows[i].ordID)
            }
            let data = {
                params: [{
                    ordExeIDs: orderIDs,//医嘱数组
                }]
            };
            $http.post('urlS', this, {
                code: '04030017',
                data: data,
                success: function (res) {
                    if (res.errorCode === '0') {
                        const data = res.result
                        if (data.length > 0) {
                            for (let i = 0; i < data.length; i++) {
                                //加载模板
                                $loadTemplate(data[i].template, data[i].printStr);
                            }
                        }
                    }
                }
            });
        };

        //延时执行
        sleep = (millisecond) => {
            return new Promise(resolve => {
                setTimeout(() => {
                    resolve()
                }, millisecond)
            })
        };

        // 导出
        exportFun = async () => {
            //导出状态
            this.setState({
                exportStatus: true
            });

            let { sessionObj, ipconfigObj, queryParams } = this.state;
            let patientInfo = this.patientRef && this.patientRef.getPatientInfo();
            let data = {
                params: [{
                    queryParams: {
                        params: [{
                            ...queryParams,
                            ...patientInfo,
                            accPatNo: patientInfo.patNo || '',
                            locID: userData.locID,
                        }],
                        code: '04030016',
                        pagination: [{
                            pageSize: this.state.pageSize,
                            currentPage: this.state.page,
                        }],
                        session: [
                            {
                                userID: sessionObj.userID,
                                locID: sessionObj.locID,
                                groupID: sessionObj.groupID,
                                hospID: sessionObj.hospID,
                                sessionID: sessionObj.sessionID,
                                hospCode: sessionObj.hospCode,
                                language: sessionObj.language,
                                hostName: ipconfigObj.hostName,
                                ipv4: ipconfigObj.ipv4,
                                ipv6: ipconfigObj.ipv6,
                                mac: ipconfigObj.mac
                            }
                        ],
                    },
                    queryCode: '04030016',
                    componentCode: 'MedicalTechnology'
                }],
                pagination: [{
                    pageSize: this.state.pageSize,
                    currentPage: this.state.page,
                }],
                session: [
                    {
                        userID: sessionObj.userID,
                        locID: sessionObj.locID,
                        groupID: sessionObj.groupID,
                        hospID: sessionObj.hospID,
                        sessionID: sessionObj.sessionID,
                        hospCode: sessionObj.hospCode,
                        language: sessionObj.language,
                        hostName: ipconfigObj.hostName,
                        ipv4: ipconfigObj.ipv4,
                        ipv6: ipconfigObj.ipv6,
                        mac: ipconfigObj.mac
                    }
                ]
            };

            await this.sleep(1000); //延时，按钮效果
            const resObj = await React.$asyncPost(this, '11020007', data);
            if (resObj) {
                let errorCode = resObj.errorCode;
                if (+errorCode === 0) {
                    let downLoadUrl = resObj.result.downloadURL;
                    //异步--消息提醒
                    if (downLoadUrl === '') {
                        this.exportNotification(); //提示栏
                        store.dispatch({
                            type: 'downloadTask',
                            value: {
                                timeStamp: new Date().getTime(),
                                startDate: Moment(new Date()).format(dayFormat),
                                endDate: Moment(new Date()).format(dayFormat)
                            }
                        })
                    } else { //同步-直接取到链接后下载
                        window.open(downLoadUrl, '_parent')
                    }

                    this.setState({
                        exportStatus: false
                    });
                } else {
                    this.setState({
                        exportStatus: false
                    });
                    message.error(resObj.errorMessage)
                }
            }
        };

        //右上角提示栏
        exportNotification = () => {
            const msgValue = (<p>数据正在导出，导出完成后可在右上角<span style={{ color: 'red' }}>↗</span><span style={{ fontWeight: 'bold' }}>【导出任务列表】</span>中下载</p>);
            notification.info({
                message: '导出中..',
                description: msgValue,
                placement: 'topRight',
                style: {
                    top: 30,
                },
            });
        };

        // 3.13.23.获取科室信息
        getDepartmentInformation() {
            let data = {
                params: [
                    {
                        hospID: userData.hospID,
                        type: 'EX^L'
                    }
                ]
            }
            $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: [] })
                    }
                }
            })
        }

        // 3.13.24 获取就诊类型
        getAdmTypeData = () => {
            let { queryParams } = this.state;
            let data = {
                params: [{}]
            }
            $http.post('urlS', this, {
                code: '04030019',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let admTypeData = res.result?.admTypeData || [];
                        queryParams.ordStartadmTypeCodeDate = admTypeData && admTypeData.length > 0 ? admTypeData[0].id : undefined;
                        queryParams.ordStartDate = res.result.startDate ? res.result.startDate : Moment().format(dayFormat);
                        queryParams.ordEndDate = res.result.endDate ? res.result.endDate : Moment().format(dayFormat);
                        this.setState({
                            queryParams,
                            admTypeData
                        })
                    }
                }
            })
        }

        // 获取列表数据
        handleQuery = () => {
            this.setState({ loading: true });
            const { queryParams } = this.state;
            let patientInfo = this.patientRef && this.patientRef.getPatientInfo();
            let data = {
                params: [{
                    ...queryParams,
                    ...patientInfo,
                    accPatNo: patientInfo.patNo || '',
                    locID: userData.locID,
                }],
                pagination: [{
                    pageSize: this.state.pageSize,
                    currentPage: this.state.page,
                }]
            };
            $http.post('urlS', this, {
                code: '04030016',
                data: data,
                success: (res) => {
                    if (res.errorCode === '0') {
                        for (let index = 0; index < res.result.length; index++) {
                            res.result.row[index].key = index + 1;
                        }
                        this.setState({
                            loading: false,
                            total: res.result.total,
                            tableData: res.result.row,
                            selectedRowKeys: [],
                            selectedRows: [],
                        });
                    } else {
                        this.setState({
                            loading: false,
                            total: 0,
                            tableData: [],
                            selectedRowKeys: [],
                            selectedRows: [],
                        });
                    }
                },
                error: function () {
                    this.setState({ loading: false });
                }
            });
        }

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

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

        // 修改操作框数据
        handleModifyInputValue = (e, dataIndex) => {
            this.state.queryParams[dataIndex] = e;
            this.setState({}, () => {
                if (dataIndex === 'ordStartDate' || dataIndex === 'ordEndDate' || dataIndex === 'ordStatusDesc' || dataIndex === 'ordExecBilled' || dataIndex === 'admTypeCode') {
                    this.handleQuery();
                }
                if (dataIndex === 'admTypeCode' && userData.hospID == '62') {
                    this.getTableColumns();
                }
            })
        }

        render() {
            var language = userData.language
            var languageObj = {}
            if (language == 'EN') {
                languageObj = this.state.ENObj
            } else {
                languageObj = this.state.CNObj
            }
            let { loading, columns, columnsWidth, queryParams, admTypeData } = this.state;
            const rowSelection = {
                onChange: (selectedRowKeys, selectedRows) => {
                    this.setState({ selectedRowKeys: selectedRowKeys, selectedRows: selectedRows })
                },
                selectedRowKeys: this.state.selectedRowKeys,
            };

            const billedOptions = [
                { label: '未结算', value: 'N' },
                { label: '已结算', value: 'Y' },
            ];
            let caseNoVis = 'none';
            if (userData.hospID === '62') {
                caseNoVis = (queryParams?.admTypeCode != 'I' ? 'none' : '');
            }

            return (
                <div className="ordersOff">
                    <Row style={{ padding: '12px 24px', paddingTop: 0 }}>
                        <Col className="flex-wrap-align-items" span={19}>
                            <div style={{ marginTop: '12px' }}>
                                <GetPatientInformation
                                    queryType="fuzzySearch"
                                    patNoPlaceholder="人员标识"
                                    onRef={ref => this.patientRef = ref}
                                    handleQuery={this.handleQuery}
                                />
                            </div>
                            <div style={{ marginTop: '12px', marginRight: '15px' }}>
                                <RangeDatePicker
                                    width="280px"
                                    isChange={true}
                                    format={dayFormat}
                                    label="医嘱日期："
                                    endDate={queryParams?.ordEndDate || undefined}
                                    startDate={queryParams?.ordStartDate || undefined}
                                    endChange={(e) => this.handleModifyInputValue(e, 'ordEndDate')}
                                    startChange={(e) => this.handleModifyInputValue(e, 'ordStartDate')}
                                />
                            </div>
                            <div style={{ marginTop: '12px' }}>
                                {languageObj.MedicalTechnologyadmType != null ? languageObj.MedicalTechnologyadmType.descripts : '就诊类型'}：
                                <Select
                                    allowClear
                                    className="common-query-input"
                                    optionFilterProp="seatchprop"
                                    placeholder="请选择"
                                    value={queryParams?.admTypeCode || undefined}
                                    onChange={(e) => this.handleModifyInputValue(e, 'admTypeCode')}
                                >
                                    {React.$SelectOptions(admTypeData)}
                                </Select>
                            </div>
                            {caseNoVis !== 'none' ? (
                                <div style={{ marginTop: '12px' }}>
                                    住院号：<Input
                                        className="common-query-input"
                                        value={queryParams?.MedicalNo || undefined}
                                        ref={(input) => { this.input = input }}
                                        onPressEnter={this.handleQuery}
                                        onChange={(e) => this.handleModifyInputValue(e, 'MedicalNo')}
                                    />
                                </div>
                            ) : ''}
                            <div style={{ marginTop: '12px' }}>
                                {languageObj.MedicalTechnologyordExecBilled != null ? languageObj.MedicalTechnologyordExecBilled.descripts : '账单状态：'}
                                <Checkbox.Group
                                    value={queryParams?.ordExecBilled || undefined}
                                    options={billedOptions}
                                    onChange={(e) => this.handleModifyInputValue(e, 'ordExecBilled')}
                                />
                            </div>
                            <div style={{ marginTop: '16px', marginLeft: '15px' }}>
                                {languageObj.MedicalTechnologyOrderExecuted != null ? languageObj.MedicalTechnologyOrderExecuted.descripts : '已执行医嘱'}：
                                <Checkbox
                                    checked={queryParams?.ordStatusDesc === 'Y' ? true : false}
                                    onChange={(e) => this.handleModifyInputValue(e.target.checked ? 'Y' : 'N', 'ordStatusDesc')}
                                >
                                </Checkbox>
                            </div>
                        </Col>
                        <Col span={5}>
                            <div style={{ marginTop: '12px' }}>
                                <Button type="primary" style={{ marginRight: '12px' }} onClick={this.handleQuery}>{languageObj.MedicalTechnologySearch != null ? languageObj.MedicalTechnologySearch.descripts : '查询'}</Button>
                                <Button type="primary" style={{ marginRight: '12px' }} onClick={this.getOrdID.bind(this, 'F')}>{languageObj.MedicalTechnologyexecute != null ? languageObj.MedicalTechnologyexecute.descripts : ''}</Button>
                                <Button ghost type="danger" onClick={this.getOrdID.bind(this, 'CE')}>{languageObj.MedicalTechnologycancel != null ? languageObj.MedicalTechnologycancel.descripts : ''}</Button>
                            </div>
                            <div style={{ marginTop: '12px' }}>
                                <Button type="primary" style={{ marginRight: '12px' }} onClick={this.print}>{languageObj.MedicalTechnologyPrint != null ? languageObj.MedicalTechnologyPrint.descripts : ''}</Button>
                                <Button type="primary" loading={this.state.exportStatus} disabled={Util.isEmpty(this.state.tableData)} onClick={this.exportFun}>{this.state.exportStatus === true ? '导出中' : '导出'}</Button>
                            </div>
                        </Col>
                    </Row>
                    <div className="common-query-split-line" style={{ height: 8 }}></div>
                    <Card
                        bordered={false}
                        size="small"
                        title={<div className="card-title-left-icon">
                            <div></div>{languageObj.MedicalTechnologyOrderList != null ? languageObj.MedicalTechnologyOrderList.descripts : ''}</div>
                        }
                    >
                        <div>
                            <Table
                                loading={loading}
                                columns={columns.length > 0 ? columns : this.columns}
                                dataSource={this.state.tableData}
                                pagination={false}
                                bordered
                                rowSelection={rowSelection}
                                style={{ height: store.getState().tableHeight.y + 30 + 'px' }}
                                scroll={{ x: columnsWidth ? columnsWidth : 1200, y: store.getState().tableHeight.y - 20 }}
                                onHeaderRow={column => {
                                    return {
                                        onDoubleClick: () => {
                                            this.columnRef.onOpenModel();
                                        },
                                    };
                                }}
                                rowKey={record => record?.key || record?.ordID || ''}
                                rowClassName={record => { if ((record.ordStatusCode != 'F') && (record.ordStatusCode != '504')) return 'table-color-dust'; }}
                            />
                            <CommonPagination
                                size="large"
                                // pageSize
                                current={this.state.page}
                                total={this.state.total}
                                search='search'
                                onShowSizeChange={this.onShowSizeChange.bind(this)}
                                complete={true}
                                dataSource={this.state.tableData}
                                loading={this.state.loading}
                                onChange={this.onChange.bind(this)}
                            />
                        </div>
                    </Card>
                    <ColumnAuthoritysModel
                        clientWidth='800px'
                        compontName='MedicalTechnology'
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={this.getTableColumns}
                    />
                </div>
            )
        }
    }
);

export default Discontinue;