<template>
    <div>
        <div>
            <div class="listBtn">
                <el-button type="primary" class="commonbutton" @click="btnQuery">查询</el-button>
            </div>
            <div class="listBtn">
                <el-button type="primary" class="commonbutton" @click="btnImportResult('pacs')">导入检查结果</el-button>
            </div>
            <div class="listBtn">
                <el-button type="primary" class="commonbutton" @click="btnImportResult('lis')">导入检验结果</el-button>
            </div>
            <div class="listBtn">
                <el-button type="primary" class="commonbutton" @click="btnReport(true)">预览报告</el-button>
            </div>
            <div class="listBtn">
                <el-button type="primary" class="commonbutton" @click="btnReport(false)">打印报告</el-button>
            </div>
            <div class="listBtn">
                <el-button type="primary" class="commonbutton" @click="btnGetReport">领用报告</el-button>
            </div>
            <div class="listBtn">
                <el-button type="primary" class="commonbutton" @click="btnUpReport">上传Web</el-button>
            </div>
        </div>
        <div>
            <!-- 通用进度条 -->
            <el-dialog title="数据处理中……" :visible.sync="elProgress.display" width="600px" height="400" :show-close="false"
                :close-on-click-modal="false" :append-to-body="true">
                <ElProgressOCX />
            </el-dialog>
        </div>
    </div>
