<template>
    <!--填写咨询内容-->
    <view class="write-dise-con" :style="{ marginTop: (height*2 - 2) +'rpx', height: 'calc(100vh - '+ (height*2 - 2) +'rpx - 100rpx)', overflow: 'auto' }">
        <view class="write-dise-con-scroll">
            <view class="itdc-head">
                <view class="itdc-head-content">
                    <view class="itdc-head-portrait">
                        <image style="width:100rpx;height:100rpx;border-radius: 50%;" onerror="imageError" :src="docObj && docObj.image ? docObj.image : windowHost +'/images/photo/a0061261ab11da688ee4574cfc8e0994.jpg'">
                        </image>
                    </view>
                    <view class="itdc-head-content-top">
                        <view class="itdc-head-content-top-text">
                            <text>{{ docObj && docObj.doctorName ? docObj.doctorName : "" }}</text>
                            <text>{{ docObj && docObj.title ? docObj.title : "" }}</text>
                            <text>|</text>
                            <text style="margin-left:16rpx">{{ docObj && docObj.locDesc ? docObj.locDesc : "" }}</text>
                        </view>
                        <view class="itdc-head-desc">
                            <text>请详细描述病情、症状，这有助于我更准确地分析，同事保证你的隐私安全！</text>
                        </view>
                    </view>
                </view>
            </view>
            <view class="write-dise-con-input">
                <view class="detail-list-item">
                    <view>预约时段</view>
                    <view class="right">
                        <text style="margin-right:20rpx">{{ time }}</text>
                    </view>
                </view>
                <view class="detail-list-item">
                    <view>就诊人</view>
                    <view class="right" @tap="showPopup">
                        <text style="margin-right:20rpx">{{ (patObj && patObj.patName ? (patObj.patName + ' ') : '') + (patObj && patObj.patSexDesc ? patObj.patSexDesc : '') }}</text>
                        <van-icon size="28rpx" color="#333333" name="arrow" />
                    </view>
                </view>
                <view class="detail-list-item">
                    <view>挂号费</view>
                    <view class="right" @tap="showPopup1">
                        <view style="margin-right:20rpx">￥<text class="c-orange">{{ payAmtInt }}</text></view>
                    </view>
                </view>
                <view class="detail-list-item">
                    <view>既往病史</view>
                    <view class="right" @tap="showPopup1">
                        <!-- <text style="margin-right:20rpx">{{ checkBoxDesc ? checkBoxDesc : "请选择" }}</text> -->
                        <text style="margin-right:20rpx">
                            <textarea class="placeholder-css text-css" @input="inputValue_jwbs" v-model="pastMedicalHistory" style="position:static;" cursor-spacing="140" :adjust-position="true"></textarea>
                        </text>
                        <van-icon size="28rpx" color="#333333" name="arrow" />
                    </view>
                </view>
                <view class="detail-list-item">
                    <view>是否药物过敏</view>
                    <view class="right">
                        <checkbox :value="checked" @change="onChangeCheck" />
                    </view>
                </view>
                <view class="detail-list-item" v-if="checked">
                    <view>过敏药物名称</view>
                    <view class="right" style="text-align: right;">
                        <input placeholder="请输入过敏药物名称" @input="drugName" />
                    </view>
                </view>
                <view class="detail-list-item" style="border-bottom: 0;" v-if="entrance!='4'">
                    <view>咨询内容</view>
                    <!-- <view class="btn" bindtap="">历史病情</view> -->
                </view>
                <view class="disease-detail-css" v-if="entrance!='4'">
                    <scroll-view class="ddc-scroll-view" :scroll-top="lineHeight">
                        <textarea v-if="isShowText" class="placeholder-css text-css" @blur="onShowText" @input="inputValue" @focus="onFocus" v-model="disesNote" style="position:static;" cursor-spacing="140" :adjust-position="true"></textarea>
                        <view v-else :class="disesNote==''?'placeholder-css':'text-css'" @tap="onShowTextare">
                            <text style="word-wrap: break-word;">{{disesNote==""?placeholder:disesNote}}</text>
                        </view>
                    </scroll-view>
                </view>
                <view class="ddc-message" v-if="entrance!='4'">*为保护您的隐私，请不要输入您的住址等信息。</view>
                <view class="detail-list-item" style="border-bottom:0" v-if="entrance!='4'">
                    <view>
                        <view>上传图片</view>
                        <view class="text1">上传内容仅对该医生可见，最多9张</view>
                        <view style="margin-top:30rpx">
                            <!--<van-uploader :file-list="fileList" max-count="9" @after-read="afterRead" multiple="true" accept="image" @delete="deleteImage" preview-size="210rpx" />-->
                        </view>
                    </view>
                    <view class="right"></view>
                </view>
            </view>
            <view class="read" v-if="entrance!='4'">
                <view class="agree-css" @tap="agree2">
                    <van-icon name="checked" v-if="showButton" style="color:#1890FFFF;" size="40rpx" />
                    <van-icon name="circle" v-if="showButton?false:true" size="40rpx" />
                </view>
                <view style="color:#666666FF;">
                    <text @tap="agree2">我已阅读并同意</text>
                    <text @tap="showBook" style="color:#1890FF;">《{{ userData.hospDesc }}互联网医院患者知情同意书》</text>
                </view>
            </view>
            <view class="wdc-footer-btn">
                <view class="health-pay-btn">
                    <!-- !userData.insuTestFlag  userData.insuTestFlag == 'O' -->
                    <!-- insuType O只是门诊，R只是挂号，OR门诊和挂号，其它不使用医保;   insuTestFlag Y 是测试，O 是正式库测试 其它为正式使用 -->
                    <!-- 测试 -->
                    <!-- <view class="pay-css"  bindtap="getAuthCode" v-if="userData && (userData.insuType == 'R' || userData.insuType == 'OR') && userData.insuTestFlag == 'Y'"> -->
                    <!-- 正式 -->
                    <view class="pay-css" bindtap="getAuthCode" v-if="userData && (userData.insuType == 'R' || userData.insuType == 'OR') && !userData.insuTestFlag">
                        <text>医保支付</text>
                    </view>
                    <view bindtap="judgeCompliance" class="pay-css personal">
                        <text>自费支付</text>
                    </view>
                </view>
            </view>
        </view>
    </view>
    <van-popup :show="showPopup" position="bottom" custom-style="height: 40%;" @close="onClosePopup">
        <block>
            <view style="padding:20rpx 24rpx 20rpx 24rpx;">
                <view style="margin-bottom:20rpx">
                    <text class="address_text2">选择就诊人</text>
                    <view style="float:right">
                        <van-button size="small" custom-class="cancel" type="info" plain @tap="onClosePopup">取消</van-button>
                    </view>
                </view>
                <view class="border-bottom-after::after"></view>
            </view>
            <view style="margin:0 24rpx 16rpx 24rpx">
                <scroll-view scroll-y="true" style="height: 320rpx;margin-bottom: 100rpx">
                    <radio-group :value="radio" @change="onChangePat">
                        <radio :name="item.patID" icon-size="30rpx" v-for="(item,index) in visitorData" :key="index">
                            <view style="margin:16rpx 16rpx;display:flex;justify-content: space-between;align-items:center">
                                <view>
                                    <view style="width:200%">
                                        <view style="width: 550rpx">
                                            <text>{{ item.patName }} {{ item.idCard }}</text>
                                        </view>
                                    </view>
                                </view>
                                <view>
                                    <view @tap.stop="updatePat" :data-index="item.patID">
                                        <van-icon size="48rpx" name="edit" />
                                    </view>
                                </view>
                            </view>
                        </radio>
                    </radio-group>
                </scroll-view>
            </view>
            <view class="add-pat-css" bindtap="gotoAddPat">
                <van-icon name="add-o" size="37rpx;" />
                <text class="add-pat-text">添加就诊人</text>
            </view>
        </block>
    </van-popup>
    <!-- 弹出疾病多选框 -->
    <van-popup :show="showPopup1" position="bottom" custom-style="height: 40%;" @close="onClosePopup1">
        <view style="padding:20rpx 24rpx 20rpx 24rpx;">
            <view style="margin-bottom:20rpx">
                <text class="address_text2">选择疾病</text>
                <view style="float:right">
                    <van-button size="small" custom-class="cancel" type="info" plain @tap="onClosePopup1">确定</van-button>
                </view>
            </view>
            <view class="border-bottom-after::after"></view>
        </view>
        <view style="margin:0 24rpx 16rpx 24rpx">
            <scroll-view scroll-y="true" style="height: 410rpx;">
                <view class="check-box">
                    <checkbox-group :value="checkBoxData" @change="onChangeCheckBoxData">
                        <view style="padding-top:20rpx" v-for="(item,index) in checkBox" :key="index">
                            <checkbox :name="item.descripts">{{ item.descripts }}</checkbox>
                        </view>
                    </checkbox-group>
                </view>
            </scroll-view>
        </view>
    </van-popup>
    <van-popup :show="showBook" custom-style="height: 80%" position="bottom" @close="onCloseBook">
        <view style="margin:30rpx 20rpx 20rpx 20rpx">
            <view style="font-size:32rpx;font-weight: 700; display: block; padding-bottom: 15px;">{{ userData.hospDesc }}互联网医院患者知情同意书111</view>
            <view decode="true" style="line-height:70rpx;font-size:24rpx;padding-bottom:120rpx;">
                <view class="p">欢迎您使用{{ userData.hospDesc }}互联网医院。在您开始使用互联网医院服务前，请您务必仔细阅读本知情同意书中的所有条款。一旦您勾选“已阅读并同意”，即表示您已充分理解并自愿接受本同意书的全部内容。</view>
                <view class="p">特别提示： 互联网诊疗不能完全替代线下面诊。若病情出现变化或存在不适宜在线诊疗的情况，请及时前往{{ userData.hospDesc }}就诊。</view>
                <view class="h2">一、基本声明与实名认证</view>
                <view class="p">1.服务性质：本院互联网医院依托实体医疗机构建立，旨在为患者提供便捷的医疗健康服务，包括但不限于在线复诊、健康咨询、处方开具、药品配送等 。</view>
                <view class="p">2.实名制要求：根据国家相关规定，互联网医院实行实名制就诊。您承诺提供的姓名、身份证号、手机号及医保信息等真实有效。因提供虚假信息导致的一切后果（如误诊、用药错误等），由您自行承担 。</view>
                <view class="h2">二、 服务范围与复诊规定</view>
                <view class="p">1.接诊范围：{{ userData.hospDesc }}互联网医院仅对部分常见病、慢性病的复诊患者提供服务。您知悉并保证，在发起在线诊疗申请前，已在{{ userData.hospDesc }}完成该疾病的首次诊断。</view>
                <view class="p">2.服务限制：{{ userData.hospDesc }}互联网医院不提供首诊服务，亦不用于急诊、危重症患者。如您属于急危重症，请立即拨打120或前往就近医院就诊。</view>
                <view class="p">3.特殊药品限制：根据法律法规，互联网医院不得开具麻醉药品、精神药品、医疗用毒性药品、放射性药品以及其他用药风险较高或有特殊管理规定的药品处方。</view>
                <view class="h2">三、 诊疗风险与医患权责</view>
                <view class="p">1.医疗局限性告知：</view>
                <view class="p">互联网诊疗无法进行体格检查及部分辅助检查，医生主要依据您提供的图文资料（病史、症状描述、既往检查报告）进行判断。若您提供的资料不准确、不全面或描述不清，可能导致诊疗方案出现偏差，相关风险由您承担。</view>
                <view class="p">由于个体差异和疾病本身的复杂性，即使医生已尽到专业努力，仍可能存在病情恶化、药物不良反应或治疗效果未达预期的风险。</view>
                <view class="p">2.诊疗终止与转诊：当出现以下情况时，医生有权终止诊疗服务，请您配合前往实体医疗机构就诊：</view>
                <view class="p">● 病情出现变化或加重；</view>
                <view class="p">● 经医生判断，疾病属于疑难杂症或需现场检查确诊；</view>
                <view class="p">● 您属于急症或重症 。</view>
                <view class="p">3.服务行为规范：医生将通过电子签名提供诊疗服务，严禁他人或人工智能软件代替接诊 。您在交流过程中应文明用语，尊重医护人员的专业判断。</view>
                <view class="h2">四、 处方与药品服务</view>
                <view class="p">1.处方审核：医生开具的电子处方需经本院执业药师审核合格后方可生效。您有权根据药师指导调整用药方案。</view>
                <view class="p">2.药品配送：如选择药品配送服务，药品将由我院或我院委托的第三方配送。请您在签收时核对药品信息。除药品质量问题外，药品一经售出，不予退换。</view>
                <view class="h2">五、 隐私保护与信息收集</view>
                <view class="p">1.信息收集：为提供诊疗服务，我们将收集您的身份信息、病情资料、健康记录（如身高、体重、慢性病史）以及问诊过程中的音视频资料 。</view>
                <view class="p">2.信息保密：本院将严格遵守《个人信息保护法》及相关医疗法规，对您的个人信息和诊疗数据予以保密，严防数据泄露。诊疗过程中的图文对话、音视频资料将按照门诊电子病历规定进行保存（保存时间不少于15年，过程记录不少于3年）。</view>
                <view class="h2">六、 费用与投诉</view>
                <view class="p">1.费用公示：互联网医院的服务收费项目及标准已在平台公示，您同意在诊疗服务开启前支付相应的挂号费/诊查费。</view>
                <view class="p">2.投诉渠道：如您在就诊过程中对服务不满意，有权通过平台客服或医院公布的监督电话进行投诉，我们将依据事实予以协调处理。</view>
                <view class="h2">七、 法律效力与协议修改</view>
                <view class="p">1.电子有效性：本知情同意书以电子形式签订，自您在线上点击“已阅读并同意”时起具有同等法律效力 。</view>
                <view class="p">2.规则更新：本院有权根据法律法规的变化或业务调整修改本知情同意书。修改后的协议一经发布即视为有效告知，如您继续使用服务，视为接受修订。</view>
                <view class="p">患者承诺：</view>
                <view class="p">本人已仔细阅读并充分理解上述所有条款，知晓互联网诊疗存在的局限性及潜在风险。本人同意遵守互联网医院的规定，保证提供信息真实有效，自愿接受互联网诊疗服务。</view>
            </view>
        </view>
        <view style="position: fixed;bottom: 0;width: 100%;">
            <van-button custom-class="button_agree" type="default" @tap="agree">已阅读并同意</van-button>
        </view>
    </van-popup>
