<!--  添加&修改病历详情  -->
<template>
    <div class="medicalHistory">
        <!-- 个人信息 -->
        <div class="patientInfo">
            <van-image
                :src="patientInfo.avatorImg?patientInfo.avatorImg:require('@/assets/images/default.png')"
                width="1rem"
                height="1rem"
                fit="cover"
                round
                class="img"
            />
            <div class="name-info">
                <span class="name">{{patientInfo.name}}</span>
                <van-tag
                    type="danger"
                    style="font-size:.22rem;display:block;width:fit-content;padding:.05rem .1rem;"
                    text-color="white"
                >{{patientInfo.UserRelationship|filterRelation}}</van-tag>
            </div>
        </div>

        <!-- 诊断结果 -->
        <div class="medicalResult mt-3">
            <div>
                <span class="bolder">诊断结果</span>
                <input type="text" v-model="patientInfo.result" placeholder="请输入诊断结果（必填）" />
            </div>
            <div>
                <span class="bolder">诊断时间</span>
                <span
                    v-if="patientInfo.time"
                    @click="dateShow=true"
                >{{patientInfo.time | filterTime}}</span>
                <span v-else @click="dateShow=true">请选择日期（必填）</span>
            </div>
        </div>

        <!-- 医嘱 病情描述 -->
        <div class="doctorAdvice mt-3">
            <div>
                <span class="bolder">医嘱</span>
                <input type="text" v-model="patientInfo.advice" placeholder="请输入医嘱" />
            </div>
            <div>
                <span class="bolder">病情描述</span>
                <input type="text" v-model="patientInfo.description" placeholder="请输入病情描述" />
            </div>
        </div>

        <!-- 诊断医生 -->
        <div class="medicalDoctor mt-3">
            <div>
                <span class="bolder">诊断医生</span>
                <input type="text" v-model="patientInfo.doctor" placeholder="请输入医生" />
            </div>
            <div>
                <span class="bolder">医生职称</span>
                <!-- DropdownMenu 下拉菜单组件 -->
                <van-dropdown-menu class="selectTitles" :overlay="false" direction="up">
                    <van-dropdown-item
                        v-model="patientInfo.DoctorAlias "
                        :options="options"
                        @change="changeTitles"
                    />
                </van-dropdown-menu>
            </div>
            <div>
                <span class="bolder">诊断科室</span>
                <span
                    @click="departmentShow=true"
                    v-if="patientInfo.departments!==''"
                >{{patientInfo.departments}}</span>
                <span @click="departmentShow=true" v-else style="color:#757575;">选择科室</span>
            </div>
            <div>
                <span class="bolder">诊断医院</span>
                <!-- <input type="text" v-model="patientInfo.hospital" placeholder="医院名称" /> -->
                <span
                    @click="HospitalShow=true"
                    v-if="patientInfo.hospital!==''"
                >{{patientInfo.hospital}}</span>
                <span @click="HospitalShow=true" v-else style="color:#757575;">医院名称</span>
            </div>
        </div>

        <!-- 附件 -->
        <div class="enclosure">
            <div class="title">病历附件（处方单，检查结果等图片）</div>
            <div class="content-img">
                <!-- 图片上传 最大值为5M-->
                <van-uploader
                    v-model="patientInfo.medicalHistoryImg"
                    preview-size="1.12rem"
                    :after-read="afterRead"
                    :max-count="5"
                    @delete="deleteImage"
                />
            </div>
        </div>

        <!-- btn -->
        <div class="button" @click="saveMedicalHistory">保存</div>

        <!-- 日期选择 -->
        <van-popup v-model="dateShow" position="bottom" round>
            <van-datetime-picker
                v-model="currentTime"
                type="date"
                :max-date="MaxDate"
                :min-date="MinDate"
                :formatter="formatterDate"
                @confirm="confirmDate"
                @cancel="dateShow=false"
            />
        </van-popup>
        <div style="display:none">{{departmentText}}</div>

        <!-- 选择科室 -->
        <van-popup v-model="departmentShow" get-container="body" position="bottom">
            <ChooseDepartment @cancel="departmentShow=false" @confirm="confirmDepartment"></ChooseDepartment>
        </van-popup>

        <!-- 选择医院 -->
        <van-popup
            v-model="HospitalShow"
            get-container="body"
            position="bottom"
            style="height:100%"
        >
            <ChooseHospital @cancel="HospitalShow=false" @confirm="confirmHospital"></ChooseHospital>
        </van-popup>
    </div>
