import React from 'react';
import { Select, Input, Modal, message, Radio } from 'antd';
import fetchJsonp from 'fetch-jsonp';
import { $http } from 'containers/config/https';
import { INSUYBUtil } from 'tools/index';

class ReadCard extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            cardTypeObj: [],
            qrCode: "",
            areaType: "本地",
            cardShow: false,
            ecTokenScence: '',	//电子凭证业务场景
            ecTokenScenceList: [],
        };
    }

    componentWillMount() {
        const userData = sessionStorage.userData ? JSON.parse(sessionStorage.userData) : {}
        const hospID = userData.hospID
        let data = {
            params: [{
                hospID: hospID
            }]
        }
        $http.post("urlS", this, {
            code: "01040059",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {

                    this.setState({
                        cardTypeObj: res.cardType
                    })
                } else {
                    message.error('失败：' + res.errorMessage);
                }
            }
        })
        this.getEctokenScenceList(); //业务场景
    }

    onAreaTypeChange = (e) => {
        this.setState({ areaType: e.target.value });
    };

    onqrCodeChange = (e) => {
        this.setState({ qrCode: e.target.value });
    };

    componentWillUnmount() {
        // 组件销毁前将静止让setState修改state的状态
        this.setState = (state, callback) => { return; }
    }

    // 选择电子凭证业务类型
    ecTokenScenceChange = (e) => {
        this.setState({
            ecTokenScence: e
        })
    }

    // 电子凭证业务场景
    getEctokenScenceList = () => {
        $http.post('urlS', this, {
            code: "05210100",
            data: {},
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    this.setState({
                        ecTokenScenceList: res.proKArr || []
                    })
                }
            }
        });
    }

    ReadCard = async (cardType, mode, callback, readCardCode) => {
        var cardTypeCode = ""
        var cardTypeObj = this.state.cardTypeObj
        var dllPath = ""
        var className = ""
        var funcName = ""
        for (var i = 0; i < cardTypeObj.length; i++) {
            var itemObj = cardTypeObj[i]
            if (itemObj.id === cardType) {
                cardTypeCode = itemObj.code
                var equiData = itemObj.equiData
                dllPath = equiData.dllPath
                className = equiData.className
                for (var j = 0; j < equiData.func.length; j++) {
                    var funcItem = equiData.func[j]
                    if (funcItem.funType === mode) {
                        funcName = funcItem.funDesc
                    }
                }
            }
        }
        if ((dllPath === "") || (className === "") || (funcName === "")) {
            message.error("读卡设备配置不正确,不能读卡");
            return
        }
        /**
         * @ByYQL: 卡类型为医保卡时调用电子凭证DLL
         * Create 2022-9-26
         */
        let dllInputdata = {};
        console.log('dllPath', +cardType);
        if (+cardType === 8) {
            //旧医保
            let that = this;
            dllInputdata = {
                "iShowForm": 0,
                "iCardType": "01", //01：电子凭证
                "operatorId": JSON.parse(window.sessionStorage.userData).userCode,
                "operatorName": JSON.parse(window.sessionStorage.userData).userName,
                "officeId": JSON.parse(window.sessionStorage.userData).locID,
                "officeName": JSON.parse(window.sessionStorage.userData).locDesc,
                "patID": ''
            };
            let dllParams = JSON.stringify({ inputDir: dllPath, clsName: className, funcName: funcName, dllInput: JSON.stringify(dllInputdata) });
            if (typeof (CefSharp) != "undefined") {   // 新元素定制浏览器
                CefSharp.BindObjectAsync("xysCefToJavaScripts");
                setTimeout(() => {
                    xysCefToJavaScripts.driveLocalHardware(dllParams).then((returnVale) => {
                        var res = JSON.parse(returnVale);
                        console.log('DLL反1', res);
                        if (+res.errorCode === 0) {
                            if (res.result) {
                                that.handleVoucherInfo(cardType, res.result?.cardInfo, callback, res.result, readCardCode);
                            } else {
                                message.warn('未获取到反参')
                            }
                        } else {
                            message.warn(res.errorMessage);
                        }
                    })
                }, 100);
            } else {
                const frame = chrome?.webview?.hostObjects?.Bridge || ''; // 新版浏览器
                if (frame) {
                    frame.DynamicLoadingDLL(dllParams)
                        .then(
                            data => {
                                let res = JSON.parse(data);
                                console.log('DLL反1', res);
                                if (+res.errorCode === 0) {
                                    if (res.result) {
                                        that.handleVoucherInfo(cardType, res.result?.cardInfo, callback, res.result, readCardCode);
                                    } else {
                                        message.warn('未获取到反参')
                                    }
                                } else {
                                    message.warn(res.errorMessage);
                                }
                            },
                            err => {
                                console.log('error', err);
                            }
                        )
                } else {
                    fetchJsonp("http://127.0.0.1:62534/XYSWCFService/DynamicLoadingDLL?JsonCallback=?", {
                        input: dllParams
                    },
                        function (data) {
                            let res = JSON.parse(data);
                            console.log('DLL反1', res);
                            if (+res.errorCode === 0) {
                                if (res.result) {
                                    that.handleVoucherInfo(cardType, res.result?.cardInfo, callback, res.result, readCardCode);
                                } else {
                                    message.warn('未获取到反参')
                                }
                            } else {
                                message.warn(res.errorMessage);
                            }
                        });
                }
            }
        } else if (+cardType === 11) {
            //需要医保结算弹出医保卡号输入界面
            this.setState({ cardShow: true, qrCode: "", areaType: "本地", insuReadFlag: "INSUJNSYB", cardType: cardType, readCardCode: readCardCode, callback: callback });
        } else if (cardTypeCode.indexOf("INSU") > -1) {
            //医保平台
            let insupaydata = {
                params: [{
                    "userID": JSON.parse(window.sessionStorage.userData).userID || '',
                    "locID": JSON.parse(window.sessionStorage.userData).locID,
                    "hospID": JSON.parse(window.sessionStorage.userData).hospID, //医院id
                    "groupID": JSON.parse(window.sessionStorage.userData).groupID,  //角色id
                    "ip": React.$getSessionData('ipConfig')?.ipv4 || ''
                }],
                "businessType": "Z1",
                "hospID": JSON.parse(window.sessionStorage.userData).hospID, //医院id
                session: [(JSON.parse(sessionStorage.getItem('userData')))]
            }
            let patientInfo = await INSUYBUtil.insuNew("GetPatientInfo", insupaydata);
            let patientInfoRet = JSON.parse(patientInfo);
            // let patientInfoRet ={"errorCode":0,"errorMessage":"","result":{"selectedInsuInfo":{"balc":4310.36,"insutype":"310","psn_type":"11","cvlserv_flag":"0","insuplc_admdvs":"441502","emp_name":"汕尾市医疗保障局","psn_insu_stas":"1","mdtrt_cert_type":"02","mdtrt_cert_no":"541502199101242310"},"selectedIdInfo":{},"output":{"idetinfo":[],"baseinfo":{"certno":"541502199101242310","psn_no":"541500CS000000301426","gend":"2","exp_content":null,"brdy":"1991-01-17","naty":"01","psn_cert_type":"01","psn_name":"邱岸洋","age":31.8},"insuinfo":[{"balc":4310.36,"insutype":"310","psn_type":"11","cvlserv_flag":"0","insuplc_admdvs":"441502","emp_name":"汕尾市医疗保障局","psn_insu_stas":"1"},{"balc":0,"insutype":"510","psn_type":"11","cvlserv_flag":"0","insuplc_admdvs":"441502","emp_name":"汕尾市医疗保障局","psn_insu_stas":"1"},{"balc":0,"insutype":"390","psn_type":"15","cvlserv_flag":"0","insuplc_admdvs":"441502","emp_name":"汕尾市陆河县陆河县未划分乡镇","psn_insu_stas":"1"}]}}}
            console.log('INSU反', patientInfoRet);
            if (+patientInfoRet.errorCode === 0) {
                if (patientInfoRet.result) {
                    this.handleVoucherInfo(cardType, patientInfoRet.result, callback, patientInfoRet.result, readCardCode);
                } else {
                    message.warn('未获取到反参')
                }
            } else {
                message.warn(patientInfoRet.errorMessage);
            }
        } else {
            let jsonpDllParams = '{"inputDir":"' + dllPath + '","clsName":"' + className + '","funcName":"' + funcName + '"}';
            let that = this;
            const frame = chrome?.webview?.hostObjects?.Bridge || ''; // 新版浏览器
            if (frame) {
                frame.DynamicLoadingDLL(jsonpDllParams)
                    .then(
                        json => {
                            json = JSON.parse(json)
                            if (json.errorCode === "0") {
                                message.success('读卡成功');
                                var cardNo = json.cardNo
                                if (mode === "RI") {
                                    callback(json);
                                    return
                                }
                                that.GetPatInfoByCardNoThis(cardType, cardNo, callback);
                            } else {
                                message.error(json.errorMessage);
                            }
                            return cardNo
                        },
                        () => {
                            that.setState({
                                visibleIp: true
                            })
                            return false
                        }
                    )
            } else {
                fetchJsonp('http://127.0.0.1:62534/XYSWCFService/DynamicLoadingDLL?' + '&input=' + jsonpDllParams, {
                    jsonpCallback: 'JsonCallback',
                })
                    .then(function (response) {
                        return response.json()
                    }).then(function (json) {
                        //返回卡号
                        json = JSON.parse(json)
                        if (json.errorCode === "0") {
                            message.success('读卡成功');
                            var cardNo = json.cardNo
                            if (mode === "RI") {
                                callback(json);
                                return
                            }
                            that.GetPatInfoByCardNoThis(cardType, cardNo, callback);
                        } else {
                            message.error(json.errorMessage);
                        }
                        return cardNo
                    }).catch(function (ex) {
                        that.setState({
                            visibleIp: true
                        })
                        return false
                    })
            }
        }
    };

    cardYBInputSure = async () => {
        let dllInputdata = {
            "params": [{
                "userID": JSON.parse(window.sessionStorage.userData).userID || '',
                "qrCode": this.state.qrCode,
                "icCardNum": "",
                "areaType": this.state.areaType,
                "hospID": JSON.parse(window.sessionStorage.userData).hospID,
                "reasonCode": "INSUJNSYB",
                "patID": "",
                "patName": "",
                "xnhjgCode": "",
                "QrBusinessType": this.state.ecTokenScence
            }],
            "code": "05210036"
        };
        let data = await INSUYBUtil.insuYBAHSYB("ReadYBCard", dllInputdata);         //读医保病人信息
        let res = JSON.parse(data);
        console.log('ReadYBCard反', res);
        // let res={"errorCode":"0","errorMessage":"成功","result":{"gfbb":"","mzdbbz":"0","sfzhm":"370687199201050041","yfdxbz":"","rydjid":"12370687199201050041","bz":"","zfsm":"","xm":"李超","zccyrq":"","appid":"1DBHJRS5I01E0F34A8C00000B959FA87","resultcode":0,"esicard_no":"","ectoken":"370000eci49hgjgf6p6d01500a0000dbdbd070","posfzhm":"","jbjgid":"37010201","kh":"A04585555","sbqbye":0,"cbzt":"1","psamkh":"","xb":"2","mzdbxesm":"","resulttext":"调用成功","ybbh":"","mzddbz":"1","jzrylb":"","zfbz":"1","dwxz":"10","dwmc":"济南普瑞眼科医院有限公司","xzqh":"370100","lbjbmc":"","zcyymc":"*","dsjgbh":"","ylzdjfny":"","zhye":455.43,"gjzhye":0,"sbm":"","wxtoken":"","zyzt":"0","kzt":"1","ptmzjbs":"","lbjbbm":"","channel_no":"01","mzddsm":"","sbjgbh":"370100","pkrkbz":"","tjrylb":"0","scbwjcd":"","bcrylb":"","dwbh":"0010072608","sfxsptmztc":"","jsffbaxx":"","tjrylbmx":"","mzdb_ejjbbm":"","ylrylbcode":"0","mzdb_ejjbmc":"","zhzybz":"0","cbjgmc":"","kyhzh":"6214672340304172636","ydbz":"0","ryid":"12370687199201050041","syzdjfny":"","ylrylb":"在职","cqhlbalb":"","ye":455.43,"ecqrcode":"","sbkydbz":"0","mzdb_bz":"","gsjcxx":"","dyrylb":"0","zhzysm":"","ptmztcsm":"","dwxzmc":"企业","mz":"","rqlb":"A","dqsfsm":"","poxm":"","mdtrt_cert_type":"01","yfdxlb":"","jsjg":"","dynamic_code":"4243803529659183948801370000","qdzffs":"","mzdbyys":"","csrq":"19920105000000","mzdbjbs":"","shbzhm":"370687199201050041","mzddyy":"","zysm":"","grbh":"370687199201050041","cbdsbh":"","ReadCardType":"read_card","Rsbjgbh":"000000","RareaType":"本地","dzpzewm":"4243803529659183948801370000"}}
        if (+res.errorCode === 0) {
            if (res.result) {
                this.handleVoucherInfo(this.state.cardType, res.result, this.state.callback, res.result, this.state.readCardCode);
            } else {
                message.warn('未获取到反参');
                this.setState({ cardShow: false });
            }
        } else {
            message.warn(res.errorMessage);
            this.setState({ cardShow: false });
        }
    };

    GetPatInfoByCardNoThis = (cardTypeID, cardNo, callback, number = '') => {
        let data = {
            params: [{
                cardTypeID: cardTypeID,
                cardNo: cardNo,
                number: number
            }]
        };
        var cardObj = {};
        cardObj.cardTypeID = cardTypeID;
        cardObj.cardNo = cardNo;
        $http.post("urlS", this, {
            code: "03040004",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    cardObj.patInfo = res.data
                    callback(cardObj)
                } else {
                    callback(cardObj)
                }
                this.setState({ cardShow: false });
            }
        })
    }

    // 返回社保卡基本信息
    getInsuPatInfo = (cardTypeID, result) => {
        const baseinfo = result.output.baseinfo;
        let cardObj = {};
        cardObj.cardTypeID = cardTypeID;
        cardObj.cardNo = baseinfo.certno;
        cardObj.patInfo = {
            patNo: '',
            patCredTypeCode: '01',
            patTypeID: '4', //YB
            patCredNo: baseinfo.certno,
            patName: baseinfo.psn_name,
            patSexCode: baseinfo.gend,
            patAge: Math.floor(baseinfo.age) + "",
            patBirthDateTime: baseinfo.brdy
        }
        if (result.selectedInsuInfo?.insuplc_admdvs) {
            let admdvs = this.parseInsuPlace(result.selectedInsuInfo.insuplc_admdvs);
            cardObj.patInfo = { ...cardObj.patInfo, ...admdvs };
        }
        return cardObj;
    }

    // 解析社保参保地为省市县
    parseInsuPlace = (insuplc_admdvs) => {
        var obj = {}
        if (insuplc_admdvs && insuplc_admdvs.length == 6) {
            obj.patPresentProvinceCode = insuplc_admdvs.substring(0, 2) + "0000";
            obj.patPresentCityCode = insuplc_admdvs.substring(0, 4) + "00";
            obj.patPresentAreaCode = insuplc_admdvs;
        }
        return obj;
    }

    //电子凭证查询病人信息
    handleVoucherInfo(cardTypeID, cardNo, callback, result, readCardCode) {
        var params = {
            params: [{
                medVoucherInfo: result
            }]
        };
        $http.post('urlDeault', this, {
            code: readCardCode || "15020001",
            data: params,
            success: function (res) {
                console.log('15020001：', res);
                if (+res.errorCode === 0) {
                    var patInfo = result?.patientInfo
                    if (res.result?.patNo == '' && patInfo?.output) {
                        //新卡返回卡信息
                        var data = this.getInsuPatInfo(cardTypeID, patInfo);
                        callback(data);
                        return;
                    }

                    this.GetPatInfoByCardNoThis(cardTypeID, '', callback, res.result?.patNo)
                } else {
                    message.error('失败：' + res.errorMessage);
                }
            }
        });
    }

    PayByCard = (PayReasonDr, callback) => {
        const userData = sessionStorage.userData ? JSON.parse(sessionStorage.userData) : {}
        const hospID = userData.hospID
        let data = {
            params: [{
                hospID: hospID,
                payReasonID: PayReasonDr || '', // 结算类型
            }]
        }
        $http.post("urlS", this, {
            code: "05210036",
            data: data,
            success: function (res) {
                if (res.errorCode === '0') {
                    let dllInput = `{"inParams":"${res.readCardData}","iType":"01"}`;
                    let dllPath = 'ReadCard/ReadYBCard.dll'
                    let className = 'ReadYBCard.SSCard'
                    let funcName = 'iReadCardBas'

                    let dataGet = 'input={"inputDir":"' + dllPath + '","clsName":"' + className + '","funcName":"' + funcName + '","dllInput":' + dllInput + '}'
                    let that = this
                    fetchJsonp('http://127.0.0.1:62534/XYSWCFService/DynamicLoadingDLL?' + '&' + dataGet, {
                        jsonpCallback: 'JsonCallback',
                    })
                        .then(function (response) {
                            return response.json()
                        }).then(function (json) {
                            //返回卡号
                            json = JSON.parse(json)
                            if (json.errorCode === "0") {
                                message.success('读卡成功');
                                callback(json);

                            } else {
                                message.error(json.errorMessage);
                            }
                        }).catch(function (ex) {
                            that.setState({
                                visibleIp: true
                            })
                            return false
                        })
                } else {
                    message.error('失败：' + res.errorMessage);
                }
            }
        })
    }

    render() {
        return (
            <div>
                <Modal
                    title="请输入医保卡号或扫描电子凭证医保码"
                    visible={this.state.cardShow}
                    onOk={() => this.cardYBInputSure()}
                    onCancel={() => this.setState({ cardShow: false })}
                >
                    <div>
                        电子凭证:<Input placeholder="请扫描电子凭证医保码回车" value={this.state.qrCode} onChange={(e) => this.onqrCodeChange(e)} onPressEnter={() => this.cardYBInputSure()}></Input>
                    </div>
                    <div>
                        区域类型:
                        <Radio.Group style={{ marginLeft: '15px' }} onChange={(e) => { this.onAreaTypeChange(e) }} value={this.state.areaType}>
                            <Radio value='本地'>本地</Radio>
                            <Radio value='省内'>省内</Radio>
                            <Radio value='跨省'>跨省</Radio>
                            <Radio value='省直'>省直</Radio>
                        </Radio.Group>
                    </div>
                    {/** 增加电子凭证业务场景选择(后台控制是否需要显示) */}
                    {this.state.ecTokenScenceList.length ? <div>
                        业务场景:<Select style={{ marginLeft: '15px', marginTop: '5px', width: '300px' }} value={this.state.ecTokenScence} onChange={this.ecTokenScenceChange} >
                            {this.state.ecTokenScenceList.map((item, index) => <Option title={item.proKDescripts} key={index} value={item.proKCode}  >{item.proKDescripts}</Option>)}
                        </Select>
                    </div> : ""}
                </Modal>
            </div>
        );
    }
};

export default ReadCard;
