<template>
    <div style="margin-left: 10px;">
        <div>
            <el-button type="primary" class="btnClass" @click="prList">人员列表</el-button>
        </div>
        <div>
            <el-button type="primary" class="btnClass" @click="dialogVisibleSetStartDate = true">体检日期</el-button>
        </div>
        <div>
            <el-button type="primary" class="btnClass" @click="btnAddPr">增加人员</el-button>
        </div>
        <div>
            <el-button type="primary" class="btnClass" @click="btnEditPr">编辑人员</el-button>
        </div>
        <div>
            <el-button type="primary" class="btnClass" @click="btnDelPr">删除人员</el-button>
        </div>
        <div>
            <el-button type="primary" class="btnClass" @click="btnPrev">上一人</el-button>
        </div>
        <div>
            <el-button type="primary" class="btnClass" @click="btnNext">下一人</el-button>
        </div>
        <!--
        <div>
            <el-button type="primary" class="btnClass" @click="save">保存结果</el-button>
        </div>
        -->
        <div>
            <el-button type="primary" class="btnClass" @click="edit">修改结果</el-button>
        </div>
        <div>
            <el-button type="primary" class="btnClass" @click="del">删除结果</el-button>
        </div>
        <div>
            <el-button type="primary" class="btnClass" @click="refuseItem" style="font-size:11px;">放弃明细项目检查</el-button>
        </div>
        <div>
            <el-button type="primary" class="btnClass" @click="delItem">删除明细项目</el-button>
        </div>
        <div>
            <el-button type="primary" class="btnClass" @click="unAudit">取消审核</el-button>
        </div>        
        <div>
            <el-button type="primary" class="btnClass" @click="btnCheckHistory">历次结果</el-button>
        </div>
        <div>
            <el-button type="primary" class="btnClass" @click="report">体检报告</el-button>
        </div>
        <div>
            <el-button type="primary" class="btnClass" @click="toSumDoctorCheck">总检</el-button>
        </div>

        <!--
        <div>
            <el-button type="primary" class="btnClass" @click="btnMakeDiagnosis">生成小结</el-button>
        </div> 
        <div>
            <el-button type="primary" class="btnClass" @click="addSummary">新增小结</el-button>
        </div>
        <div>
            <el-button type="primary" class="btnClass" @click="audit">审核</el-button>
        </div>        
        <div>
            <el-button type="primary" class="btnClass">排队</el-button>
        </div>
        -->
        

        <div v-if="doctorCheck.doctorCheckDialogVisible" 
          :style="`border-radius: 10px;border: 1px solid #000;background-color:#FFF; position: absolute;top:70px;right:10px;width:300px;height: ${window.pageHeight - 42 - 5 - 30}px;opacity:1;`">
          
          <PatientRegisterList win="doctorCheck" :winAbsolute="true"/>
          
        </div>

        <!-- 抽屉方式，遮罩层不能操作 
        <el-drawer title="体检人员列表" :visible.sync="doctorCheck.doctorCheckDialogVisible" direction="rtl" 
          :wrapperClosable="false" :modal="false" :size="300">
          <PatientRegisterList win="doctorCheck" />
        </el-drawer>
        -->


        <!-- 体检人员登记 -->
        <el-dialog style="z-index:30001;"
            :title="patientRegister.patientRegisterRd.id ? '体检人员--编辑' : '体检人员--新增'"
            :visible.sync="dialogVisible"
            :close-on-click-modal="false"
            fullscreen 
            >
            <PatientRegisterEdit  style="z-index:30001;"
                :formInitData="formData"
                :editTimes="editTimes"
                :refreshRegister="refreshRegister"
            />
        </el-dialog>
        <el-dialog
            title="设置体检日期" style="z-index:30002;"
            :visible.sync="dialogVisibleSetStartDate"
            :close-on-click-modal="false" :show-close="false"
            width="300px" 
            >
            <div style="padding: 0 20px;">
                <span style="margin-right:5px ;">体检日期</span>
                <el-date-picker v-model="medicalStartDateTemp" type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="出生日期"                    
                    prefix-icon="" size="small" style="width:150px;"/>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisibleSetStartDate = false">取 消</el-button>
                <el-button type="primary" @click="btnSetStartDate">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog
            title="历次结果" 
            :visible.sync="dialogVisibleCheckHistory"
            :close-on-click-modal="false" 
            width="800px" 
            >
            <div style="padding: 0 20px;">
                <el-tabs v-model="tabChoosed">                    
                    <el-tab-pane label="明细结果" name="2">
                        <CheckDetails :patientRegisterId="doctorCheck.prBase.id" />
                    </el-tab-pane>                    
                    <el-tab-pane label="项目对比" name="4">
                        <SumItemsType :patientId="doctorCheck.prBase.patientId" />
                    </el-tab-pane>
                    <el-tab-pane label="横向对比" name="5">
                        <SumItems :patientId="doctorCheck.prBase.patientId" />
                    </el-tab-pane>
                    <el-tab-pane label="历次综述" name="6">
                        <SumHistory :patientId="doctorCheck.prBase.patientId" />
                    </el-tab-pane>
                </el-tabs>
            </div>
        </el-dialog>     
    </div>
