import request from '@/utils/request.js'
import {fromAnalysisModel} from "@/model/tongue-analysis.model";
import {removeRedundantSemicolons} from '@/api/hack';
import {generateUUID} from '@/utils';

// 获取就诊病人信息
export function getPatiiensMsg(data) {
    return request({
        url: `/outpatient/recordsMgr/${data}`,
        method: 'get',

    })
};

// 获取中医电子病历回显信息
export function getEmrShowMsg(data) {
    return request({
        url: `/outpatient/electronicmedicalrecordMgr/infoByRecordsId?recordsId=${data.recordsId}`,
        method: 'post',
        data
    })
};

// 获取自然语义分析 中医电子病历回显信息
export function getNLP_TemplateResult(text) {
    const [_, method, url ] = (window.SIX_config.NLP_GET_URL || '').match(/^(?:\[(\w*)])?\s*(.*)?/) || [];
    return request({
        url: url || `https://dev.hzliuzhi.com:62006/tcm_chat/json/record`,
        method: method || 'post',
        data: {
            message: text,
        },
        meta: { ignoreResponse: true },
    }).then(res => {
        if (res.code === 200) {
            const {fourmedicine: value, ...data} = res.data;
            return {
                ...data,
                echoData: value ? typeof value === 'string' ? value : JSON.stringify(value) : '{}',
            };
        }
        throw new Error(res.message);
    });
}

export function getASR_Token() {
    try {
        let token = localStorage.getItem('ASR_TOKEN');
        if (token) {
            const proof = JSON.parse(token);
            if (Math.round(Date.now() / 1000) < proof.expireTime) return proof;
        }
    } catch (e) {}
    const [_, method, url ] = (window.SIX_config.SST_TOKEN_URL || '').match(/^(?:\[(\w*)])?\s*(.*)?/) || [];
    return request({
        url: url || `https://dev.hzliuzhi.com:62006/tcm_chat/asr/token`,
        method: method || 'get',
        meta: { ignoreResponse: true },
    }).then(res => {
        if (res.code === 200) {
            if (!res.data.appKey) res.data.appKey = `zF5fGsgjoAXnL7F3`;
            localStorage.setItem('ASR_TOKEN', JSON.stringify(res.data));
            return res.data;
        }
        localStorage.removeItem('ASR_TOKEN');
        throw new Error(res.message);
    });
}

export function connectASR_WebSocket(proof) {
    return new WebSocket(`wss://nls-gateway.cn-shanghai.aliyuncs.com/ws/v1?token=${proof.token}`);
}


// 提交诊断页面数据
export function addDiagnosisData(data) {
    return request({
        url: '/outpatient/diagnosisMgr/Add',
        method: 'post',
        data
    })
};

export function addDiagnosisData2(data) {
    return request({
        url: '/outpatient/diagnosisMgr/Add',
        method: 'post',
        data,
    }).then(res => {
        if (res.ResultCode !== 0) throw Error(res.ResultInfo || `错误`);
        if (!res.Data.mainDiagnosis) return {mainDiagnosis: res.Data};
        return res.Data;
    });
}

// 修改诊断页面数据
export function editDiagnosisData(data) {
    return request({
        url: '/outpatient/diagnosisMgr/update',
        method: 'post',
        data
    })
};

// 开方获取患者基本信息
export function getPatiensBasisM(data) {
    return request({
        url: '/test/outpatient/patientBaseInfo?patientId=' + data.patientId,
        method: 'post',
        // data
    }).then(res => removeRedundantSemicolons(res));
};

// 刷新电子病历信息
export function refreshElectronicInfo(data) {
  return request({
    url: '/test/outpatient/refreshElectronicInfo?patientId=' + data.patientId,
    method: 'post',
    ignoreErrorMessage: '请重试',
  }).then(res => {
    if (res.ResultCode !== 0) throw Error(res.ResultInfo || `请重试`);
    if (res.Data == null) throw Error(`暂无新数据，请稍后刷新`);
    const {pulseDiagnosisReportVo, ..._data} = res.Data;
    const data = removeRedundantSemicolons(_data);
    return data.outpatientElectronicmedicalrecord != null ? data : {
      outpatientElectronicmedicalrecord: data,
      pulseDiagnosisReportVo,
    };
  });
}


