<template>
    <div>
        <div v-show="checkPagePriv(pagePriv.privs, '人员列表')" class="listBtn">
            <el-button type="primary" class="commonbutton" @click="prList">人员列表</el-button>
        </div>
        <div v-show="checkPagePriv(pagePriv.privs, '医生诊台')" class="listBtn">
            <el-button type="primary" class="commonbutton" @click="toDoctorCheck">医生诊台</el-button>
        </div>
        <div v-show="checkPagePriv(pagePriv.privs, '导入检查结果')" class="listBtn">
            <el-button type="primary" class="commonbutton" @click="btnImportResult('pacs')"
                :disabled="sumBtnDisabled('save')">导入检查结果</el-button>
        </div>
        <div v-show="checkPagePriv(pagePriv.privs, '导入检验结果')" class="listBtn">
            <el-button type="primary" class="commonbutton" @click="btnImportResult('lis')"
                :disabled="sumBtnDisabled('save')">导入检验结果</el-button>
        </div>
        <div v-show="checkPagePriv(pagePriv.privs, '保存')" class="listBtn">
            <el-button type="primary" class="commonbutton" @click="btnSave"
                :disabled="sumBtnDisabled('save')">保存</el-button>
        </div>
        <div v-show="checkPagePriv(pagePriv.privs, '修改')" class="listBtn">
            <el-button type="primary" class="commonbutton" @click="btnEdit"
                :disabled="sumBtnDisabled('edit')">修改</el-button>
        </div>
        <div v-show="checkPagePriv(pagePriv.privs, '取消总检')" class="listBtn">
            <el-button type="primary" class="commonbutton" @click="btnDel"
                :disabled="sumBtnDisabled('del')">取消总检</el-button>
        </div>
        <div v-show="checkPagePriv(pagePriv.privs, '审核')" class="listBtn">
            <el-button type="primary" class="commonbutton" @click="audit" :disabled="sumBtnDisabled('audit')">审核</el-button>
        </div>
        <div v-show="checkPagePriv(pagePriv.privs, '取消审核')" class="listBtn">
            <el-button type="primary" class="commonbutton" @click="unAudit"
                :disabled="sumBtnDisabled('unAudit')">取消审核</el-button>
        </div>
        <!-- 直接放在 建议旁边
        <div class="listBtn">
            <el-button type="primary" class="btnClass" @click="addDiagnosis">疾病诊断</el-button>
        </div>
        -->
        <div v-show="checkPagePriv(pagePriv.privs, '体检报告')" class="listBtn">
            <el-button type="primary" class="commonbutton" @click="btnReport"
                :disabled="sumBtnDisabled('report')">体检报告</el-button>
        </div>
        <div v-show="checkPagePriv(pagePriv.privs, '复查')" class="listBtn">
            <el-button type="primary" class="commonbutton" @click="reCheck"
                :disabled="sumBtnDisabled('reCheck')">复查</el-button>
        </div>
        <div v-show="false" class="listBtn">
            <el-button type="primary" class="commonbutton" @click="intervene"
                :disabled="sumBtnDisabled('intervene')">干预措施</el-button>
        </div>
        <div v-show="checkPagePriv(pagePriv.privs, '职业病')" class="listBtn">
            <el-button type="primary" class="commonbutton" @click="btnOcc"
                :disabled="sumBtnDisabled('btnOcc')">职业病</el-button>
        </div>


        <div v-show="sumDoctorCheck.sumDoctorCheckDialogVisible"
            :style="`z-index:3;border-radius: 10px;border: 1px solid #ddd;background-color:#FFF; position: absolute;top:50px;right:0px;width:300px;height: ${window.pageHeight - 42 - 10}px;opacity:1;`">

            <PatientRegisterList win="sumDoctorCheck" :winAbsolute="true" />

        </div>

        <el-dialog title="职业病" :visible.sync="dialogWin.OccDisease" width="800px" :close-on-click-modal="false"
            :append-to-body="true">
            <OccDisease />
        </el-dialog>

        <!-- 抽屉方式，遮罩层不能操作 
        <el-drawer title="体检人员列表" :visible.sync="sumDoctorCheck.sumDoctorCheckDialogVisible" direction="rtl" 
          :wrapperClosable="false" :modal="false" :size="300">
          <PatientRegisterList :win="sumDoctorCheck" :winAbsolute="false"/>
        </el-drawer>
        -->
        <!-- 直接放在 建议旁边
        <el-drawer title="诊断列表" :visible.sync="sumDoctorCheck.sumDiagnosisVisible" direction="ltr"  :size="300"
          :wrapperClosable="false">
          <SumDiagnosis :patientRegisterId="dataTransOpts.tableS.patient_register.id" />
        </el-drawer>
        -->
    </div>
