import {
    json
} from "../../utils/ajax";
import store from '@store';
import {MODI_LOADING} from '@store/types/homePage.js';
import Notify from '@commonComp/Notify';
import {
    getAllDataList,
    getAllDataStringList,
    pushAllDataList,
    filterDataArr,
    filterOtherDataArr
} from '@utils/tools';
export const getConceptDetails = (bool) => {
    let baseList = store.getState();
    let disLis = baseList.diagnosticList.diagnosticList||[];
    let tmpLis  = [];
    for(let i = 0;i < disLis.length;i++){
        let obj = {}
        obj.name = disLis[i].name
        obj.type = 7
        obj.position = 3
        tmpLis.push(obj)
    }
    json('/conceptDetail/getConceptDetails', {
        "conceptIntorduces": tmpLis
    }).then((res)=>{//conceptIntroduceDTO
        let data = res.data;
        if (data.code == 0) {
            realSaveData(bool,data.data)
        } else {
            console.log(res)
            realSaveData(bool)
        }
    }).catch((err)=>{
        realSaveData(bool)
        console.log(err)
    })
}
export const saveMessage=(bool)=>{
    store.dispatch({type:MODI_LOADING,flag:true});
    getConceptDetails(bool)
}
export const realSaveData = (bool,list) => {
    let baseList = store.getState();
    const dConfig = baseList.typeConfig;
    const readMode = dConfig.readMode;          //回读模式
    let state = baseList.patInfo.message;
    //保存时保存当前的数据实际模式，不是系统模式，针对回读模式与系统模式不一致的情况处理
    let whichSign = readMode===-1||readMode===null?dConfig.mode:readMode;
    const pushMessage = baseList.pushMessage;
    let jsonStr = getAllDataStringList(baseList);
    let jsonData = getAllDataList(baseList);
    const lisData = baseList.inspect.pushItem;
    const lisArr = transferIndexData(lisData);
    const haveAssess = Object.keys(baseList.assessResult.data).length>0;
    let otherData = {},pacsData={};
    const docConfigs = dConfig.readConfig===-1||!dConfig.readConfig?dConfig.typeConfig:dConfig.readConfig;
    const evaluation={
      htmlContent:haveAssess?JSON.stringify(getEvaluations(baseList.assessResult,pushMessage)):'{}',
      //scaleList:[]
    };//getEvaluation();
    //console.log(baseList)
    // console.log(jsonStr.diag,'保存历史病历')
    otherData['yjs_1']=jsonData['yjs_1']||''
    otherData['yjs_2']=jsonData['yjs_2']||''
    otherData['yjs_3']=jsonData['yjs_3']||''
    otherData['yjs_4']=jsonData['yjs_4']||''
    otherData['haveAssess']=haveAssess
    otherData['pfix']=jsonStr.other?filterOtherDataArr(JSON.parse(jsonStr.other),jsonData.other):''
    pacsData.pacs = jsonData.pacs
    pacsData.checkedListImport = jsonData.checkedListImport;
    json('/inquiryInfo/saveInquiry', {
        "doctorId": state.doctorId,
        "conceptIntroduceDTO":list||[],
        "hospitalDeptId": state.hospitalDeptId,
        "hospitalId": state.hospitalId,
        "patientId": state.patientId,         //患者id              
        "dataJson": JSON.stringify(Object.assign({haveAssess:haveAssess,docConfigs:docConfigs},jsonData)),
        "indexData":lisArr,
        "inquiryEvaluation":evaluation,
        "detailList": [{
            "content": jsonStr.chief,
            "contentValue":filterDataArr(JSON.parse(jsonStr.chief)),
            "contentJson":'',
            "type": 1
        }, {
            "content": jsonStr.present,
            "contentValue":filterDataArr(JSON.parse(jsonStr.present)),
            "contentJson":'',
            "type": 2
        }, {
            "content": jsonStr.other,
            "contentValue":filterDataArr(JSON.parse(jsonStr.other)),
            "contentJson":JSON.stringify(otherData),
            "type": 3
        }, {
            "content": jsonStr.vital,
            "contentValue":filterDataArr(JSON.parse(jsonStr.vital)),
            "contentJson":'',
            "type": 4
        }, {
            "content": jsonStr.lis,
            "contentValue":jsonStr.lis,
            "contentJson":JSON.stringify(jsonData.lis),
            "type": 5
        }, {
            "content": jsonStr.pacs,
            "contentValue":jsonStr.pacs,
            "contentJson":JSON.stringify(pacsData),
            "type": 6
        }, {
            "content": jsonStr.diag,
            "contentValue":jsonStr.diag,
            "contentJson":'',
            "type": 7
        }, {
            "content": jsonStr.advice,
            "contentValue":jsonStr.advice,
            "contentJson":JSON.stringify(jsonData.advice),
            "type": 8
        }],
        "sign": whichSign, //类型0结构化 1文本
        "diagnose": (jsonData.diag.length > 0 ? jsonData.diag[0].name : ''), //诊断
        "inquiryCode": state.recordId, //就诊序列号
        "drugList":baseList.pushMessage.advice.drugList || [],//药品列表
        // "regVisitedState": 0,      //就诊状态
        // "type": 0,
    }).then((res) => {
        let data = res.data
        if (data.code == 0) {
            if(!bool){
                Notify.success('历史病历保存成功');
            }
        } else {
          Notify.info(data.msg);
        }
        store.dispatch({type:MODI_LOADING,flag:false});
    }).catch(function(){
        store.dispatch({type:MODI_LOADING,flag:false});
        Notify.info('保存失败，请稍后再试！');
    });
    if(bool){
        json('/printRecord/savePrintRecords', {
            "dataJson": JSON.stringify(getAllDataList(baseList)),
            "doctorId": state.doctorId,
            "hospitalDeptId": state.hospitalDeptId,
            "hospitalId": state.hospitalId,
            "inquiryCode": state.recordId, //就诊序列号
            "name": (jsonData.diag.length > 0 ? jsonData.diag[0].name : ''), //诊断
            "patientId": state.patientId, //患者id              
            "type": whichSign, //类型0结构化 1文本
            "content": {
                "advice": jsonStr.advice,
                "chief": jsonStr.present,
                "diag": jsonStr.diag,
                "lis": jsonStr.lis,
                "other": jsonStr.other,
                "pacs": jsonStr.pacs,
                "present": jsonStr.present,
                "vital": jsonStr.vital
            },
        }).then((res) => {
            let data = res.data
            if (data.code == 0) {
                console.log('打印记录保存成功')
            } else {
                console.log(res)
            }
        })
    }
};