// 获取表格 药品列表
export function getTableDrug(data, isPurposeType = false) {
    if (isPurposeType) {
        data.name = data.key;
        return request({
            url: '/basis/stitutionsdrugMgr/materialQuery',
            method: 'post',
            data
        }).then(res => {
            const data = Array.isArray(res.Data) ? res.Data : [];
            res.Data = {
                TotalRecordCount: data.length,
                TotalPageCount: 1,
                PageSize: data.length,
                ButtonRight: "",
                CurrentPageSize: data.length,
                PageIndex: 1,
                Items: data.map(item => {
                    return {
                        pid: item.drugId,
                        matid: item.drugId,
                        ypmc: item.name,
                        gg: item.gg,
                        dw: item.dw,
                        price: item.price || '',
                    }
                })
            };
            return res;
        })
    }
    return request({
        url: '/test/outpatient/selectDrug?page=' + data.page + '&limit=' + data.limit,
        method: 'post',
        data
    })
};

//添加处方

export function addRecipe(data) {
    return request({
        url: '/test/outpatient/addOutPatient',
        method: 'post',
        data
    })
};

//获取诊断页 回显数据
export function getDiagnosisShowData(data) {
    return request({
        url: '/outpatient/diagnosisMgr/infoByRecordsId?recordsId=' + data.recordsId,
        method: 'post',

    })
};

// 获取处方回显数据
export function getRecipeShowData(data) {
    return request({
        url: '/test/outpatient/getPrescription/' + data,
        method: 'get'
    })
};

// 通过 处方id 获取处方回显数据
export function getRecipeDataByid(data) {
    return request({
        url: `/outpatient/patientprescriptionMgr/${data.pid}`,
        method: 'get'
    })
};


// 添加中医电子病历
export function addEMR(data) {
    return request({
        url: '/outpatient/electronicmedicalrecordMgr/Add',
        method: 'post',
        data: removeRedundantSemicolons(data),
    })
};

// 修改中医电子病历信息
export function editEMR(data) {
    return request({
        url: '/outpatient/electronicmedicalrecordMgr/update',
        method: 'post',
        data: removeRedundantSemicolons(data),
    })
};

// 回传his
export function backToHis(data) {
    return request({
        url: '/outpatient/electronicmedicalrecordMgr/electronicmedicalRecordsReturnHis',
        method: 'post',
        data
    })
}

// 寄到本院 获取地址
export function getAddressForHospital(data) {
    return request({
        url: '/test/outpatient/getAddress',
        method: 'post',
        data
    })
}

// 获取体质辨识列表接口 
export function getPhysicalList(data) {
    return request({
        url: '/outpatient/identificationMgr/listPain?page=' + data.page + '&limit=' + data.limit + '&name=' + data.name,
        method: 'post',
        data
    })
};

// 获取某i个用户的体质辨识记录
export function getUserPhysicList(data) {
    return request({
        url: '/outpatient/identificationMgr/listPainInfo?patientId=' + data.patientId + '&limit=' + data.limit + '&page=' + data.page,
        method: 'post',
        data
    })
};

//体质辨识 添加
export function addPhysicalList(data) {
    return request({
        url: '/outpatient/identificationMgr/Add',
        method: 'post',
        data
    })
};

// 获取体质辨识 详情
export function getPhysicalDetail(data) {
    return request({
        url: `/outpatient/identificationresultMgr/${data.identid}`,
        method: 'get'
    })
};

// 获取体质辨识 详情
export function getPhysicalDetailGy(data) {
    return request({
        url: `/outpatient/identificationMgr/selecthealthInterventionBydentificationId?dentificationId=${data.dentificationId}`,
        method: 'post',
        data
    })
};

// 提交体质辨识 医生建议
export function submitDoctorjy(data) {
    return request({
        url: '/outpatient/identificationresultMgr/update',
        method: 'post',
        data
    })
};