</template>
<script>
    import ChooseDepartment from "@/components/ChooseDepartment.vue"; //选择科室
    import ChooseHospital from "@/components/ChooseHospital.vue"; //选择医院
    export default {
        name: "alterAddMedicalHistory",
        data() {
            return {
                MaxDate: new Date(),
                MinDate: new Date("1970/01/01 00:00:00"),
                // 个人信息
                patientInfo: {
                    avatorImg: "", //个人头像
                    name: "", //姓名
                    relation: "", // 关系
                    UserRelationship: 0, // 关系id
                    result: "", //诊断结果
                    time: "", //时间
                    advice: "", //医嘱
                    description: "", //病情描述
                    doctor: "", //医生
                    DoctorAlias: 0, //医生职称
                    departments: "", //科室
                    departmentsId: -1, //诊断科室id
                    hospital: "", //医院
                    familyMemberID: "", //病人id
                    /** 病历详情图片 */
                    medicalHistoryImg: []
                },
                id: null, //病历id

                /** 日期选择参数 on */
                dateShow: false, //是否显示
                currentTime: new Date(),
                /** 日期选择参数 off */

                /** DropdownMenu 下拉菜单医生职称组件参数 */
                options: [
                    {
                        text: "选择职称",
                        value: 0
                    },
                    {
                        text: "主任医生",
                        value: 1
                    },
                    {
                        text: "副主任医生",
                        value: 2
                    },
                    {
                        text: "主治医生",
                        value: 3
                    },
                    {
                        text: "医师",
                        value: 4
                    }
                ],

                /** 选择科室 on*/
                departmentShow: false,
                departmentList: [], //科室列表
                /** 选择科室  off*/

                /** 选择医院 on*/
                HospitalShow: false,
                /** 选择医院 off */

                /** 图片上传 on */
                fileList: [
                    // { url: "https://img.yzcdn.cn/vant/cat.jpeg" } // Uploader 根据文件后缀来判断是否为图片文件
                    // { url: "https://cloud-image", isImage: true }
                    // 如果图片 URL 中不包含类型信息，可以添加 isImage 标记来声明
                ],
                imgUrl: [], //图片上传返回的地址,
                imgUpload: {
                    // 1: true,
                }, // 图片是否上传完成对象
                imgUploadIndex: 1 //图片数组索引
                /** 图片上传 off*/
            };
        },
        components: {
            ChooseDepartment,
            ChooseHospital
        },
        methods: {
            init() {
                if (!this.$route.query.familyMemberID && !this.$route.query.id) {
                    this.$router.back();
                }

                // 基本个人头像信息
                let query = this.$route.query;
                this.patientInfo.avatorImg = query.headImg;
                this.patientInfo.name = query.name;
                this.patientInfo.UserRelationship = query.relation;
                //家庭成员id
                this.patientInfo.familyMemberID = query.familyMemberID;

                if (!this.$route.query.id) {
                    //新增病历  没有病历id 为添加病历
                    document.title = "添加病历";
                } else {
                    // 修改病历
                    this.id = this.$route.query.id; //病历id;
                    // 修改病历  获取病历信息
                    this.GetMedicalFile();
                    // 获取科室
                    this.GetDepartmentList();
                }
            },
            // 修改
            handleAmend(e) {
                // console.log(e);
            },
            // 日期格式化
            formatterDate(type, value) {
                if (type === "year") {
                    return `${value}年`;
                } else if (type === "month") {
                    return `${value}月`;
                }
                return `${value}日`;
            },
            // 确认日期
            confirmDate(date) {
                this.dateShow = false;
                var str =
                    date.getFullYear() +
                    "/" +
                    (date.getMonth() + 1) +
                    "/" +
                    date.getDate();
                this.$set(this.patientInfo, "time", str);
            },
            // 保存病历
            saveMedicalHistory() {
                if (!this.patientInfo.result || !this.patientInfo.time) {
                    return this.$toast("请输入必填项");
                }

                /** 图片未上传完成  */
                for (let index in this.imgUpload) {
                    if (this.imgUpload.hasOwnProperty(index)) {
                        // console.log(this.imgUpload[index]);
                        if (!this.imgUpload[index]) {
                            return this.$toast("图片未上传完成");
                        }
                    }
                }

                // 新增  修改病历
                let dataObj = {
                    Id: this.id,
                    DoctorsAdvice: this.patientInfo.advice, //医嘱
                    CaseDetails: this.patientInfo.description, //病情描述
                    FamilyMemberID: this.patientInfo.familyMemberID, //家庭成员id ,
                    DiagnosisResult: this.patientInfo.result, //诊断结果 ,
                    DiagnosisDate: this.patientInfo.time, //诊断时间 ,
                    DiagnosisDoctor: this.patientInfo.doctor, //诊断医生 ,
                    DoctorAlias: this.patientInfo.DoctorAlias, //医生职称 1=>主任医生,  2 =>副主任医生 3 =>主治医生  4 =>医师
                    DiagnosisDepartment: this.patientInfo.departmentsId, //诊断科室
                    DiagnosisHospital: this.patientInfo.hospital, //诊断医院
                    ListFile: this.imgUrl //附件类型
                };
                this.$toast.loading({
                    duration: 0, //持续展示
                    forbidClick: true, //禁用背景点击
                    message: "保存中...",
                    mask: true //背景遮罩
                });
                this.$http.AddOrUpdateMedicalFile(dataObj).then(
                    ({ data }) => {
                        this.$toast.clear();
                        this.$toast(data.ResultMsg);
                        if (data.IsSuccess) {
                            // 成功
                            setTimeout(() => {
                                this.$router.replace({
                                    name: "memberFile",
                                    query: { id: this.patientInfo.familyMemberID }
                                });
                            }, 500);
                        } else {
                            // 失败
                        }
                    },
                    () => {
                        this.$toast.clear();
                        this.$toast.fail("网络错误");
                    }
                );
            },
            // 选择职称之后触发
            changeTitles(value) {
                // console.log(value);
            },
            // 确认科室
            confirmDepartment(obj) {
                this.$set(this.patientInfo, "departments", obj.text); // 诊断科室
                this.$set(this.patientInfo, "departmentsId", obj.id); //诊断科室id
                this.departmentShow = false;
            },
            // 确认医院
            confirmHospital(dataObj) {
                this.patientInfo.hospital = dataObj.name;
                this.HospitalShow = false;
            },
            //   上传   datafile=>上传文件   file =>图片file对象  index  =>imgUpload 对象索引
            upload(dataFile, index) {
                this.$set(this.imgUpload, index, false);

                this.$toast({
                    message: "图片上传中",
                    type: "loading",
                    duration: 60000,
                    forbidClick: true
                });
                this.$http.UploadFile(dataFile).then(
                    ({ data }) => {
                        this.$toast.clear();
                        this.$set(this.imgUpload, index, true); //图片上传完成

                        if (data.IsSuccess) {
                            // 成功
                            // 返回的图片地址 发送图片地址
                            this.imgUrl.push(data.ResultObject[0]);
                            let index =
                                this.patientInfo.medicalHistoryImg.length - 1;
                            this.$set(
                                this.patientInfo.medicalHistoryImg[index],
                                "url",
                                data.ResultObject[0].AccessoryUrl
                            );
                            //图片上传完成
                        } else {
                            // 失败
                            this.$toast(data.ResultMsg);
                        }
                    },
                    () => {
                        this.imgUpload = true; //网络错误
                        this.$toast.fail("上传失败");
                    }
                );
            },
            // 文件读取完成
            afterRead(file) {
                // console.log(file);
                // 发送请求上传
                this.selectFileImage(file);
            },
            //删除图片预览时触发
            deleteImage(file) {
                // console.log(file.url);
                /** 删掉imgUrl */
                // console.log(this.imgUrl
                console.log(file.url);
                this.imgUrl = this.imgUrl.filter(v => {
                    if (v.AccessoryUrl !== file.url) {
                        return true;
                    }
                });
            },
            // 根据病历id 获取病历信息
            GetMedicalFile() {
                this.$http.GetMedicalFile(this.id).then(
                    ({ data }) => {
                        if (data.IsSuccess) {
                            // 成功
                            this.filterInfo(data.ResultObject);
                        } else {
                            // 失败
                            this.$toast(data.ResultMsg);
                        }
                    },
                    () => this.$toast("网络错误")
                );
            }, // 处理信息
            filterInfo(dataObj) {
                // Member (FamilyMember, optional): 成员信息 ,
                // FileList (Array[Accessory], optional): 附件列表 ,
                // Medical (MedicalFile, optional): 成员病例信息
                let { Member, FileList, Medical } = dataObj;
                let imgurl = []; // 附件地址
                FileList
                    ? FileList.map(v => {
                          imgurl.push({ url: v.AccessoryUrl });
                      })
                    : "";
                this.imgUrl = FileList ? FileList : [];

                this.patientInfo = {
                    avatorImg: Member.HeadImg, //个人头像
                    name: Member.FamilyMemberName, //姓名
                    relation: "", // 关系
                    UserRelationship: Member.UserRelationship, // 关系id
                    result: Medical.DiagnosisResult, //诊断结果
                    time: Medical.DiagnosisDate, //诊断时间
                    advice: Medical.DoctorsAdvice, //医嘱
                    description: Medical.CaseDetails, //病情描述
                    doctor: Medical.DiagnosisDoctor, //医生
                    DoctorAlias: Medical.DoctorAlias, //医生职称
                    departments: "", //科室
                    departmentsId: Medical.DiagnosisDepartment, //诊断科室id
                    hospital: Medical.DiagnosisHospital, //医院
                    familyMemberID: Medical.FamilyMemberID, //病人id
                    /** 病历详情图片 */
                    medicalHistoryImg: imgurl
                };
            },
            // 获取科室信息
            GetDepartmentList() {
                // 优先本地 获取科室信息
                if (!sessionStorage.getItem("DepartmentList")) {
                    this.$http.GetDepartmentList().then(({ data }) => {
                        if (data.IsSuccess) {
                            // 本地存储  科室信息
                            sessionStorage.setItem(
                                "DepartmentList",
                                JSON.stringify(data.ResultObject)
                            );
                            this.departmentList = data.ResultObject;
                        } else {
                            this.$toast(res.data.ResultMsg);
                        }
                    });
                } else {
                    this.departmentList = JSON.parse(
                        sessionStorage.getItem("DepartmentList")
                    );
                }
            },
            // 压缩图片  图片类型，图片的最大宽度和最大高度
            resizeMe(img, type, max_width, max_height) {
                var canvas = document.createElement("canvas");
                var width = img.width;
                var height = img.height;
                max_width = !isNaN(max_width) ? max_width : 0;
                max_height = !isNaN(max_height) ? max_height : 0;
                // 在这里图片是等比例缩放的，调用方法时填入图片允许的最大宽度或者是最大的高度
                //如果最大宽度为0 则按照最大高度固定，宽度自适应的方式来实现
                //如果是最大高度为0，则按照最大的宽度来实现
                if (max_width == 0) {
                    if (height > max_height) {
                        width = Math.round((width *= max_height / height));
                        height = max_height;
                    }
                }
                if (max_height == 0) {
                    if (width > max_width) {
                        height = Math.round((height *= max_width / width));
                        width = max_width;
                    }
                }
                canvas.width = width;
                canvas.height = height;
                var ctx = canvas.getContext("2d");
                canvas.width = width;
                canvas.height = height;
                ctx.drawImage(img, 0, 0, width, height);
                type = type === "jpg" ? "jpeg" : type;
                return canvas.toDataURL("image/" + type, 0.7); //这里的0.7值的是图片的质量
            },
            // 选择图片对象  并且上传
            selectFileImage(files) {
                var reader = new FileReader();
                var file = files.file;
                var fileName = file.name;
                var fileType = file.name.split(".")[1];
                reader.readAsArrayBuffer(file);

                reader.onload = ev => {
                    var blob = new Blob([ev.target["result"]]);
                    window["URL"] = window["URL"] || window["webkitURL"];
                    var blobURL = window["URL"].createObjectURL(blob);
                    var image = new Image();
                    image.src = blobURL;
                    image.onload = e => {
                        var thumb = this.resizeMe(image, fileType, 800, 0); //获得的路径是将图片转换成了base64

                        // 转为file对象
                        let data = new FormData();
                        let imgFile = this.dataURLtoFile(thumb, "123.png");
                        data.append("file", imgFile);
                        // 发送请求
                        // 是否上传成功对象
                        let index = this.imgUploadIndex;
                        this.imgUploadIndex++;
                        // 上传
                        this.upload(data, index);
                    };
                };
            },
            //   base64转为 file对象
            dataURLtoFile(dataurl, filename) {
                //将base64转换为文件
                var arr = dataurl.split(","),
                    mime = arr[0].match(/:(.*?);/)[1],
                    bstr = atob(arr[1]),
                    n = bstr.length,
                    u8arr = new Uint8Array(n);
                while (n--) {
                    u8arr[n] = bstr.charCodeAt(n);
                }
                return new File([u8arr], filename, { type: mime });
            }
        },
        filters: {
            // 时间过滤
            filterTime(date) {
                let newDate = new Date(date);
                let year = newDate.getFullYear();
                let month = newDate.getMonth() + 1;
                let day = newDate.getDate();
                return year + "年" + month + "月" + day + "日";
            }
        },
        computed: {
            // 选中科室的提示文字
            departmentText() {
                var text = "";
                this.departmentList.map((v, i) => {
                    v.DepartmentsList.map(value => {
                        if (this.patientInfo.departmentsId == value.Id) {
                            text = value.DepartmentName;
                        }
                    });
                });
                //科室提示文本
                this.$set(this.patientInfo, "departments", text);
                return text;
            }
        },
        created() {
            this.init();
        }
    };