</template>
<script>

import { mapState } from "vuex";
import { getapi, postapi, putapi, deletapi } from "@/api/api";
import { getPagePriv, checkPagePriv, deepCopy } from "../../utlis/proFunc";

import PatientRegisterList from "../doctorCheck/PatientRegisterList.vue";
import SumDiagnosis from "./SumDiagnosis.vue";
import OccDisease from "../../components/occDisease/OccDisease.vue"
import moment from "moment";

export default {
    components: {
        PatientRegisterList,
        SumDiagnosis,
        OccDisease
    },
    data() {
        return {
            pagePriv: {
                routeUrlorPageName: 'sumDoctorCheck', //当前页面归属路由或归属页面权限名称
                privs: [] // 页面权限
            },
            dialogVisible: false,
            tableData: [
                {
                    col: 'col',
                    details: [{ id: 1, name: '000' }, { id: 2, name: '001' }]
                }
            ],
        };
    },

    created() {
        //获取用户当前页面的权限
        let userPriv = window.sessionStorage.getItem('userPriv')
        if (userPriv) this.pagePriv.privs = deepCopy(getPagePriv(this.pagePriv.routeUrlorPageName))
    },

    //挂载完成
    mounted() {

    },

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

    methods: {

        checkPagePriv,

        prList() {
            this.sumDoctorCheck.sumDoctorCheckDialogVisible = true
        },

        //诊断列表
        addDiagnosis() {
            this.sumDoctorCheck.sumDiagnosisVisible = true
        },

        //to医生诊台
        toDoctorCheck() {
            // this.doctorCheck.prBase = Object.assign({},this.dataTransOpts.tableS.patient_register)
            // this.patientRegister.photo = this.doctorCheck.prBase.photo
            this.$router.push({ path: "/doctorCheck", query: { patient_register: this.dataTransOpts.tableS.patient_register } });
        },

        // 按钮可用
        sumBtnDisabled(btnFlagName) {
            let patientRegister = this.dataTransOpts.tableS.patient_register
            let ret = true

            //' 请选择体检人员'
            if (!patientRegister.id) return ret
            // '人员已锁定，不可执行此操作'
            if (patientRegister.isLock && patientRegister.isLock == 'Y') return ret

            switch (btnFlagName) {
                case 'addSuggtion':
                case 'save':
                    if (patientRegister.completeFlag && patientRegister.completeFlag != '3') ret = false
                    break;
                case 'edit':
                case 'del':
                case 'audit':
                    if (patientRegister.completeFlag && patientRegister.completeFlag == '3' && patientRegister.isAudit != 'Y') ret = false
                    break;
                case 'unAudit':
                case 'reCheck':
                    if (patientRegister.completeFlag && patientRegister.completeFlag == '3' && patientRegister.isAudit && patientRegister.isAudit == 'Y') ret = false
                    break;
                case 'report':
                    ret = false
                    break;
                case 'intervene':
                    if (patientRegister.completeFlag && patientRegister.completeFlag == '3') ret = false
                    break;
                default:
                    ret = false
                    break;
            }
            console.log('sumBtnDisabled btnFlagName, patientRegister,ret', btnFlagName, patientRegister, ret)
            return ret
        },

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

            let url = '/api/app/ImportLisResult/ImportResultByPatientRegisterId'
            switch (checkType) {
                case 'pacs':
                    url = '/api/app/ImportPacsResult/ImportResultByPatientRegisterId'
                    break;
                default:
                    break;
            }

            postapi(url, { patientRegisterId: this.dataTransOpts.tableS.patient_register.id }).then(res => {
                if (res.code > -1) {
                    this.$message.success({ showClose: true, message: '导入成功！' })
                } else {
                    this.$message.error({ showClose: true, message: res.message })
                }
            })
        },

        //保存数据
        btnSave() {

            // //更新总检
            // this.updateSumDoctorCheck();
            // //更新综述       
            // this.saveSummary();
            // //更新建议与诊断     
            // this.saveSuggestion();
            let body = {
                patientRegisterId: this.dataTransOpts.tableS.patient_register.id,
                summaryDoctorId: this.dataTransOpts.tableS.patient_register.summaryDoctorId || null,
                summaryDate: this.dataTransOpts.tableS.patient_register.summaryDate||moment(new Date()).format("yyyy-MM-DD HH:mm:ss"),
                medicalConclusionId: this.dataTransOpts.tableS.patient_register.medicalConclusionId || null,
                sumSummarys: this.sumDoctorCheck.summaryList,
                sumSuggestions: this.sumDoctorCheck.suggestionList
            }

            // 检查综述建议是否同一个人，防止不同人员数据覆盖
            let message = ''
            for (let index = 0; index < this.sumDoctorCheck.summaryList.length; index++) {
                let e = this.sumDoctorCheck.summaryList[index];
                if (!e.patientRegisterId || e.patientRegisterId != this.dataTransOpts.tableS.patient_register.id) {
                    message = "人员ID 与 综述人员ID 不一致"
                    break
                }
            }
            if (message) {
                this.$message.error({ showClose: true, message })
                return
            }

            for (let index = 0; index < this.sumDoctorCheck.suggestionList.length; index++) {
                let e = this.sumDoctorCheck.suggestionList[index];
                if (!e.patientRegisterId || e.patientRegisterId != this.dataTransOpts.tableS.patient_register.id) {
                    message = "人员ID 与 建议人员ID 不一致"
                    break
                }
            }
            if (message) {
                this.$message.error({ showClose: true, message })
                return
            }




            postapi(`/api/app/patientregister/UpdatePatientRegisterSummarySuggestion`, body)
                .then((res) => {
                    if (res.code > -1) {
                        // this.dataTransOpts.tableS.patient_register.completeFlag = '3';
                        this.dataTransOpts.refresh.patient_register.S++
                    }
                })
        },

        //修改结果
        btnEdit() {
            this.dataTransOpts.tableS.patient_register.completeFlag = '2'
        },

        //取消总检
        async btnDel() {
            let tips = false  // 已打印删除提示 
            if (this.dataTransOpts.tableS.patient_register.reportPrintTimes > 0) {
                let sysParmId = "summary_check_cancel_alreay_print_is_prompt"
                let sysParam = await postapi('/api/app/SysParmValue/GetSysParmValueBySysParmId', { sysParmId })
                if (sysParam.data.toUpperCase() == 'Y') tips = true
            }

            let body = {
                patientRegisterId: this.dataTransOpts.tableS.patient_register.id
            }

            if (tips) {
                this.$confirm("已打印过报告， 是否继续取消总检?", "提示", {
                    confirmButtonText: "是",
                    cancelButtonText: "否",
                    type: "warning",
                })
                    .then(() => {
                        return postapi(`/api/app/patientregister/CancelSumCheck`, body)
                    })
                    .then((res) => {
                        if (res.code > -1) {
                            this.dataTransOpts.tableS.patient_register.completeFlag = '2';
                        }
                    })
                    .catch((err) => {
                        if (err != "cancel") {
                            this.$message.info({ showClose: true, message: err });
                        }
                    });

            } else {
                postapi(`/api/app/patientregister/CancelSumCheck`, body)
                    .then((res) => {
                        if (res.code > -1) {
                            this.dataTransOpts.tableS.patient_register.completeFlag = '2';
                        }
                    })
            }







        },

        //审核
        audit() {

            let body = {
                patientRegisterId: this.dataTransOpts.tableS.patient_register.id,
                //auditDoctor: "3fa85f64-5717-4562-b3fc-2c963f66afa6", 
                //auditDate: "string" 不传时，取当前时间
                isAudit: 'Y'
            }

            console.log(`/api/app/patientregister/updatepatientregisterauditordoctor`, body)
            postapi(`/api/app/patientregister/updatepatientregisterauditordoctor`, body)
                .then((res) => {
                    console.log("audit", res.data);
                    if (res.code > -1) {
                        this.dataTransOpts.tableS.patient_register.isAudit = 'Y';
                        // this.dataTransOpts.refresh.patient_register.S++
                    }
                })
                .catch((err) => {
                    this.$message.error({ showClose: true, message: `总检审核失败，原因：${err}` });
                });
        },

        //取消审核
        unAudit() {

            let body = {
                patientRegisterId: this.dataTransOpts.tableS.patient_register.id,
                //auditDoctor: "3fa85f64-5717-4562-b3fc-2c963f66afa6", 
                //auditDate: "string" 不传时，取当前时间
                isAudit: 'N'
            }

            console.log(`/api/app/patientregister/updatepatientregisterauditordoctor`, body)
            postapi(`/api/app/patientregister/updatepatientregisterauditordoctor`, body)
                .then((res) => {
                    console.log("unAudit", res.data);
                    if (res.code != -1) {
                        this.dataTransOpts.tableS.patient_register.isAudit = 'N';
                        // this.$message({ type: "success", message: `取消总检审核成功` });
                        // this.dataTransOpts.refresh.patient_register.S++
                    }
                })
                .catch((err) => {
                    this.$message({ type: "error", message: `取消总检审核失败，原因：${err}` });
                });
        },

        //体检报告
        async btnReport() {

            if (!this.$peisAPI) {
                this.$message.info("此功能，需要在壳客户端才可运行！")
                return
            }
            ///3a0c990e-5756-2dc0-19d5-69a617fe4048
            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',
                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' },
                ],
            };

            // 总检审核后才能打印
            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'
            }

            // postapi(`/api/app/printreport/getpeisreport?PatientRegisterId=${this.dataTransOpts.tableS.patient_register.id}`)
            //     .then((res) => {
            //         if (res.code != -1) {
            //             toOutShell.ReportTable = res.data;
            //             console.log('JSON.stringify(toOutShell)', JSON.stringify(toOutShell));
            //             return this.$peisAPI.printPre(JSON.stringify(toOutShell));
            //         }
            //     })
            toOutShell.BusinessCode = this.dataTransOpts.tableS.patient_register.id
            this.$peisAPI.printPre(JSON.stringify(toOutShell))
                .then(res => {
                    if (res) {
                        let lres = JSON.parse(res)
                        if (lres.code < 0) this.$message.error({ showClose: true, message: lres.message })
                    }
                })
                .catch(err => {
                    this.$message.warning(err);
                });


        },



        //复查
        reCheck() {
            console.log("复查")
        },

        //干预措施
        intervene() {
            console.log("干预措施")
        },

        // 显示职业病
        btnOcc() {
            if (!this.dataTransOpts.tableS.patient_register.id) {
                this.$message.warning({ showClose: true, message: '人员信息尚未保存！' })
                return
            }
            this.dataTransOpts.plus.OccDisease++
            this.dialogWin.OccDisease = true
        },

        //更新总检
        updateSumDoctorCheck() {
            let body = {
                patientRegisterId: this.dataTransOpts.tableS.patient_register.id,
                //summaryDoctor:this.dataTransOpts.tableS.patient_register.summaryDoctor,
                //summaryDate: this.dataTransOpts.tableS.patient_register.summaryDate,
                completeFlag: '3'
            }
            console.log(`/api/app/patientregister/updatepatientregistersummarydoctor`, body)
            postapi(`/api/app/patientregister/updatepatientregistersummarydoctor`, body)
                .then((res) => {
                    console.log("updateSumDoctorCheck", res.data);
                    if (res.code != -1) {
                        this.dataTransOpts.tableS.patient_register.completeFlag = '3';
                        this.$message({ type: "success", message: `总检保存成功！` });
                    }
                })
                .catch((err) => {
                    this.$message({ type: "error", message: `总检保存失败，原因：${err}` });
                });

        },


        //更新综述
        saveSummary() {
            let body = []
            this.sumDoctorCheck.summaryList.forEach(item => {
                delete item.id;
                delete item.summaryFlag;
                delete item.displayOrder;

                item.details.forEach(e => {
                    delete e.sumSummaryHeaderId;
                    delete e.displayOrder;
                })
                body.push(item)
            });
            console.log(`/api/app/sumsummaryheader/createsumsummary`, body)
            if (body.length < 1) return
            postapi(`/api/app/sumsummaryheader/createsumsummary`, body)
                .then((res) => {
                    console.log("saveSummary", res.data);
                    if (res.code != -1) {
                        //this.dataTransOpts.tableS.patient_register.completeFlag = '1';
                    }
                })
                .catch((err) => {
                    this.$message({ type: "error", message: `综述保存失败，原因：${err}` });
                });

        },


        //更新建议      
        saveSuggestion() {
            let body = []
            this.sumDoctorCheck.suggestionList.forEach(item => {
                delete item.id;
                delete item.suggestionFlag;
                delete item.displayOrder;

                item.details.forEach(e => {
                    delete e.sumSuggestionHeaderId;
                    delete e.displayOrder;
                })
                body.push(item)
            });
            console.log(`/api/app/sumsuggestionheader/createsumsuggestion`, body)
            if (body.length < 1) return
            postapi(`/api/app/sumsuggestionheader/createsumsuggestion`, body)
                .then((res) => {
                    console.log("saveSuggestion", res.data);
                    if (res.code != -1) {
                        //this.dataTransOpts.tableS.patient_register.completeFlag = '1';
                    }
                })
                .catch((err) => {
                    this.$message({ type: "error", message: `建议保存失败，原因：${err}` });
                });

        },

        addSummary() {
            if (!this.dataTransOpts.tableS.patient_register.id) {
                alert("请选择检查项目")
                return
            }
            this.doctorCheck.checkSummaryList.push({
                registerCheckId: this.dataTransOpts.tableS.patient_register.id,
                summary: '',
                summaryFlag: 'N',
            })
            this.doctorCheck.checkSuggestionList.push({
                registerCheckId: this.dataTransOpts.tableS.patient_register.id,
                suggestion: '',
            })
        },
    },

    //监听事件()
    watch: {

    },
};
</script>
<style scoped>
@import '../../assets/css/global_button.css';

.listBtn {
    margin-top: 10px;
    margin-left: 10px;
    text-align: center;
}
</style>