// 提交健康干预
export function submitDoctorGy(data) {
    return request({
        url: '/outpatient/identificationMgr/SavehealthIntervention',
        method: 'post',
        data
    })
}

// 删除体质辨识记录
export function deletePhysicRecord(data) {
    return request({
        url: '/outpatient/identificationMgr/BatchDelete?ids=' + data.ids,
        method: 'post',
        data
    })
};

//根据选择的中药类型查询所属药房id
export function getPharmacyID(data) {
    return request({
        url: '/basis/pharmacyMgr/getPidBytype?type=' + data.type,
        method: 'post',
        data
    })
};

// 切换药房 id
export function changePharmacy(data) {
    if (data && Array.isArray(data.drugIds) && data.drugIds.length === 0) return Promise.resolve({
        "Data": [],
        "ResultInfo": "操作成功",
        "ResultCode": 0
    });
    return request({
        url: '/test/outpatient/changeDrug',
        method: 'post',
        data
    })
};

// 获取开方界面协定方数据
export function getAgreeRecipe(data) {
    return request({
        url: '/test/outpatient/getPres?page=' + data.pageId + '&limit=' + data.pageSize,
        method: 'post',
        data
    })
};

// 根绝就诊记录id 获取就诊信息
export function getSeeDByID(data) {
    return request({
        url: '/test/outpatient/byRecId',
        method: 'get',
        params: data
    })
};

// 获取病历详情数据
export function getRecordDetail(data) {
    return request({
        url: '/outpatient/CaseManagement/' + data.id,
        method: 'get',
        params: data
    })
}
// 获取药品详细信息
export function getDrugDetail(data) {
    return request({
        url: '/basis/stitutionsdrugMgr/stiDrugInfo?stiDrugId=' + data.stiDrugId,
        method: 'post',
        data
    })
};

//开方界面获取协定方详细信息
export function getAccordDetail(data) {
    return request({
        url: '/test/outpatient/preInfo',
        method: 'get',
        params: data
    })
};

// 获取我最常用 
export function getMyOfenUse(data) {
    return request({
        url: '/test/outpatient/myused',
        method: 'get',
        params: data
    })
};


//协定方 转方 判断
export function changeBasisPre(data) {
    return request({
        url: '/test/outpatient/changeBasisPre',
        method: 'post',
        data
    })
};

//专家经验转方判断
export function changeExpre(data) {
    return request({
        url: '/test/outpatient/changeExpPre',
        method: 'post',
        data
    })
}

// 处方修改
export function updateRecipe(data) {
    return request({
        url: '/test/outpatient/update',
        method: 'post',
        data
    })
};

// 开方页面选择药房
export function customerQuery(data) {
    return request({
        url: "/basis/pharmacyMgr/customerQuery?type=" + data.type,
        method: 'post',
        data
    })
}


//智能辨证 问卷临时存储 
export function znQuestionSave(data) {
    return request({
        url: '/smartDialecticalQuestionnaireTempSave/tempSave',
        method: 'post',
        data
    })
}

// 只能辨证 问卷回显
export function znQusetionShow(data) {
    return request({
        url: `/smartDialecticalQuestionnaireTempSave/echoData/${data.recordId}`,
        method: 'get',
        params: data
    })
};

// 处方是否支付
export function recipeIsPay(params) {
    return request({
        url: `/outpatient/pay/checkPrescriptionPaymentStatus`, //params.preId // ${JSON.stringify(params)}
        method: 'post',
        // params
        data: params
    })
}

// 根据就诊记录id 查询 是否有处方
export function getPreNumber(params) {
    return request({
        url: `/outpatient/recordsMgr/getPrescriptionNumberByRecordId/${params.pid}`,
        method: 'get',
        params
    })
}

// 获取药房 共享药房和 本地药房id
export function getPharmacyIDS(params) {
    return request({
        url: `/basis/pharmacyMgr/getPharmacyIds`,
        method: 'get',
        params
    })
}

// 提交处方预览
export function getRecipePriview(data) {
    return request({
        url: `/test/outpatient/addOutPatientPreview`,
        method: 'post',
        data
    })
}

