<template>
    <div>
        <el-dialog title="结算历史" :visible.sync="cardlist" @close="cardcolsein()" width="width: 90% !important;">
            <el-form ref="ruleForm" :model="ruleForm" label-width="80px" :inline="true">
                <div class="search">
                    <div style="display: flex">
                        <div>
                            <el-form-item label="姓名">
                                <el-input v-model="ruleForm.name"></el-input>
                            </el-form-item>
                            <el-form-item label="身份证号">
                                <el-input v-model="ruleForm.cardid"></el-input>
                            </el-form-item>
                            <el-form-item label="患者id">
                                <el-input v-model="ruleForm.id"></el-input>
                            </el-form-item>
                            <el-form-item label="工号">
                                <el-input v-model="ruleForm.job_number"></el-input>
                            </el-form-item>
                            <el-form-item label="结算时间">
                                <el-date-picker v-model="jsDate" value-format="yyyy-MM-dd" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
                                </el-date-picker>
                            </el-form-item>

                            <el-form-item>
                                <el-button type="primary" @click="search()">查询</el-button>
                                <el-button type="primary" @click="resetForm()">重置</el-button>
                            </el-form-item>
                        </div>
                    </div>
                    <div class="search_middle"></div>
                </div>
            </el-form>
            <div style="padding-bottom: 25px">
                <el-table
                    :data="tableData1"
                    :header-cell-style="{ background: '#49ABF5', color: '#FFFFFF' }"
                    style="width: 100%; overflow-y: auto"
                    tooltip-effect="dark"
                    row-key="id"
                    height="50vh"
                    ref="tableList"
                    @expand-change="expandSelect"
                    @row-click="rowClick"
                >
                    <el-table-column prop="his_patient_id" label="id"> </el-table-column>
                    <el-table-column prop="user_name" label="患者姓名"></el-table-column>
                    <el-table-column prop="id" label="结算号id" width="180"> </el-table-column>
                    <el-table-column prop="amount" label="总金额"> </el-table-column>
                    <el-table-column prop="created_at" label="结算时间" width="150"> </el-table-column>
                    <el-table-column prop="operator_code" label="操作员"> </el-table-column>
                    <el-table-column prop="personal_pay" label="医保个账支付"> </el-table-column>
                    <el-table-column prop="insurance_burden" label="医保负担金额"> </el-table-column>
                    <el-table-column prop="cash_pay" label="院内账户支付"> </el-table-column>
                    <el-table-column label="结算状态">
                        <template slot-scope="scope">
                            <span>{{ scope.row.status.name }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="100">
                        <template slot-scope="scope">
                            <el-button style="margin-bottom: 5px" @click.stop="printcard(scope.row)" type="primary" size="small">重打告知单</el-button>
                            <!-- <el-button style="margin-bottom: 5px"  @click.stop="printcard1(scope.row)" type="primary"
                            size="small">重打告知单</el-button> -->
                            <!-- <el-button style="margin-bottom: 5px"  @click.stop="readcardshow(scope.row)" type="success"
                            size="small">重新尝试本次结算</el-button>
                        <el-button style="margin-bottom: 5px" @click.stop="deletelist(scope.row)" type="danger"
                            size="small">撤销本次结算</el-button> -->
                        </template>
                    </el-table-column>
                </el-table>
                <pagination v-show="total > 0" :total="total" :page.sync="pageInfo.page" :limit.sync="pageInfo.limit" @pagination="desali()" />
            </div>
        </el-dialog>
        <el-dialog title="选择卡类型" :visible.sync="yibaoshow" width="35%">
            <img :src="logo" style="display: block; margin: -50px auto 0px" alt="logo" />
            <el-form :model="yibaoinfo" :inline="true" @submit.native.prevent>
                <div style="text-align: center">
                    <el-form-item label="卡类型">
                        <el-radio-group v-model="yibaoinfo.cardtype">
                            <el-radio label="02">身份证</el-radio>
                            <el-radio label="03">社会保障卡</el-radio>
                            <el-radio label="00">就诊卡</el-radio>
                            <el-radio label="01">电子医保凭证</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </div>
                <div style="text-align: center">
                    <el-input
                        v-if="yibaoinfo.cardtype == '02'"
                        v-model="shenfenzheng"
                        type="text"
                        placeholder="请输入患者卡号"
                        @keyup.enter.native="queren"
                        ref="input"
                        style="width: 300px"
                    ></el-input>
                </div>
                <div style="text-align: center">
                    <el-input
                        v-if="yibaoinfo.cardtype == '01'"
                        v-model="adminpingzhengma"
                        type="text"
                        placeholder="请输入患者卡号"
                        @keyup.enter.native="queren"
                        ref="input"
                        style="width: 300px"
                    ></el-input>
                </div>
                <div style="text-align: center">
                    <el-input v-if="yibaoinfo.cardtype == '00'" v-model="jiuzhencard" type="text" placeholder="请输入患者卡号" @keyup.enter.native="queren" ref="input" style="width: 300px"></el-input>
                </div>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="yibaoshow = false">取 消</el-button>
                <el-button type="primary" @click="queren">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { settlement_history, pdxq, jsxx, printmis, mzxxs, mzxx } from '@/api/mzSFC'
import { getPatientInfo } from '@/api/patient'
import { getPatientInfo2 } from '@/api/jiesuan'
import printProof from '../../utils/print_proof'
import printProof2 from '../../utils/print_proofZF'
import getLodop from '../../assets/js/LodopFuncs'
export default {
    name: 'SelectCard',
    props: {
        cardlistdata: null,
        cardlist: Boolean,
        flag: String,
        xzbz: String,
    },
    data() {
        return {
            jsDate: [],
            total: 0,
            pageInfo: {
                page: 1,
                limit: 10,
            },
            shenfenzheng: '',
            ruleForm: {
                name: '',
                cardid: '',
                id: '',
                job_number: localStorage.getItem('jobNumber') ?? '',
            },
            channel: '',
            yibaoinfo: {
                sfzhm: '',
                idcard: '',
                cardtype: '02',
                cardno: '',
                channel: 'local',
            },
            logo: require('@/assets/logo/CardReader.gif'),
            yibaoshow: false,
            patientinfo: [],
            expands: [],
            tableData1: [],
            adminpingzhengma: '',
            jiuzhencard: '',
            tableData: [],
            loading: false,
            patientInfo: {},
            patientinf: {},
        }
    },

    created() {
        // this.desali()
    },
    watch: {
        cardlist: {
            deep: true,
            handler(to) {
                if (to == true) {
                    this.desali()
                }
            },
        },
    },
    mounted() {
        this.socketInit()
    },
    methods: {
        search() {
            this.desali()
        },
        resetForm() {
            this.ruleForm.name = ''
            this.ruleForm.cardid = ''
            this.ruleForm.id = ''
            this.ruleForm.job_number = ''
            this.jsDate = []
            this.desali()
        },
        socketInit() {
            this.wj = new WebSocket('ws://127.0.0.1:6932/')
            this.wj.onopen = function () {}
            this.wj.onmessage = this.onmessagecard
            this.wj.onclose = function () {}
        },
        queren() {
            this.wj.send('{ "MethodName": "OpenDevice" }')
            if (this.yibaoinfo.cardtype == '02') {
                // TODO: 输入框
                // FIXME: 要修改的东西ASDASDAS
                //读身份证
                if (this.shenfenzheng != '') {
                    this.yibaoinfo.cardno = this.shenfenzheng
                    this.getmzxx('1')
                } else {
                    this.wj.send('{ "MethodName": "OpenDevice" }')
                    this.wj.send('{ "MethodName": "ReadIDCard"}')
                }

                //没卡就手写传卡号
            } else if (this.yibaoinfo.cardtype == '03') {
                //读医保卡
                this.wj.send('{ "MethodName": "OpenDevice" }')
                this.wj.send('{ "MethodName": "ReadSSSECard" }')
                // TODO:
                // FIXME: 要修改的东西ASDASDAS
            } else if (this.yibaoinfo.cardtype == '01') {
                this.getmzxx('3')
            } else if (this.yibaoinfo.cardtype == '00') {
                this.getmzxx('4')
            }
            this.carddialogFormVisible = false
        },
        onmessagecard(evt) {
            let res = JSON.parse(evt.data)
            // 赋值调接口
            if (res.MethodName == 'ReadIDCard' && res.RespCode == 0) {
                // 身份证读取
                this.yibaoinfo.cardno = res.RespData.CardId
                this.getmzxx('1')
            } else if (res.MethodName == 'ReadSSSECard' && res.RespCode == 0) {
                // 社保卡读取
                if (this.yibaoinfo.channel == 'offsite') {
                    this.yibaoinfo.cardno = res.RespData.sfzh
                } else {
                    this.yibaoinfo.idcard = res.RespData.CardNo
                }
                this.yibaoinfo.xm = res.RespData.xm
                this.yibaoinfo.p_sbm = res.RespData.ksbm
                this.yibaoinfo.sfzhm = res.RespData.sfzh
                this.getmzxx('2')
            } else {
                return false
            }
        },
        getmzxx(e) {
            if (e == '1') {
                this.param = {
                    grbh: this.yibaoinfo.cardno,
                    p_xzbz: 'C',
                    yltclb: '0',
                    channel: this.patientinf.channel,
                    card_type: this.yibaoinfo.cardtype,
                    from_web: '1',
                }
                mzxx(this.param)
                    .then(response => {
                        this.patientInfo = response.data
                        this.recardfun(response.data)
                        this.yibaoshow = false
                    })
                    .finally(() => {
                        this.yibaoshow = false
                    })
            }
            if (e == '2' && this.yibaoinfo.channel == 'offsite') {
                this.param = {
                    grbh: this.yibaoinfo.cardno,
                    p_xzbz: 'C',
                    yltclb: '0',
                    channel: this.patientinf.channel,
                    card_type: '02',
                    from_web: '1',
                }
                mzxx(this.param)
                    .then(response => {
                        this.patientInfo = response.data
                        this.recardfun(response.data)
                        this.yibaoshow = false
                    })
                    .finally(() => {
                        this.yibaoshow = false
                    })
            }
            if (e == '2' && this.yibaoinfo.channel != 'offsite') {
                this.param = {
                    p_xm: this.yibaoinfo.xm,
                    p_sbm: this.yibaoinfo.p_sbm,
                    p_gfbb: '03',
                    p_shbzhm: this.yibaoinfo.sfzhm,
                    p_kh: this.yibaoinfo.idcard,
                    channel: this.patientinf.channel,
                    p_ewm: '',
                    p_dzpzywm: '301',
                    card_type: this.yibaoinfo.cardtype,
                    from_web: '1',
                }
                mzxxs(this.param)
                    .then(response => {
                        this.patientInfo = response.data
                        this.recardfun(response.data)
                        this.yibaoshow = false
                    })
                    .finally(() => {
                        this.yibaoshow = false
                    })
            }
            if (e == '3') {
                this.param = {
                    p_xm: this.yibaoinfo.xm,
                    p_sbm: this.yibaoinfo.p_sbm,
                    p_gfbb: '03',
                    p_shbzhm: this.yibaoinfo.sfzhm,
                    p_kh: this.yibaoinfo.idcard,
                    channel: this.patientinf.channel,
                    p_ewm: this.adminpingzhengma,
                    p_dzpzywm: '301',
                    card_type: this.yibaoinfo.cardtype,
                    from_web: '1',
                }
                mzxxs(this.param)
                    .then(response => {
                        this.patientInfo = response.data
                        this.recardfun(response.data)
                        this.yibaoshow = false
                    })
                    .finally(() => {
                        this.yibaoshow = false
                    })
            }
            if (e == '4') {
                this.param = {
                    grbh: this.jiuzhencard,
                    p_xzbz: 'C',
                    yltclb: '0',
                    channel: this.patientinf.channel,
                    card_type: this.yibaoinfo.cardtype,
                }
                mzxx(this.param)
                    .then(response => {
                        this.patientInfo = response.data
                        this.recardfun(response.data)
                        this.yibaoshow = false
                    })
                    .finally(() => {
                        this.yibaoshow = false
                    })
            }
            this.yibaoshow = false
        },
        readcardshow(e) {
            this.patientinf = e
            this.yibaoshow = true
        },
        round(num, decimals) {
            const factor = Math.pow(10, decimals)
            return Math.round(num * factor) / factor
        },
        recardfun(e) {
            let x = {
                cache_uuid: e.cache_uuid,
                his_pay_fee_nos: this.patientinf.his_pay_fee_nos,
                patient_id: this.patientinf.patient.his_patient_id,
                is_pre: 0,
                grzhzf: this.patientinf.grzhzf,
                gjzhzf: this.patientinf.gjzhzf,
                his_deduct_amount: this.patientinf.his_deduct_amount,
            }
            jsxx(x)
                .then(response => {
                    const _this = this
                    this.$message.success('结算成功')
                    const jshidprint = response.data.jshid
                    setTimeout(function () {
                        _this.printcard(jshidprint)
                    }, 2000)

                    //刷新列表
                    pdxq({
                        zfbl: 'auto',
                        rqlb: this.patientCard.rqlb,
                        channel: this.patientCard.channel,
                        his_patient_id: this.patientCard.patientId,
                    })
                        .then(response => {
                            this.tableData.cost = response.data
                            this.tableData.costs = response.data
                            this.tylist = response.data
                            this.tiles(this.tylist)
                        })
                        .finally(res => {
                            this.loading = false
                        })
                })
                .finally(() => {
                    // this.$message.error('结算失败')
                    this.loadingapplyList = false
                    this.dialogVisible = false
                    this.fullscreenLoading = false
                    this.yibaoshow = false
                })
        },
        // 每次只展示一行
        expandSelect(row, expandedRows) {
            // 当没有展开行时
            if (expandedRows.length > 0) {
                // 先清空展开行数组
                this.expands = []
                // 把当前行的id放到展开行数组中（data中getRowKeys获取的是什么这里就push什么）
                this.expands.push(row.id)
            } else {
                // 清空存放目前展开行的数组
                this.expands = []
            }
        },

        timestampToTime(times) {
            let time = times[1]
            let mdy = times[0]
            mdy = mdy.split('/')
            let month = parseInt(mdy[0])
            let day = parseInt(mdy[1])
            let year = parseInt(mdy[2])
            return year + '-' + month + '-' + day + ' ' + time
        },
        printcard(e) {
            const _this = this
            console.log(e)

            printmis({
                channel: '3',
                patient_id: e.his_patient_id,
                settle_id: e.jshid,
            })
                .then(response => {
                    this.$message({
                        message: response.message,
                        type: 'success',
                    })

                    let time = new Date()
                    let nowTime = time.toLocaleString('sv-SE')
                    let text = ''
                    let textend = ''
                    let texttitle = ''
                    if (response.data.settle_fees != null) {
                        for (let index = 0; index < response.data.settle_fees.length; index++) {
                            texttitle =
                                `<div ><span style="color: black;font-weight: 700">` +
                                response.data.settle_fees[index].address +
                                `(` +
                                response.data.settle_fees[index].site +
                                `)</span></div>
                           `
                            let textList = ''
                            for (let indexs = 0; indexs < response.data.settle_fees[index].list.length; indexs++) {
                                const element = response.data.settle_fees[index].list[indexs]
                                textList =
                                    textList +
                                    `<div style='font-size: 13px;position: relative;'>
							        <div class="conline" style='width:60%;'>` +
                                    element.item_name +
                                    `</div>
							        <div class="conline" style=' position: absolute;right: 60px;top: 0px;'>` +
                                    element.qty +
                                    `</div>
							        <div class="conline" style=' position: absolute;right: 0px;top: 0px;'>` +
                                    element.total +
                                    `元</div>
						            </div>`
                            }

                            text = text + texttitle + `<div style="margin-bottom:10px">` + textList + `</div>`
                        }
                    }
                    textend = `<div class="btnborder">` + text + `</div>`
                    let user =
                        `
                 <!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<style>
		* {
			padding: 0px;
			margin: 0px;
		}

		.feiyong {
			font-size: 18px;
			display: flex;
			justify-content: space-between;
		}

		.zhong {
			text-align: center;
			width: 100%
		}
		.money{
			position:absolute;right: 0px;
		}
		.btnborder{
			border-bottom: 1px gray solid;
			padding-bottom: 10px;
			margin-bottom: 10px;
		}
		.conline{
			line-height: 25px;
		}
	</style>
	<body>
		<div style="margin-left:5px; width: 250px;margin-bottom: 10px;">
				<div class="zhong"><span style="font-size: 20px;font-weight: 600;">山东省第二人民医院</span>
				</div>
				<div class="zhong btnborder"><span style="font-size: 20px;font-weight: 600;">缴费成功凭条<span>
				</div>
				<div style="margin:-5px 0px 0px 18px;position: relative">
					<div class="conline"><span>姓名:</span><span class="money" >${response.data.patient.name}</span></div>
                      <div class="conline"><span>性别:</span><span class="money">${response.data.patient.sex}</span></div>
                    <div class="conline"><span>年龄:</span><span class="money">${response.data.patient.age}</span></div>
					<div class="conline"><span>就诊卡号：</span><span class="money">${response.data.id_card}</span></div>
					<div class="conline"><span>交易方式:</span><span class="money">${response.data.trade_type}</span></div>
                    <div class="conline"><span>开单医师:</span><span class="money">${response.data.doctor_name}</span></div>
					<div class="conline" style="${
                        response.data.patient_burden != 0 && (response.data.patient_burden != '0.00') == false ? 'display:none' : 'display:block'
                    }"><span>个人负担金额：</span><span class="money"  >${response.data.patient_burden}元</span></div>
					<div class="conline" style="${
                        (response.data.insurance_burden != 0 && response.data.insurance_burden != '0.00') == false ? 'display:none' : 'display:block'
                    }"><span>医保负担金额：</span><span class="money"  >${response.data.insurance_burden}元</span></div>
					
                    <div class="conline" style="${
                        (response.data.personal_pay_syd != 0 && response.data.personal_pay_syd != '0.00') == false ? 'display:none' : 'display:block'
                    }"><span>省异地个帐支付：</span><span class="money" >${response.data.personal_pay_syd}元</span></div>
					
                    <div class="conline" style="${
                        (response.data.cash_pay != 0 && response.data.cash_pay != '0.00') == false ? 'display:none' : 'display:block'
                    }"><span>院内账户支付：</span><span class="money"  >${response.data.cash_pay}元</span></div>
                    
                    <div class="conline" style="${
                        (response.data.personal_pay != 0 && response.data.personal_pay != '0.00') == false ? 'display:none' : 'display:block'
                    }"><span>医保账户支付：</span><span class="money"  >${response.data.personal_pay}元 </span></div>
                    
                    <div class="conline" style="${
                        (response.data.family_pay != 0 && response.data.family_pay != '0.00') == false ? 'display:none' : 'display:block'
                    }"><span>共济账户支付：</span><span class="money">${response.data.family_pay}元</span></div>
					<div class="btnborder conline"><span>费用合计：</span><span class="money">${response.data.amount}元</span></div>
			` +
                        textend +
                        `
					<div><span>打印时间：</span><span>${nowTime}</span>
					</div>
                    <div style='height:50px'><span>结算时间：</span><span>${response.data.js_date}</span> </div>
				</div>
			</div>
	</body>
</html>
                 `
                    var LODOP = getLodop()
                    if (LODOP) {
                        printProof(user)
                        this.$message({
                            message: '打印成功',
                            type: 'success',
                        })
                    } else {
                        this.$message({
                            message: '结算成功！打印驱动异常！',
                            type: 'warning',
                        })
                    }
                })
                .finally(() => {})
        },
        resure(e) {
            var x = {
                cache_uuid: this.patientInfo.cache_uuid,
                his_pay_fee_nos: this.cost_id,
                patient_id: this.tableData.patient.id,
                is_pre: 0,
                // pre_id: this.bxxxinfo.id,
                grzhzf: this.bxxxinfo.grzhzf,
                his_deduct_amount: this.bxxxinfo.his_deduct_amount,
            }
            jsxx(x)
                .then(response => {
                    this.$message.success('结算成功')
                    this.dialogVisible = false
                    this.loadingapplyList = false
                    this.fullscreenLoading = false
                })
                .finally(() => {
                    // this.$message.error('结算失败')
                    this.loadingapplyList = false
                    this.fullscreenLoading = false
                })
        },
        deletelist(e) {
            if (e.his_success == true) {
                this.$message({
                    message: '当前结算已完成，不允许在此撤销结算',
                    type: 'error',
                })
                return false
            }
            window.location.href = '/yibaomanager/refoundSFC?a=' + e.jshid + '&s=1'
        },
        cardcolsein() {
            this.$emit('cardcolsein', false)
        },
        desali() {
            this.tableData1 = []
            this.param = {
                ...this.pageInfo,
                user_name: this.ruleForm.name,
                id_card: this.ruleForm.cardid,
                his_patient_id: this.ruleForm.id,
                operator_code: this.ruleForm.job_number,
                start_time: this.jsDate[0] ? this.jsDate[0]+' 00:00:00' : '',
                end_time: this.jsDate[1] ? this.jsDate[1]+' 23:59:59' : '',
                // ...this.ruleForm
            }
            settlement_history(this.param)
                .then(response => {
                    this.tableData1 = response.data
                })
                .finally(() => {})
        },
        rowClick(row) {
            //点击行时展开收起
            pdxq({
                his_patient_id: row.patient.his_patient_id,
            })
                .then(response => {
                    this.patientinfo = response.data
                    this.$refs.tableList.toggleRowExpansion(row)
                })
                .finally(() => {})
        },
        load(tree, treeNode, resolve) {
            setTimeout(() => {
                resolve([
                    {
                        id: 32,
                        date: '2016-05-01',
                        name: '王小虎',
                        address: '上海市普陀区金沙江路 1519 弄',
                    },
                ])
            }, 1000)
        },
    },
}
</script>

<style>
.el-dialog:not(.is-fullscreen) {
    margin-top: 3vh !important;
}
.el-dialog {
    width: 90%;
}

.el-table::before {
    height: 0;
}
</style>