</script>
<style lang='less' scoped>
    // 阴影
    .shadow(@color: rgba(153, 153, 153, 0.2)) {
        box-shadow: 0rem 0.05rem 0.14rem 0rem @color;
    }

    .medicalHistory {
        padding: 0.24rem 0.24rem 0.5rem;

        .mt-3 {
            margin-top: 0.3rem;
        }

        .common {
            background-color: #ffffff;
            .shadow();
            border-radius: 0.1rem;
        }

        // 个人信息
        .patientInfo {
            .common();
            display: flex;
            padding: 0.4rem 0.3rem;

            .img {
                margin-right: 0.28rem;
            }

            .name-info {
                display: flex;
                flex-direction: column;
                justify-content: space-around;

                span {
                    font-size: 0.28rem;
                    line-height: 0.32rem;
                    color: #4c4c4c;
                    font-weight: 600;

                    &.sex {
                        font-size: 0.24rem;
                        color: #7f7f7f;
                    }
                }
            }
        }

        .medicalResult,
        .medicalDoctor,
        .doctorAdvice {
            .common();
            padding: 0 0.22rem;

            > div {
                display: flex;
                height: 1.07rem;
                line-height: 1.07rem;
                font-size: 0.3rem;
                text-align: left;
                border-bottom: 0.02rem solid #f2f2f2;
                &:nth-last-of-type(1) {
                    border-bottom: none;
                }

                span {
                    display: block;
                    width: 1.2rem;
                    color: #000;
                    margin-right: 0.26rem;
                    flex-shrink: 0;
                    &.bolder {
                        font-weight: 600;
                        font-size: 0.28rem;
                    }
                    &:nth-of-type(2) {
                        flex: 1;
                        // color: #7f7f7f;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        white-space: nowrap;
                    }
                }
                input {
                    flex: 1;
                    width: 100%;
                    // color: #7f7f7f;
                    color: #000;
                }
            }
        }

        // 附件
        .enclosure {
            background-color: transparent;
            box-shadow: none;

            .title {
                font-size: 0.3rem;
                height: 0.72rem;
                line-height: 0.72rem;
                color: #787878;
                text-align: left;
                padding-left: 0.24rem;
            }
            .content-img {
                .common();
                padding: 0.3rem 0 0.3rem 0.24rem;
                display: flex;
                flex-wrap: wrap;
            }
        }

        // 选择医生职称
        /deep/ .selectTitles {
            width: 100%;
            height: 100%;

            &::after {
                display: none;
            }
            .van-dropdown-menu__title {
                width: 100%;
                padding: 0;
                font-size: 0.3rem;
                &::after {
                    right: 0.1rem;
                }
            }
            .van-dropdown-item {
                width: 5.8rem;
                left: auto;
                right: 0.2rem;
            }
        }

        .button {
            width: 4rem;
            height: 0.8rem;
            background-image: linear-gradient(#00a0e9, #00a0e9),
                linear-gradient(#3d9cff, #3d9cff);
            background-blend-mode: normal, normal;
            box-shadow: 0rem 0.04rem 0.12rem 0rem rgba(0, 110, 233, 0.44);
            border-radius: 0.4rem;
        }
    }
</style>