//转换化验指标保存需要的数据
function transferIndexData(data) {
    const arr=[];
   data.map((it)=>{
       if(it.uniqueName&&it.value!=''){
           arr.push({
             creatTime:it.time+':00',
             indexUnique:it.uniqueName,
             indexUnit:it.units,
             indexValue:it.value,
             isAbnormal:(it.maxValue||it.minValue)?(it.value<it.minValue||it.value>it.maxValue?1:0):0
           });
       }
   });
   return arr;
}

function getEvaluations(base,pushMessage){
    let obj = [];
    Object.keys(base.wholeIndexs).map((i)=>{
      obj[i]=pushMessage.chronicPushItems[i];
    });
    return {
      data:base.data,
      chooseSelecteds:base.chooseSelecteds,
      indexTimeTypes:base.indexTimeTypes,
      wholeAssess:obj,
      wholeAssessText:base.wholeAssessText,
      wholeIndexs:base.wholeIndexs,
      scaleInfo:pushMessage.scaleInfo,
      scaleResult:pushMessage.formulaResult,
      wholeResults:base.wholeResults,
      calcuResult:base.calcuResult,
      calcuValues:base.calcuValues,
      scaleItems:base.wholeScaleItems,
    };
}

export const clearMessages = () => {
    let baseList = store.getState();
    let whichSign = baseList.typeConfig.mode;
    pushAllDataList(whichSign,'clear');
};