</template>

<script>
import { Utils } from '@/utils/util';
import { $http } from "@/utils/https"
import { httpConfig } from '@/utils/httpConfig';
import GenerateTestUserSig from '@/debug/GenerateTestUserSig.js';
import Dialog from '@/components/dialog/dialog';
import vanPopup from '@/components/popup/index'
import vanButton from '@/components/button/index'
import vanIcon from '@/components/icon/index'
import monitor from '@/utils/alipayLogger';

const app = getApp();
let timer = null;
let isPayment = true;
export default {
    components: {
        'van-popup': vanPopup,
        'van-button': vanButton,
        'van-icon': vanIcon
    },
    props: {
        path: String,
        payPath: String,
        flag: Boolean
    },
    data() {
        return {
            windowHost: httpConfig && httpConfig.ipDeault ? httpConfig.ipDeault : "",
            payTypeRadio: '',
            onFacus: true,
            motto: '',
            idCardNo: String,
            admReasonCode: null, // '02': 医保支付 '01': 自费支付
            payAmtInt: 0, // 自费支付金额
            userData: this.$cache.get('userData'),
            hisHospID: this.$cache.get('userData').hisHospID,
            symptom: String,
            payTradeNum: "", ///就诊ID
            prescribeTradeNum: "",
            healthPayAmt: 0, ///医保支付金额
            cashamt: 0,
            insuamt: 0,
            insuGRBalance: 0,
            fileList: [], ////图片列表
            backPage: 2, ////回退页码
            locID: '',
            showButton: false,
            userData: Object,
            showBook: false,
            patID: String,
            patIndex: Number,
            radio: '',
            visitorData: Array,
            showPopup: false,
            showPopup1: false,
            onFocus: false, //textarea焦点是否选中
            isShowText: false,
            show: false,
            active: 1,
            docObj: {},
            schTimeKey: "", ///预约时间段ID
            schDateKey: "", //图文咨询预约ID
            disesTime: "", //患病时长
            disesNote: "", //症状描述
            pastMedicalHistory: "", // 既往病史
            patObj: {},
            placeholder: "请详细描述您想要咨询的问题，如症状描述、持续时间、用药情况、检查治疗等。",
            lineHeight: 0, ////文本框高度
            height: app.globalData.height * 2 + 20,
            medCardID: "",
            infoByTrandNoFlag: false,
            infoByTrandNo: 0,
            time: "",
            checked: false,
            drugName: "",
            checkBoxData: [],
            checkBoxDesc: "",
            checkBox: [],
            showMedicalInsurancePopup: true, // 医保使用提示弹窗是否显示
        }
    },
    onShow() {
        const self = this
        let {
            admReasonCode,
            payTradeNum
        } = self;

        if (!isPayment) {
            isPayment = true;
        }
        console.log('就诊号：' + payTradeNum)
        console.log('操作类型：' + admReasonCode)
        if (payTradeNum) {
            uni.showLoading();
            self.getPayStatus("healthPay");
        } else if (admReasonCode == '02' && app.globalData.authCode) {
            // 如果是医保支付
            self.judgeCompliance(admReasonCode, function () {
                if (this.payTradeNum) {
                    uni.showLoading();
                    self.getPayStatus("healthPay");
                }
            })
        }
    },
    onUnload() {
        if (timer) {
            uni.hideLoading();
            clearInterval(timer)
        }
    },
    methods: {
        // 获取便民挂号信息
        getRegInfo: function () {
            const self = this
            let userData = this.$cache.get('userData')
            let data = {
                params: [{
                    hospID: userData.hospID || "",
                    hospCode: userData.hisHospID || "",
                    admreasonID: ""

                }]
            }
            $http.post("urlS", self, {
                code: "03040041",
                data: data,
                namespace: "Y",
                success: function (res) {
                    uni.hideLoading();
                    if (+res.errorCode === 0) {
                        let resObj = res.result
                        let locObj = {
                            locID: resObj.locID,
                            locCode: resObj.locCode,
                            locDesc: resObj.locDesc
                        }
                        let patObj = {
                            idCardNo: userData.idCardNo,
                            imUserID: userData.imUserID,
                            patDesc: userData.patName,
                            patID: userData.patID,
                            hisPatNo: userData.hisPatNo,
                            hisPatID: userData.hisPatID,
                            mobile: userData.mobile,
                            patSexDesc: userData.patSexDesc,
                            medCardID: userData.medCardID || ''
                        }
                        let docObj = {
                            doctorID: resObj.doctorID,
                            doctorCode: resObj.doctorCode,
                            doctorName: resObj.doctorName,
                            image: resObj.image,
                            title: resObj.title,
                        }
                        this.setData({
                            docObj: docObj,
                            patObj: patObj,
                            schTimeKey: resObj.resDetailID,
                            userData: this.$cache.get('userData'),
                            locID: locObj.locID,
                            entrance: "1"
                        }, () => {
                            this.getPayAmt();
                            // this.healthPayAmt();
                            this.getIp();
                        })
                    } else {
                        Toast({
                            context: this,
                            message: res.errorMessage
                        });
                    }
                }
            });
        },

        // 获取多选
        getCheckBox() {
            const self = this
            let userData = this.$cache.get('userData')
            let data = {
                params: [{
                    hospID: userData.hospID || "",
                    hospCode: userData.hisHospID || '',
                    upDirectID: "",
                    locID: "",
                    inputValue: ""
                }]
            }
            $http.post("urlS", self, {
                code: "03050253",
                data: data,
                namespace: "Y",
                success: function (res) {
                    if (+res.errorCode === 0) {
                        self.setData({
                            checkBox: res.result.data
                        }, () => {
                            // console.log("checkBox", this.data.checkBox)
                        })
                    }
                }
            });
        },

        // 切换单选按钮
        onChangeCheck(event) {
            this.setData({
                checked: event.detail,
            });
        },

        // 多选
        onChangeCheckBoxData(event) {
            this.setData({
                checkBoxData: event.detail,
            })
        },

        // 输入过敏药品名称
        drugName(e) {
            this.setData({
                drugName: e.detail.value
            })
        },

        onClosePopup() {
            this.setData({
                showPopup: false
            });
        },

        showPopup() {
            this.setData({
                showPopup: true
            });
        },

        onClosePopup1() {
            this.setData({
                checkBoxDesc: this.checkBoxData.toString(),
                showPopup1: false
            })
        },

        showPopup1() {
            this.setData({
                showPopup1: true
            });
        },

        // 跳转到添加就诊人
        gotoAddPat: Utils.debounce(function () {
            uni.navigateTo({
                url: "../../../../mine/addCard/visitorEntry/visitorEntry",
                success: (res) => {
                    res.eventChannel.emit('turnBack', {
                        url: this.flag ? '../../../index/pages/graphicConsultation/graphicConsulWriteContent/graphicConsulWriteContent' : '../../../index/pages/videoConsultation/videoConsulWriteContent/videoConsulWriteContent',
                    })
                },
            })
        }),

        // 选择就诊人
        onChangePat(event) {
            var {
                visitorData
            } = this.data;
            let patObj = {};
            for (var i = 0; i < visitorData.length; i++) {
                if (visitorData[i].patID === event.detail) {
                    patObj = visitorData[i];
                    break;
                }
            }
            this.setData({
                radio: event.detail,
                patObj
            }, () => {
                this.loginTim(this.patObj);
            });
            this.onClosePopup()
        },

        onCloseBook() {
            this.setData({
                showBook: false
            });
        },

        showBook() {
            this.setData({
                showBook: true
            });
        },

        agree() {
            this.setData({
                showButton: true
            }, () => {
                this.onCloseBook();
            })
        },

        agree2() {
            this.setData({
                showButton: this.showButton == false ? true : false
            })
        },

        // 查询就诊人列表
        getVisitorDataList: function () {
            const self = this
            let data = {
                params: [{}]
            }
            $http.post("urlS", self, {
                code: "01030001",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        if (res.result && res.result.totalCount === 0) {

                            Dialog.alert({
                                context: self,
                                title: '提示',
                                message: '请添加就诊人',
                            }).then(() => {
                                self.gotoAddPat()
                            });
                            return
                        } else {
                            let data = JSON.parse(JSON.stringify(res.result.rows))
                            self.replaceIdCardNo(data);
                        }

                    } else {
                        self.setData({
                            visitorData: []
                        });
                    }
                }
            });
        },

        // 处理身份证号
        replaceIdCardNo(data) {
            const self = this
            for (var i = 0; i < data.length; i++) {
                data[i].idCard = Utils.identityCardEncryption(data[i].idCardNo)
            }
            self.setData({
                visitorData: data
            }, () => {
                if (data.length === 1) {
                    self.setData({
                        patIndex: 0,
                        patID: data[0].patID,
                        patObj: data[0],
                        radio: data[0].patID
                    }, () => {
                        self.loginTim(data[0])
                    })
                    app.globalData.patObj = data[0];
                } else if (this.$cache.get('userData').patID != "") {
                    for (var i = 0; i < self.visitorData.length; i++) {
                        if (self.visitorData[i].patID == this.$cache.get('userData').patID) {
                            self.setData({
                                patObj: self.visitorData[i],
                                patID: self.visitorData[i].patID,
                                patIndex: i,
                                radio: self.visitorData[i].patID,
                            }, () => {
                                if (!app.globalData.isLogOut) { // 判断是否以及退出，已经退出则不需要退出再登录，而是直接登录
                                    self.login(self.patObj && self.patObj.imUserID ? self.patObj.imUserID : "");
                                }
                            });
                            app.globalData.patObj = self.visitorData[i];
                            break;
                        }
                    }
                }
            });
        },

        // 图片加载出错，替换为默认图片
        imageError(e) {
            this.docObj.image = "https://api.daidr.me/apis/imgholder/74x95.png?text=推荐医生";
        },

        // 文件上传
        afterRead(event) {
            const {
                file
            } = event.detail;
            var self = this;
            let newUserData = this.$cache.get('userData');
            for (var i = 0; i < file.length; i++) {
                uni.uploadFile({
                    url: newUserData && newUserData.consultFileUpload ? newUserData.consultFileUpload.indexOf("http") !== -1 ? newUserData.consultFileUpload : this.windowHost + newUserData.consultFileUpload : this.windowHost + '/uploadFile?fileType=consult',
                    filePath: file[i].path,
                    name: 'file',
                    // formData: { user: 'test' },
                    success(res) {
                        // 上传完成需要更新 fileList
                        if (res.statusCode === 200) {
                            let path = JSON.parse(res.data).filePath;
                            self.fileList.push({
                                url: (newUserData && newUserData.consultFile ? newUserData.consultFile.indexOf("http") !== -1 ? newUserData.consultFile : this.windowHost + newUserData.consultFile : this.windowHost + "/images/consult/") + path,
                                isImage: true,
                                path: path
                            });
                            self.setData({
                                fileList: self.fileList
                            })
                        }
                    }
                });
            }
        },

        // 删除图片
        deleteImage(event) {
            this.fileList.splice(event.detail.index, 1);
            this.setData({
                fileList: this.fileList
            })
        },

        onShowTextare() { //显示textare
            this.setData({
                isShowText: true,
                onFacus: true
            })
        },

        onShowText() { //显示text
            this.setData({
                isShowText: false,
                onFacus: false
            })
        },

        inputValue(e) {
            var value = e.detail.value;
            this.setData({
                disesNote: value,
            });
            app.globalData.disesNote = value
        },

        // 既往病史
        inputValue_jwbs() {
            var value = e.detail.value;
            this.setData({
                pastMedicalHistory: value,
            });
            app.globalData.pastMedicalHistory = value
        },

        updatePat(e) {
            let patID = e.currentTarget.dataset.index
            // console.log(132132132132, patID, e.currentTarget)
            uni.navigateTo({
                url: "/pages/mine/addCard/cardDetail/cardDetail",
                success: (res) => {
                    res.eventChannel.emit('turnBack', {
                        patID: patID,
                        url: this.flag ? '../../../index/pages/graphicConsultation/graphicConsulWriteContent/graphicConsulWriteContent' : '../../../index/pages/videoConsultation/videoConsulWriteContent/videoConsulWriteContent',
                    })
                },
            })
        },

        // 登录
        login: Utils.debounce(function (userID) {
            // console.log("IM登录", userID)
            let userData = GenerateTestUserSig.genTestUserSig(userID || '');
            let promise = app.globalData.tim.login({
                userID: userID || '',
                userSig: userData && userData.userSig ? userData.userSig : ""
            });
            promise.then((imResponse) => {
                app.globalData.isLogOut = true;
                // console.log("tim登录成功：", userID);
            }).catch((imError) => {
                // console.log('tim登录失败', userID, imError); // 登录失败的相关信息
            });
        }),

        // 退出
        signOut: function (type, userID) {
            const self = this
            try {
                let promise = app.globalData.tim.logout();
                promise.then((imResponse) => {
                    app.globalData.isLogOut = false;
                    // console.log("退出登录成功：", imResponse)
                    if (type === "signOut") {
                        self.login(userID);
                    }
                }).catch(function (imError) {
                    console.log('退出失败');
                });
            } catch (err) {
                console.log("退出失败")
            }
        },

        // 重新登录tim
        loginTim(patObj) {
            const self = this
            let userData = this.$cache.get('userData') || {};
            let {
                patIndex
            } = this;
            if (userData.imUserID !== patObj.imUserID) {
                this.$cache.set('userData', {
                    ...userData,
                    idCardNo: patObj.idCardNo,
                    imUserID: patObj.imUserID,
                    patDesc: patObj.patName,
                    patID: patObj.patID,
                    hisPatNo: patObj.hisPatNo,
                    hisPatID: patObj.hisPatID,
                    mobile: patObj.mobile,
                    patValue: patIndex ? patIndex : 0,
                    patSexDesc: patObj.patSexDesc,
                    medCardID: patObj.medCardID || ''
                });
                // console.log(!app.globalData.isLogOut)
                if (!app.globalData.isLogOut) { // 判断是否以及退出，已经退出则不需要退出再登录，而是直接登录
                    self.login(patObj.imUserID)
                } else {
                    self.signOut('signOut', patObj.imUserID)
                }
            }
        },

        // 判断患者是否符合科室要求
        judgeCompliance: Utils.debounce(function (admReasonCode, callback) {
            const self = this
            return new Promise((resolve, reject) => {
                if (!isPayment) {
                    if (admReasonCode == "02") {
                        uni.hideLoading();
                    }
                    return;
                }

                let code = typeof (admReasonCode) === 'string' ? admReasonCode : '01';
                self.setData({
                    admReasonCode: code
                })
                let {
                    locID,
                    patObj
                } = self;
                let data = {
                    params: [{
                        patID: '',
                        patNo: patObj.hisPatNo || '',
                        locID: locID || '',
                        schDateKey: self.schDateKey,
                        schTimeKey: self.schTimeKey
                    }]
                }
                if (admReasonCode != "02") {
                    uni.showLoading({
                        mask: true
                    })
                }
                $http.post("urlS", self, {
                    code: "03100090",
                    data: data,
                    namespace: "Y",
                    success: function (resOne) {
                        if (+resOne.errorCode === 0) {
                            self.lockNumber(code).then(data => {
                                typeof callback == 'function' && callback()
                            });
                        } else {
                            uni.hideLoading();
                            Utils.showToast(resOne.errorMessage, 'none')
                        }
                    },
                    error: function (error) {
                        console.log(error)
                    }
                });
            })
        }),

        // 挂号前加入到锁号表中
        lockNumber(code) {
            return new Promise((resolve, reject) => {
                let appointID = this.flag ? this.schDateKey : this.schTimeKey;
                let {
                    entrance
                } = this
                if (appointID === "") {
                    uni.hideLoading();
                    Utils.showToast('请选择医生排班记录！', 'error')
                    return;
                }
                if (this.disesNote.length <= 10 && entrance != '4') {
                    uni.hideLoading();
                    Utils.showToast('症状描述不得少于10个字', 'error')
                    return;
                }
                if (!this.patObj.patName) {
                    uni.hideLoading();
                    Utils.showToast('请选择就诊人', 'error')
                    return;
                }
                if (!this.showButton && entrance != '4') {
                    uni.hideLoading();
                    Utils.showToast('请先阅读并勾选患者知情同意书', 'error')
                    return;
                }
                let userData = this.$cache.get('userData');
                let data = {
                    params: [{
                        resDetailID: this.flag ? this.schDateKey : "",
                        patID: '',
                        bookMethodCode: "NET",
                        hospCode: userData.hisHospID || '',
                        resTimeID: this.flag ? "" : this.schTimeKey,
                    }]
                }
                $http.post("urlS", this, {
                    code: "03050234",
                    data: data,
                    namespace: "Y",
                    success: function (res) {
                        uni.hideLoading();
                        if (+res.errorCode === 0) {
                            // console.log(res)
                            this.pay(code, res.orderNo, function () {
                                resolve()
                            })
                        } else {
                            Utils.showToast(res.errorMessage, 'none')
                        }
                    },
                    error: function (error) {
                        uni.hideLoading();
                        // console.log(error)
                    }
                });
            })
        },

        // 获取IP地址 
        getIp() {
            var self = this;
            uni.request({
                url: this.windowHost + '/localIP',
                success: function (e) {
                    self.setData({
                        motto: e.data.ipv4,
                    })
                }
            });
        },

        // 根据科室，医生，日期查询图文排班ID
        getSchDateKey: Utils.debounce(function () {
            const self = this
            let data = {
                params: [{
                    doctorID: app.globalData.docObj.doctorID + "",
                    hospCode: this.$cache.get('userData').hisHospID,
                    locID: app.globalData.locObj.locID,
                    userID: "",
                    imageFlag: "Y",
                    date: app.globalData.schDate
                }]
            }
            $http.post("urlS", self, {
                namespace: "Y",
                code: "03100040",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        self.setData({
                            schDateKey: res.result.length > 0 ? res.result[0].resDetailID : "",
                            time: res.result.length > 0 ? res.result[0].timeDatail : "",
                        }, () => {
                            setTimeout(() => {
                                self.getPayAmt();
                            }, 500)
                            // this.healthPayAmt(); 
                            self.getIp();
                        });
                        app.globalData.writeObj.schDateKey = res.result.length > 0 ? res.result[0].resDetailID : "";
                    } else {
                        self.setData({
                            schDateKey: ""
                        });
                    }
                }
            });
        }),

        // 获取医生收费金额
        getPayAmt() {
            // console.log(12321321, this.data.flag, this.data.schDateKey, this.data.schTimeKey)
            const { patObj } = this
            const userData = this.$cache.get('userData')
            let data = {
                params: [{
                    locResDetailID: this.flag ? this.schDateKey : this.schTimeKey,
                    patID: patObj && patObj.patID ? patObj.patID : userData.patID,
                    hisPatNo: patObj && patObj.hisPatNo ? userData.hisPatNo : userData.hisPatNo,
                }]
            }
            $http.post("urlS", this, {
                namespace: "Y",
                code: "03100105",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setData({
                            payAmtInt: Number(res.result).toFixed(2)
                        });
                    } else {
                        Utils.showToast(res.errorMessage, 'none')
                    }
                }
            });
        },

        // 获取医保付费金额
        healthPayAmt() {
            let data = {
                params: [{
                    appointID: this.schDateKey ? this.schDateKey : this.schTimeKey,
                    // hisHospID:this.data.hisHospID,
                    // userCode: this.$cache.get('userData').userCode,
                }]
            }
            $http.post("urlS", this, {
                code: "01050005",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        // console.log("获取医保付费金额", res)
                        this.setData({
                            healthPayAmt: res.result && res.result.priceAmt ? Number(res.result.priceAmt).toFixed(2) : 0
                        });
                    } else {
                        this.setData({
                            healthPayAmt: 0
                        });
                    }
                }
            });
        },

        // 或取医保卡绑定openID以及跳转路径
        getOpenIDAndRouter() {
            let userData = this.$cache.get('userData');
            let data = {
                params: [{
                    pubAccCode: userData.pubAccCode || '',
                    openID: userData.openID || '',
                }]
            }
            $http.post("urlS", this, {
                code: "01050010",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let result = res.result;
                        uni.navigateToMiniProgram({
                            appId: result.bind_appid || '',
                            path: result.bind_url || '',
                            envVersion: 'release',
                            success(res) {
                                // 打开成功
                            },
                            fail: (error) => {
                                Utils.showToast('跳转绑定电子医保卡界面失败，请稍后重试。', 'none')
                            }
                        })
                    }
                }
            });
        },

        // 支付
        pay: Utils.debounce(function (admReasonCode, orderNo, callback) {
            let userData = this.$cache.get('userData');
            if (!isPayment) {
                return;
            }
            isPayment = false;
            var imageAddress = "";
            for (var i = 0; i < this.fileList.length; i++) {
                if (imageAddress === "") {
                    imageAddress = this.fileList[i].path
                } else {
                    imageAddress = imageAddress + "&" + this.fileList[i].path
                }
            }
            let entrance = this.entrance;
            let data = {
                params: [{
                    authCode: app.globalData.authCode, // 医保支付授权码
                    cityCode: userData.cityCode, // 医保城市编码
                    channel: userData.channel, // 医保渠道号
                    totalFee: this.payAmtInt,
                    ipAddress: this.motto,
                    appointID: this.flag ? this.schDateKey : this.schTimeKey,
                    body: this.flag ? (entrance === '2' ? '图文咨询' : '免费咨询') : (entrance === '3' ? '视频问诊' : "预约挂号"),
                    businessType: this.flag ? "TWWZ" : (entrance === '3' ? "SPWZ" : "REGPAY"), // REGPAY - 预约挂号
                    patID: this.patObj && this.patObj.hisPatID ? this.patObj.hisPatID : '',
                    patNo: this.patObj && this.patObj.hisPatNo ? this.patObj.hisPatNo : '',
                    patName: this.patObj && this.patObj.patName ? this.patObj.patName : '',
                    idCardNo: this.patObj && this.patObj.idCardNo ? this.patObj.idCardNo : '',
                    mobile: this.patObj && this.patObj.mobile ? this.patObj.mobile : '',
                    insuFlag: admReasonCode,
                    medicalcardid: this.medCardID,
                    data: {
                        code: "03100041",
                        params: [{
                            resTimeID: this.schTimeKey,
                            resDetailID: this.schDateKey,
                            hospCode: userData?.hisHospID || hisHospID,
                            patID: this.patObj && this.patObj.hisPatID ? this.patObj.hisPatID : '',
                            patName: this.patObj && this.patObj.patName ? this.patObj.patName : '',
                            patNo: this.patObj && this.patObj.hisPatNo ? this.patObj.hisPatNo : '',
                            bookMethodID: "Y",
                            bookMethodID: "Win",
                            insuFlag: admReasonCode,
                            orderNo: orderNo,
                            symptom: {
                                illnessTime: this.disesTime ? this.disesTime : '',
                                symptom: this.disesNote,
                                imageAddress: imageAddress,
                                appointID: this.flag ? this.schDateKey : this.schTimeKey,
                                AllergyFlag: this.checked ? "Y" : "N",
                                AllergyDesc: this.drugName || "",
                                DiseaseDesc: this.checkBoxDesc || ""
                            },
                            paywStr: [{
                                payWayCode: "WECHAT",
                                payWayID: "",
                                payWayAmt: this.payAmtInt // admReasonCode === '02' ? this.healthPayAmt :
                            }],
                        }],
                    },
                }]
            }
            uni.showLoading({
                title: '结算中,请稍后',
                mask: true
            })
            console.log('预结算参数')
            console.log(data)
			return
            // $http.post("urlS", this, {
            //     code: "01050002",
            //     data: data,
            //     success: function (res) {
            //         console.log('预结算返回值：')
            //         console.log(res)
            //         uni.hideLoading();
            //         app.globalData.authCode = '' //医保授权置空
            //         if (+res.errorCode === 0) {
            //             app.globalData.disesNote = ''
            //             this.setData({
            //                 payTradeNum: res.result.payTradeNum ? res.result.payTradeNum : '',
            //                 prescribeTradeNum: res.result.prescribeTradeNum ? res.result.prescribeTradeNum : '',
            //                 cashamt: res.result.cashamt ? res.result.cashamt : 0,
            //                 insuamt: res.result.insuamt ? res.result.insuamt : 0,
            //                 insuGRBalance: res.result.insuGRBalance ? res.result.insuGRBalance : 0
            //             }, () => {
            //                 if (admReasonCode === '02') {
            //                     if (res.result.payFlag == 'Y') {
            //                         // this.demoTest()
            //                         this.toJumpHealthPay(res.result) // 跳转医保待支付待结算详情页
            //                     } else {
            //                         this.getPayStatus("gotoView");
            //                         // this.gotoView();
            //                     }
            //                 } else {
            //                     if (+this.data.payAmtInt !== 0) {
            //                         this.wechatPay(res.result).then(() => {
            //                             typeof callback == 'function' && callback()
            //                         })
            //                     } else {
            //                         this.getPayStatus("gotoView");
            //                         // this.gotoView();
            //                     }
            //                 }
            //             })
            //         } else {
            //             uni.hideLoading();
            //             Utils.showToast(res.errorMessage + '，请稍后重试', 'none')
            //             isPayment = true;
            //         }
            //     },
            //     error: function (error) {
            //         // console.log(error)
            //         uni.hideLoading();
            //         isPayment = true;
            //     }
            // });
        }),

        // 医保移动支付获取授权码
        getAuthCode() {
            this.setData({
                payTradeNum: '', // 清空单号
                prescribeTradeNum: '', // 清空单号
                admReasonCode: '02'
            })
            Utils.getAuthCode()
        },

        toJumpHealthPay: Utils.debounce(function (data) {
            if (typeof data == 'object') {
                data['flag'] = this.flag
                data['payAmtInt'] = this.payAmtInt
                data['payTradeNum'] = this.payTradeNum
                data['prescribeTradeNum'] = this.prescribeTradeNum
            }
            uni.navigateTo({
                url: "/pages/index/pages/videoConsultation/waitYbSettlement/index",
                success: (res) => {
                    // console.log('writeDiseCon settlmentData')
                    // console.log(data)
                    res.eventChannel.emit('settlmentData', {
                        settlmentData: data
                    })
                },
            })
        }),

        // 获取支付状态
        getPayStatus(btnType) {
            let self = this;
            let userData = this.$cache.get('userData');
            let {
                infoByTrandNo,
                infoByTrandNoFlag
            } = self.data;
            if (!infoByTrandNoFlag) {
                infoByTrandNo++
                self.setData({
                    infoByTrandNo
                })
                // console.log(self.data.infoByTrandNo)
                if (self.infoByTrandNo > 5) {
                    uni.hideLoading();
                    self.setData({
                        infoByTrandNo: 0
                    })
                    isPayment = true
                    return
                }
            }
            let data = {
                params: [{
                    hospitalCode: userData.hisHospID || '',
                    userCode: "wxsf",
                    payTradeNum: this.payTradeNum
                }]
            }
            uni.showLoading({
                title: '订单状态查询中',
                mask: true
            })
            $http.post("urlS", this, {
                code: "130980",
                data: data,
                namespace: "UPP",
                success: function (res) {
                    // console.log(res)
                    isPayment = true;
                    if (res.errorCode == 'UN') {
                        uni.showToast({
                            icon: "error",
                            title: res.errorMessage,
                            duration: 5000,
                        })
                    } else if (+res.errorCode === 0) {
                        //# ifdef MP-ALIPAY
                        // 服务办结
                        monitor.api({
                            api: "预约挂号",
                            success: true,
                            c1: "taSR_YL",
                            time: Math.floor(Math.random() * 100 + 50)
                        })
                        //# endif
                        uni.hideLoading();
                        this.setData({
                            infoByTrandNoFlag: true
                        }, () => {
                            if (btnType === "gotoView") {
                                this.gotoView();
                            } else if (btnType === "wechatPay" || btnType === "healthPay") {
                                uni.reLaunch({
                                    url: '../../../common/paySuccess/paySuccess?payAmtInt=' + self.payAmtInt + '&flag=' + self.flag + '&payTradeNum=' + self.payTradeNum + '&prescribeTradeNum=' + self.prescribeTradeNum
                                })
                            }
                        })
                    } else if (res.errorCode == 'UN') { // 医保支付成功，HIS保存未成功，跳转账单已缴费页面
                        uni.switchTab({
                            url: '../../pages/tabBar/order/order?tab=1',
                        })
                    } else if (res.errorCode == 'NOTPAY') {
                        self.resetData(res.errorMessage)
                    } else {
                        if (self.infoByTrandNo == 5) {
                            self.resetData(res.errorMessage)
                        } else {
                            self.getPayStatus(btnType)
                        }
                    }
                },
                error: function (error) {
                    self.resetData("失败，稍后重试")
                }
            });
        },

        resetData(errorMessage) {
            uni.hideLoading()
            isPayment = true;
            Toast({
                context: this,
                message: errorMessage
            });
            this.setData({
                payTradeNum: '',
                prescribeTradeNum: ''
            })
        },

        // 不需要调用微信
        gotoView() {
            // console.log("gotoView-uni.reLaunch")
            let self = this;
            uni.reLaunch({
                url: '../../../common/paySuccess/paySuccess?payAmtInt=' + self.payAmtInt + '&flag=' + self.flag + '&payTradeNum=' + self.payTradeNum + '&prescribeTradeNum=' + self.prescribeTradeNum
            })
        },

        // 微信支付调用
        wechatPay(data) {
            let self = this;
            console.log("微信支付参数")
            console.log(data)
            return new Promise((resolve, reject) => {
                uni.requestPayment({
                    timeStamp: data.timeStamp + "",
                    nonceStr: data.nonceStr,
                    package: data.package,
                    signType: data.signType,
                    paySign: data.paySign,
                    success(res) {
                        console.log('pay success', res)
                        self.getPayStatus("wechatPay");
                        resolve()
                    },
                    fail(err) {
                        isPayment = true;
                        console.log('pay fail', err)
                        Utils.abnormalOrderDeal(data) // 取消未支付订单
                        reject()
                    }
                })
            })
        }
    }
}
</script>

<style>

</style>