</template>
<script>
import moment from "moment";
import { mapState } from "vuex";
import { getapi, postapi, putapi, deletapi } from "@/api/api";
import { arrayExistObj, deepCopy, parseID } from "../../utlis/proFunc";
import ElProgressOCX from "../report/ElProgressOCX.vue";
//import PatientRegisterList from "../doctorCheck/PatientRegisterList.vue";
export default {
    components: {
        //PatientRegisterList,
        ElProgressOCX
    },
    data() {
        return {


        };
    },

    created() { },

    //挂载完成
    mounted() {
        this.dataTransOpts.tableS.patient_register.id = ''
        // this.getPatientRegister(this.dataTransOpts.tableS.patient_register.patientRegisterNo)
    },

    computed: {
        ...mapState(["dict", "elProgress", "dataTransOpts", "patientRegister", "doctorCheck", "sumDoctorCheck", "report"]),
    },

    methods: {
        btnQuery() {
            this.patientRegister.query.times++
        },

        // 导入结果
        btnImportResult(checkType) {
            if (!this.dataTransOpts.tableS.patient_register.id) {
                this.$message.warning({ showClose: true, message: "请先选择记录！" })
                return
            }

            let patientRegisterId = this.dataTransOpts.tableS.patient_register.id
            let url = '/api/app/ImportLisResult/ImportResultByPatientRegisterId'
            switch (checkType) {
                case 'pacs':
                    url = '/api/app/ImportPacsResult/ImportResultByPatientRegisterId'
                    postapi(url, { patientRegisterId })
                        .then(res => {
                            if (res.code > -1) {
                                return postapi('/api/app/ImportElectrocardiogramResult/ImportElectrocardiogramResultByPatientRegisterId', { patientRegisterId })
                            }
                        })
                        .then(res => {
                            if (res && res.code > -1) {
                                this.$message.success({ showClose: true, message: '导入成功！' })
                            }
                        })
                    break;
                default:
                    postapi(url, { patientRegisterId }).then(res => {
                        if (res.code > -1) {
                            this.$message.success({ showClose: true, message: '导入成功！' })
                        }
                    })
                    break;
            }


        },

        //领用体检报告
        btnGetReport() {
            if (!this.dataTransOpts.tableS.patient_register.id) {
                this.$message.warning({ showClose: true, message: "请先选择记录！" })
                return
            }
            this.dataTransOpts.tableS.patient_register.completeFlag = '2'
        },

        //上传报告
        async btnUpReport() {
            if (!this.$peisAPI) {
                this.$message.info({ showClose: true, message: "此功能，需要在壳客户端才可运行！" })
                return
            }

            if (this.dataTransOpts.tableM.patient_register && this.dataTransOpts.tableM.patient_register.length > 0) {
                this.elProgress.display = true;
                this.elProgress.percentage = 0;

                let ReportCode = '0005';
                let token = window.sessionStorage.getItem('token');
                let user = window.sessionStorage.getItem('user');
                let toOutShell = {
                    ReportCode, token,
                    isBuildImage: 'N',
                    IsUploadPdf: 'N',
                    preViewCanPrint: 'Y',
                    BusinessCode: '',
                    Parameters: [
                        { Name: 'printer', Value: user },
                        { Name: 'LTS', Value: 'Y' }, //Y、N   N只看不能打印
                        { Name: "firstPage", Value: "pic/peisReportFirstPage.jpg" },
                        { Name: "pageHeader", Value: "pic/peisReportPageHeader.jpg" },
                        { Name: "pageFooter", Value: "pic/peisReportPageFooter.jpg" },
                        { Name: "orgSign", Value: "pic/orgSign.png" },
                        { Name: 'picExtOne', Value: 'pic/hisLog.jpg' },
                    ],
                    IsHealthReport: 'Y'
                };

                for (let i = 0; i < this.dataTransOpts.tableM.patient_register.length; i++) {

                    let e = this.dataTransOpts.tableM.patient_register[i];
                    this.elProgress.percentage = Math.floor(((i + 1) * 100) / this.dataTransOpts.tableM.patient_register.length);

                    // 调上传接口
                    try {
                        if (e.completeFlag == '3') {
                            toOutShell.BusinessCode = e.patientRegisterId
                            let jsonToOutShell = JSON.stringify(toOutShell)
                            console.log('toOutShell', jsonToOutShell)
                            let res = await this.$peisAPI.upLoadReportPdf(jsonToOutShell)
                            if (JSON.parse(res).code < 0) {
                                console.log('$peisAPI.upLoadReportPdf err', res)
                            } else {
                                // 上传成功 ，更新上传传状态
                                e.isUpload = 'Y'
                                console.log('btnUpReport success', JSON.parse(res))
                            }
                        } else {
                            let patientRegisterId = e.patientRegisterId
                            let res2 = await postapi('/api/app/TransToWebPeis/TransPatientRegisterByPatientRegisterId', { patientRegisterId })
                            if (res2.code == -1) {
                                console.log('TransToWebPeis err', res2)
                            }
                        }

                    } catch (error) {
                        console.log('error', error)
                        this.$message.warning({ showClose: true, message: error });
                    }
                }
                this.elProgress.display = false;

            } else {
                this.$message.warning({ showClose: true, message: "请勾选择记录！" })
                return
            }
        },



        //体检报告
        async btnReport(isPreview) {
            if (!this.dataTransOpts.tableS.patient_register.id) {
                this.$message.warning({ showClose: true, message: "请先选择记录！" })
                return
            }

            if (!this.$peisAPI) {
                this.$message.info({ showClose: true, message: "此功能，需要在壳客户端才可运行！" })
                return
            }

            ///3a0c990e-5756-2dc0-19d5-69a617fe4048
            let ReportCode = '0005';
            if (this.dataTransOpts.tableS.patient_register.isPatientOccupationalDisease == 'Y') ReportCode = '0006'
            let token = window.sessionStorage.getItem('token');
            let user = window.sessionStorage.getItem('user');
            let toOutShell = {
                ReportCode, token,
                isBuildImage: 'N',
                IsUploadPdf: 'N',
                preViewCanPrint: 'Y',
                BusinessCode: this.dataTransOpts.tableS.patient_register.id,
                Parameters: [
                    { Name: 'printer', Value: user },
                    { Name: 'LTS', Value: 'Y' }, //Y、N   N只看不能打印
                    { Name: "firstPage", Value: "pic/peisReportFirstPage.jpg" },
                    { Name: "pageHeader", Value: "pic/peisReportPageHeader.jpg" },
                    { Name: "pageFooter", Value: "pic/peisReportPageFooter.jpg" },
                    { Name: "orgSign", Value: this.dataTransOpts.tableS.patient_register.isPatientOccupationalDisease == 'Y' ? "pic/orgSignOcc.png" : "pic/orgSign.png" },
                    { Name: 'picExtOne', Value: 'pic/hisLog.jpg' },
                    { Name: 'resultSign', Value: 'pic/resultSign.png' },
                ],
            };

            // 总检审核后才能打印
            if (this.dataTransOpts.tableS.patient_register.completeFlag != '3') toOutShell.preViewCanPrint = 'N'
            if (toOutShell.preViewCanPrint == 'Y' && this.dataTransOpts.tableS.patient_register.isAudit == 'N') {
                let sysParmId = "medical_report_print_after_summary_check_is_audit"
                let sysParam = await postapi('/api/app/SysParmValue/GetSysParmValueBySysParmId', { sysParmId })
                if (sysParam.data.toUpperCase() == 'Y') toOutShell.preViewCanPrint = 'N'
            }

            // let res = await postapi(`/api/app/printreport/getpeisreport?PatientRegisterId=${this.patientRegister.patientRegisterId}`)
            // toOutShell.ReportTable = res.data
            let JSONtoOutShell = JSON.stringify(toOutShell)
            console.log('$peisAPI.printPre', JSONtoOutShell)
            if (isPreview) {
                this.$peisAPI.printPre(JSONtoOutShell)
                    .then(res => {
                        if (JSON.parse(res).code < 0) {
                            this.$message.warning({ showClose: true, message: JSON.parse(res).message });
                        }
                    })
                    .catch((err) => {
                        console.log('预览体检报告错误', err)
                        this.$message.warning({ showClose: true, message: `${err}` });
                    });

            } else {
                if (toOutShell.preViewCanPrint == 'N') {
                    this.$message.warning({ showClose: true, message: '未总检或未审核，不可打印报告' })
                    return
                }
                this.$peisAPI.print(JSONtoOutShell)
                    .then(res => {
                        if (JSON.parse(res).code < 0) {
                            this.$message.warning({ showClose: true, message: JSON.parse(res).message });
                        } else {
                            return postapi('/api/app/patientregister/updatepatientregisterreportprinttimesmany', [this.dataTransOpts.tableS.patient_register.id]);
                        }
                    })
                    .then(res => {
                        if (res && res.code < 0) {
                            this.$message.error({ showClose: true, message: `${res.message}` });
                        }
                    })
                    .catch((err) => {
                        console.log('打印体检报告错误', err)
                        this.$message.error({ showClose: true, message: `${err}` });
                    });

            }

        },

        //按条码号查个人数据
        getPatientRegister(patientRegisterNo) {
            if (!patientRegisterNo) return
            postapi('/api/app/patientregister/GetAlreadyRegisterPatientRegisterByNo', { patientRegisterNo })
                .then((res) => {
                    if (res.code > -1) {
                        this.dataTransOpts.tableS.patient_register = deepCopy(res.data)
                    }
                })
        },

    },

    //监听事件()
    watch: {
        // 强制刷新人员登记信息
        "dataTransOpts.refresh.patient_register.S": {
            // immediate:true,
            handler(newVal, oldVal) {
                console.log(`watch 组合项目列表 newVal: ${newVal} oldVal: ${oldVal} patient_register.id: ${this.dataTransOpts.tableS.patient_register.patientRegisterNo}`);
                this.getPatientRegister(this.dataTransOpts.tableS.patient_register.patientRegisterNo)
                // this.dataTransOpts.refresh.register_check.M++
            }
        },
    },
};
</script>
<style scoped>
@import '../../assets/css/global_button.css';

.listBtn {
    margin-top: 10px;
    /*
    text-align: center;
    */
}

.btnClass {
    width: 100px;
}
</style>