// 专家/协定方转为开方查询接口
export function getRecipeByBasis(data) {    
    return request({
        url: `/test/outpatient/changeStAccordPre`,
        method: 'post',
        data
    })
}


//适宜技术病历转方
export function getRecipeBySuitTech(data) { 
    return request({
        url: `/test/outpatient/changeStRecordPre`,
        method: 'post',
        data
    })
}

// 获取中药制剂 包装单位 
export function getBzdw(params) {
    return request({
        url: '/test/outpatient/getBZDW',
        method: 'get',
        params
    })
}

// 获取健康跟踪记录 详情 
export function getHealthTrack(data) {
    return request({
        url: '/outpatient/identificationMgr/getHealthTrackingRecordBydentificationId?page=' + data.page + '&limit=' + data.limit + '&dentificationId=' + data.dentificationId,
        method: 'post',
        data
    })
}

// 新增健康跟踪记录
export function addHealthTrack(data) {
    return request({
        url: '/outpatient/identificationMgr/addHealthTrackingRecord',
        method: 'post',
        data
    })
}

// 获取主要体质
export function getMainPhysical(data) {
    return request({
        url: '/outpatient/identificationMgr/getAnalysisGroupItemName',
        method: 'get'
    })
}

// 中医体质统计分析
export function getPhysicalTotalList(data) {
    return request({
        url: '/outpatient/identificationMgr/statisticalList?page=' + data.page + '&limit=' + data.limit,
        method: 'post',
        data
    })
}

// 中医体质统计分析导出
export function exportPhysicalTotal(data) {
    return request({
        url: '/outpatient/identificationMgr/statisticalListExport?page=' + data.page + '&limit=' + data.limit,
        method: 'post',
        data
    })
}

// 中医体质分析详情 生成PDF
export function createPdf(data) {
    return request({
        url: '/PDF/PDF',
        method: 'post',
        data
    })
}

// 查询是否健康干预锅
export function findIsHealthGY(data) {
    return request({
        url: `/outpatient/identificationresultMgr/healthInterventionOrNot/${data.identid}`,
        method: 'get',
        params: data
    })
}

// 获取医保规则最大(最小)药味数
export function getMaxMinDoaseNumber(data) {
    return request({
        url: '/basis/medicalInsuranceRegulationMgr/minimumAndMaximumDosageNumber',
        method: 'post',
        data
    })
}

// 获取合理安全用药规则
export async function getRationalSafeUse() {
    return request({
        url: '/basis/medicalInsuranceRegulationMgr/minimumAndMaximumDosageNumber',
        method: 'post',
    })
}

export function getTongueAndFaceAnalysis(data) {
    return request({
        url: '/outpatient/electronicmedicalrecordMgr/getTongueFaceAnalysisResult',
        method: 'post',
        data,
        params: {recordsId: data.recordsId},
    }).then(res => {
        if (res.ResultCode == 0) {
            const tongue = fromAnalysisModel('tongue', res.Data);
            const face = fromAnalysisModel('face', res.Data);
            return res.Data = {
                id: res.Data.recordsid,
                time: res.Data.recordstime,
                tongue,
                face,
                cover: [tongue ? tongue.cover : null, face ? face.cover : null].filter(Boolean).flatMap(item => item),
            }, res;
        } else {
            throw res
        }
    })
}

export function getTongueAndFaceAnalysisRecords(patientId, page = 1, limit = 6) {
    // patientId = '8d12c55e-7a29-45f3-804d-ed12b0e27660'
    return request({
        url: '/outpatient/electronicmedicalrecordMgr/getRecordTfs',
        method: 'post',
        params: {patientId, page, limit},
    }).then(res => {
        if (res.ResultCode == 0) {
            return {
                total: res.Data.TotalRecordCount,
                data: res.Data.Items.map(item => {
                    const tongue = fromAnalysisModel('tongue', item);
                    const face = fromAnalysisModel('face', item);
                    return {
                        id: item.recordsid,
                        time: item.recordstime,
                        tongue,
                        face,
                        cover: [tongue ? tongue.cover : null, face ? face.cover : null].filter(Boolean).flatMap(item => item),
                    }
                }),
            }
        } else {
            throw res
        }
    })
}