</template>
<script>
import { mapState, mapActions, mapMutations} from "vuex";
import { getapi, postapi, putapi, deletapi } from "@/api/api";
import { arrayExistObj,objCopy } from "../../utlis/proFunc";

import PatientRegisterEdit from "../../components/patientRegister/PatientRegisterEdit.vue";
import PatientRegisterList from "./PatientRegisterList.vue";

import CheckDetails from "../../components/sumDoctorCheck/CheckDetails.vue";
import SumItemsType from "../../components/sumDoctorCheck/SumItemsType.vue";
import SumItems from "../../components/sumDoctorCheck/SumItems.vue";
import SumHistory from "../../components/sumDoctorCheck/SumHistory.vue";

import moment from 'moment';

export default {
    components: {
        PatientRegisterEdit,
        PatientRegisterList,
        CheckDetails,
        SumItemsType,
        SumItems,
        SumHistory
    },
    props:["optGrant","addSummary","btnMakeDiagnosis","save","audit","unAudit"],

    data() {
        return {
            medicalStartDate:'',  //设置体检日期
            medicalStartDateTemp:'',  //设置体检日期 临时体检日期 
            medicalStartDateDatas:[], // 设置体检日期 的人员信息登记信息，按登记日期排序 (用于上一人，下一人)

            dialogVisibleSetStartDate:false, //设置体检日期窗口
            editTimes:0,
            nextTodialogVisible:false,  //设置完体检日期是否显示 体检人员登记窗口
            dialogVisible:false,  //体检人员登记窗口
            formData:{
                registerManType:'doctor', //登记人员类型，客服：customer 医生：doctor 支持在医生诊台处理登记人员
                id: "", //id
                photo:'', //照片
                patientId: "00000000-0000-0000-0000-000000000000", //档案号ID 选择了档案就传档案号，未选就传00000-0000...
                patientNo: "", //档案号
                customerOrgId: ["00000000-0000-0000-0000-000000000000"], //单位编号 默认个人 
                customerOrgGroupId: null, //分组
                medicalPackageId: null, //套餐
                patientName: "", //姓名
                birthDate: null, //日期型
                sexId: "U", //性别 默认未知U
                age: null, //年龄
                jobCardNo: "", //工卡号
                medicalCardNo: "", //体检卡号
                maritalStatusId: "9", //婚姻状况 默认未知
                medicalTypeId: null, //体检类别
                personnelTypeId: null, //人员类别
                jobPost: "", //职务
                jobTitle: "", //职称
                salesman: "", //介绍人
                sexHormoneTermId: null, //性激素期限
                isNameHide: "N", //隐藏姓名
                isPhoneFollow: "N", //电话随访
                isVip: "N", //vip客户
                remark: "", //
                isLock: "N", //是否锁住
                completeFlag: "1", //完成标志 0:预登记，1：未检，2：部份已检，3：已总检  【创建编辑时不操作】
                isMedicalStart: "N", //体检开始标志 【创建编辑时不操作】
                patientRegisterNo: "", //条码号 【创建编辑时不操作】
                medicalTimes: 1, //条码号 【创建编辑时不操作】
                organizationUnitId: null, //体检中心
                address: "", //地址
                email: "", //email
                idNo: "", //身份证号
                telephone: "", //电话
                mobileTelephone: "", //手机号
                nationId: null, //民族编号
                birthPlaceId: null, //籍惯（出生地）
                postalCode: "", //邮编
                creatorId: null,
                creationTime: "",
                lastModificationTime: "",
                lastModifierId: null,
                isVipBox: false, //vip客户
                isNameHideBox: false, //隐藏姓名
                isPhoneFollowBox: false, //电话随访
                isLockBox: false, //是否锁住
                customerOrgRegisterId: null,
                isMaxMedicalTimes: 'N',
                medicalStartDate:null,
            }, //单位 记录 目前新增与更新是一致
            formInitData:{},

            medicalStartDateLoadOpts:{  //按体检日期 查询参数
                totalCount:0,        
                skipCount:0,
                maxResultCount:50000,
            },

            displayPrList:false,    //是否显示人员列表
            dialogVisibleCheckHistory:false,  //历次结果
            tabChoosed:'2',
        };
    },

    created() { 
        this.formInitData = Object.assign({},this.formData)
        this.medicalStartDateTemp = new Date()
    },

    //挂载完成
    mounted() {

    },

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

    methods: {
        ...mapActions(["getCustomerOrgGroup"]),
        ...mapMutations(['doctorCheckPrBaseInit']),

        prList() {
            // console.log('this.doctorCheck.doctorCheckDialogVisible', this.doctorCheck.doctorCheckDialogVisible)
            this.doctorCheck.doctorCheckDialogVisible = true
            // console.log('this.doctorCheck.doctorCheckDialogVisible2', this.doctorCheck.doctorCheckDialogVisible)
        },


        
        //设置体检日期
        btnSetStartDate(){
            this.medicalStartDate = this.medicalStartDateTemp
            this.dialogVisibleSetStartDate = false
            if(this.nextTodialogVisible) this.btnAddPr()
        },

        //人员登记
        btnAddPr(){
            // debugger
            if(this.medicalStartDate){
                this.formData = Object.assign({},this.formInitData,{medicalStartDate:moment(this.medicalStartDate).format('yyyy-MM-DD')})                
                this.dialogVisible = true
                this.patientRegister.photo = ''
                setTimeout(() =>{
                    this.editTimes++
                },100)                
            }else{
                this.nextTodialogVisible = true
                this.dialogVisibleSetStartDate = true
            }
        },

        //人员删除
        btnDelPr(){
            if(!this.doctorCheck.prBase.id){
                this.$message.warning("未选中要删除的人员记录")
                return
            }
            let id = this.doctorCheck.prBase.id
            this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
                confirmButtonText: "是",
                cancelButtonText: "否",
                type: "warning",
            }).then(() => {
                //console.log('{patientRegisterIds}',{patientRegisterIds})
                return postapi(`/api/app/patient-register/delete-many`, {patientRegisterIds:[id]})
            }).then((res) => {
                if(res.code != -1){
                    this.$message.success("操作成功！")
                    this.doctorCheckPrBaseInit();
                    let lfind = arrayExistObj(this.medicalStartDateDatas,'id',id)
                    if(lfind > -1) this.medicalStartDateDatas.splice(lfind,1)
                }   
            }).catch((err) => {
                if (err == "cancel") {
                this.$message.info("已取消删除");
                }
            });

        },


        //人员编辑
        btnEditPr() {
            if(!this.doctorCheck.prBase.id){
                this.$message.warning("未选中要编辑的人员记录")
                return
            }

            this.patientRegister.patientRegisterRd = Object.assign({},this.doctorCheck.prBase)
            this.formData = Object.assign({},this.doctorCheck.prBase)
            
            //console.log(this.patientRegister.patientRegisterRd,this.patientRegister.prList)
            this.dialogVisible = true;
            this.editTimes++; //触发表单窗口，数据更新
        },

        // 上一人
        btnPrev(){
            if(!this.medicalStartDate){
                this.$message.warning("请先设置体检日期")
                return
            }
            if(this.medicalStartDateDatas.length == 0) {
                this.$message.warning("当前设置的体检日期，无体检人员信息")
                return
            }

            let lfind = -1
            if(this.doctorCheck.prBase.id){
                lfind = arrayExistObj(this.medicalStartDateDatas,'id',this.doctorCheck.prBase.id)
                if(lfind == 0){
                    this.$message.warning("已是第一个人")
                    return
                }
                if(lfind > - 1) lfind--
            }

            // 未选中，未找到，显示第一人
            if(lfind < 0){
                if(this.medicalStartDateDatas && this.medicalStartDateDatas.length > 0){
                    this.findPR(this.medicalStartDateDatas[0])
                }
            }else{
                if(this.medicalStartDateDatas && this.medicalStartDateDatas.length > 0){
                    this.findPR(this.medicalStartDateDatas[lfind])
                }
            }

        },

        // 下一人
        btnNext(){
            if(!this.medicalStartDate){
                this.$message.warning("请先设置体检日期")
                return
            }
            if(this.medicalStartDateDatas.length == 0) {
                this.$message.warning("当前设置的体检日期，无体检人员信息")
                return
            }            
            let lfind = 0
            if(this.doctorCheck.prBase.id){
                lfind = arrayExistObj(this.medicalStartDateDatas,'id',this.doctorCheck.prBase.id)
                lfind++
            }

            // 未选中，未找到，显示第一人            
            if(this.medicalStartDateDatas.length > lfind){
                this.findPR(this.medicalStartDateDatas[lfind])
            }else{
                this.$message.warning("已是最后一人")
            }
            

        },

        //查询找到相关信息处理
        findPR(rd){
            this.doctorCheck.prBase = Object.assign({},this.doctorCheck.prBase,rd)            
            this.patientRegister.photo = rd.photo
        },

        
        //刷新或添加列表数据
        refreshRegister(patientRegister){
            console.log('编辑/新增的 form :',patientRegister)
            this.doctorCheck.prBase = Object.assign({},patientRegister)
            this.patientRegister.photo = patientRegister.photo
        },

        //修改结果
        edit() {
            let ret = this.optGrant('edit')
            if (ret) {
                this.$message.warning(ret)
                return
            }
            this.doctorCheck.RegisterCheckEdit.completeFlag = '0'
        },

        //删除结果
        del() {
            let ret = this.optGrant('del')
            if (ret) {
                this.$message.warning(ret)
                return
            }

            postapi('/api/app/registercheck/updatecompletemany', [{ registerCheckId: this.doctorCheck.RegisterCheckEdit.id, completeFlag: '0' }])
                .then((res) => {
                    console.log("del", res.data);
                    if (res.code != -1) {
                        this.doctorCheck.RegisterCheckEdit.completeFlag = '0';
                        let lfind = arrayExistObj(this.doctorCheck.RegisterCheckList,'id',this.doctorCheck.RegisterCheckEdit.id)
                        if(lfind > -1) this.doctorCheck.RegisterCheckList[lfind].completeFlag = '0'

                        this.$message.success("操作成功！");
                    }
                });
        },

        //放弃明细项目检查                
        refuseItem() {
            let ret = this.optGrant('refuseItem')
            if (ret) {
                this.$message.warning(ret)
                return
            }
            // console.log('this.doctorCheck.checkItem',this.doctorCheck.checkItem)
            if(!this.doctorCheck.checkItem){
                this.$message.warning("请选择要操作的明细项目")
                return
            }
            if(!this.doctorCheck.checkItem.itemId){
                this.$message.warning("请选择要操作的明细项目")
                return
            }
            
            let lfind = arrayExistObj(this.doctorCheck.checkItemList, 'itemId', this.doctorCheck.checkItem.itemId)
            if (lfind == -1) {
                this.$message.warning("请选择要操作的明细项目")
                return
            }

            this.doctorCheck.checkItemList[lfind].result = "放弃检查"

        },

        //删除明细项目                
        delItem() {
            let ret = this.optGrant('delItem')
            if (ret) {
                this.$message.warning(ret)
                return
            }

            if(!this.doctorCheck.checkItem){
                this.$message.warning("请选择要删除的明细项目")
                return
            }
            if(!this.doctorCheck.checkItem.itemId){
                this.$message.warning("请选择要删除的明细项目")
                return
            }

            let lfind = arrayExistObj(this.doctorCheck.checkItemList, 'itemId', this.doctorCheck.checkItem.itemId)
            if (lfind == -1) {
                this.$message.warning("请选择要删除的明细项目")
                return
            }

            this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
                confirmButtonText: "是",
                cancelButtonText: "否",
                type: "warning",
            }).then(() => {
                return postapi(`/api/app/registercheckitem/deleteregistercheckitem?RegisterCheckId=${this.doctorCheck.checkItem.registerCheckId}&ItemId=${this.doctorCheck.checkItem.itemId}`)
            }).then(res => {
                if (res.code != -1) {
                    this.doctorCheck.checkItemList.splice(lfind, 1);
                    this.doctorCheck.checkItem.itemId = ''
                }
            }).catch((err) => {
                if (err == "cancel") {
                    this.$message.info("已取消");
                }else{
                    this.$message({ type: "error", message: `项目明细删除失败，原因：${err}` });
                }
            });
          
        },

        // 历次结果
        btnCheckHistory() {
            if(!this.doctorCheck.prBase.id) return;
            this.dialogVisibleCheckHistory = true;
        },
        
        //体检报告
        report() {
            
            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,
                preViewCanPrint: this.doctorCheck.prBase.isAudit, //this.sumDoctorCheck.sumPREdit.isAudit
                Parameters: [
                    { Name: 'printer', Value: user },
                    { Name: 'LTS', Value: 'Y' }, //Y、N   N只看不能打印
                    { Name: 'hisLog', Value: 'pic/hisLog.jpg' },
                    { Name: "peisReportFirstPage", Value: "pic/peisReportFirstPage.jpg" },
                    { Name: "peisReportPageHeader", Value: "pic/peisReportPageHeader.jpg" },
                    { Name: "peisReportPageFooter", Value: "pic/peisReportPageFooter.jpg" }
                ],
            };


            postapi(`/api/app/printreport/getpeisreport?PatientRegisterId=${this.doctorCheck.prBase.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));
                    }
                })
                .catch(err => {
                    this.$message.warning(err);
                });

        },
        
        //总检
        toSumDoctorCheck() {
            this.sumDoctorCheck.sumPREdit = Object.assign({},this.doctorCheck.prBase)
            this.$router.push({ path: "/sumDoctorCheck" });
        },
        
    },

    //监听事件()
    watch: {
        //1级单位值改变，分组改变
        "patientRegister.query.CustomerOrgParentId"(newVal, oldVal) {
            console.log(
                "watch patientRegister.query.CustomerOrgParentId newVal：",
                newVal,
                " oldVal：",
                oldVal
            );
            if (newVal != oldVal && newVal !== this.dict.personOrgId) {
                this.getCustomerOrgGroup(newVal);
            }
        },

        // 设置体检日期
        "medicalStartDate":{
            immediate:true,
            handler(newVal,oldVal){
                if(newVal){
                    let body = {
                        customerOrgs: [
                            {
                                startDate: moment(this.medicalStartDate).format('yyyy-MM-DD'),
                                endDate: moment(this.medicalStartDate).format('yyyy-MM-DD'),
                                dateType: '2'  //体检日期
                            }
                        ],
                        maxResultCount: 1000
                    }

                    postapi('/api/patientregister/getpeisrecordlist',body).then(res => {
                        if(res.code != -1) this.medicalStartDateDatas = res.data.items
                    })

                }else{
                    this.medicalStartDateDatas = []
                }
            }
        },
    },
};
</script>
<style scoped>
@import '../../assets/css/global_button.css';

.btnClass {
    margin-top: 1px;
    width: 100px;
    height: 26px;
    padding: 5px 5px; /*原始 默认值 10px 10px */
}
</style>