import {
    json
} from "../../utils/ajax";
import store from '@store';
import {MODI_LOADING} from '@store/types/homePage.js';
import { CLEARMEDICALNAME } from '@store/types/patInfo.js';
import Notify from '@commonComp/Notify';
import {tellPred} from '@store/async-actions/preIcss.js';
import {
  getAllDataList,
  getAllDataStringList,
  pushAllDataList,
  filterDataArr,
  filterOtherDataArr,
  timestampToTime,
  formatTextInfo,
  delHistoryDataList,
} from '@utils/tools';
import { embedPush } from '@store/async-actions/pushMessage'
export const getConceptDetails = (bool) => {
    let baseList = store.getState();
    let isPreIcss = baseList.typeConfig.isPreIcss;
    if(isPreIcss){
        tellPred()
    }
    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 {
            realSaveData(bool)
        }
    }).catch((err)=>{
        realSaveData(bool)
    })
}
export const saveMessage = (bool) =>{
    return (dispatch) =>{
       return new Promise((resolve, reject) => {
         saveMedicalData()
           .then(res => {
             resolve();
           })
           .catch(err => {
            //  console.log(err, 'data.code');
           });
       });
    }
}

// 获取参数value
function formatFormParmas(val,arr){
    let item = arr.length!==0 && arr.find(item=>{
       return item.id === val
    })
    return item.value
}

// 保存病历_lcq_new_重写
export const saveMedicalData = () =>{
    let baseList = store.getState();
    const { patInfo: { patInfoData },homePage:{curHos}} = baseList;
    let inquiryDate = timestampToTime(new Date().getTime())  // 获取当前时间  
    let modeName = baseList.patInfo.medicalName   //病历名称
    let jsonData = getAllDataList(baseList);
    let tempPreview = formatTextInfo(baseList);
    // console.log(tempPreview, 'tempPreview');
    let preview = [
      {
        content: tempPreview.chief,
        contentValue: filterDataArr(JSON.parse(tempPreview.chief)),
        contentJson: '',
        type: 1,
      },
      {
        content: tempPreview.present,
        contentValue: filterDataArr(JSON.parse(tempPreview.present)),
        contentJson: '',
        type: 2,
      },
      {
        content: tempPreview.pastHistory,
        contentValue: filterDataArr(JSON.parse(tempPreview.pastHistory)),
        contentJson: '',
        type: 3,
      },
      {
        content: tempPreview.personalHistory,
        contentValue: filterDataArr(JSON.parse(tempPreview.personalHistory)),
        contentJson: '',
        type: 4,
      },
      {
        content: tempPreview.familyHistory,
        contentValue: filterDataArr(JSON.parse(tempPreview.familyHistory)),
        contentJson: '',
        type: 5,
      },
      {
        content: tempPreview.marriageHistory,
        contentValue: filterDataArr(JSON.parse(tempPreview.marriageHistory)),
        contentJson: '',
        type: 6,
      },
      {
        content: tempPreview.menstruationHistory,
        contentValue: filterDataArr(JSON.parse(tempPreview.menstruationHistory)),
        contentJson: '',
        type: 7,
      },
      {
        content: tempPreview.vital,
        contentValue: filterDataArr(JSON.parse(tempPreview.vital)),
        contentJson: '',
        type: 8,
      },
      // 化验
      {
        content: tempPreview.lis,
        contentValue: tempPreview.lis,
        contentJson: JSON.stringify(tempPreview.lis),
        type: 9,
      },
      {
        content: tempPreview.pacs.dataString,
        contentValue: tempPreview.pacs.assistLabel,
        contentJson: JSON.stringify(tempPreview.pacs.dataString),
        type: 10,
      },
      {
        content: tempPreview.diag.diagnosticStr,
        contentValue: tempPreview.diag.diagnosticList,
        contentJson: tempPreview.diag.diagnosticStrNoType,
        diseaseName: tempPreview.diag.diseaseName,
        type: 11,
      },
      {
        content: tempPreview.advice,
        contentValue: tempPreview.advice,
        operationName: tempPreview.operationName,
        contentJson: JSON.stringify(tempPreview.advice),
        type: 12,
      },
      {
          content: tempPreview.tcmDiag.diagnosticStr,
          contentValue: tempPreview.tcmDiag.diagnosticList,
          diseaseName: tempPreview.tcmDiag.diseaseName,
          contentJson: tempPreview.tcmDiag.diagnosticStrNoType,
          type: 13,
      },
    ];
    // let sex = formatFormParmas('patientSex', patInfoData) === '男' ? 1 : 0
    let params = {
        "age": formatFormParmas('patientAge', patInfoData),
        "cardNo": formatFormParmas('patientIdNo', patInfoData),
        "dataJson": JSON.stringify(Object.assign({}, jsonData)),
        "deptName": formatFormParmas('hospitalDeptName', patInfoData),
        "doctorName": formatFormParmas('doctorName', patInfoData),
        "inquiryCode": formatFormParmas('recordId', patInfoData), 
        // "inquiryDate": formatFormParmas('systemTime', patInfoData),   // 2020/9/14 编辑状态保存原有时间 _lcq
        "inquiryDate": inquiryDate,
        "modeName": modeName,
        "patName": formatFormParmas('patientName', patInfoData),
        "preview": JSON.stringify(preview),  // 左侧病历预览信息
        "sex": formatFormParmas('patientSex', patInfoData),
        "hospitalId":curHos.hosId
    }
    return new Promise((resolve,reject) =>{
      json('/demo/templateInfo/saveTemplateInfo', params).then(res => {
        let data = res.data;
        if (data.code == 0) {
          store.dispatch({ type: CLEARMEDICALNAME }); // 清除病历名称
          Notify.success('病历保存成功');
          resolve('ok')
        } else {
          reject(data.code);
          Notify.info(data.msg);
        }
        store.dispatch({ type: MODI_LOADING, flag: false });
      });
    }) 
   
}


// 保存病历信息
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 checkBody = baseList.checkBody.data;
    let vitalTags = [],unVitalTags=[];
    checkBody&&checkBody.map((it)=>{
        if(it.specFlag===4){
          vitalTags.push(it);
        }else{
          unVitalTags.push(it);
        }
    });

    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,
        "vitalSigns":JSON.stringify(vitalTags||[]),
        "physicalExcVs":JSON.stringify(unVitalTags||[]),
        "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": JSON.stringify(jsonStr.pacs),
            "contentValue":JSON.stringify(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.dateValue,
             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');
    delHistoryDataList()
    // store.dispatch(embedPush({
    //   action: "patientia",
    //   mode: 1
    // }))

};