import axios from '@utils/ajax'
import {
  initItems,
  delItems,
  batchDelItems,
  changeTitle,
  keepPushData,
  changeVisible,
  getDptLis,
  initAdminItems,
  delItemsAdmin,
  batchDelItemsAdmin,
  changeTitleAdmin,
  floderListAdmin,
  folderModal,
  setSearchTemplateNorms,
} from '@store/actions/tabTemplate';
import {DIAG_SHOW} from "@store/types/print";
import Notify from '@commonComp/Notify';
import store from '@store';
import {
  getAllDataList,
  getAllDataStringList,
  pushAllDataList,
  getUrlArgObject,
  didPushParamChange
} from '@utils/tools';
import { billing, getMRAnalyse } from '@store/async-actions/pushMessage';


export const initItemList = (current,name,selectTemp) => {
  let admin = store.getState().homePage.admin;
  if(admin || selectTemp==2){
    return initAdminItemList(current,name,selectTemp)
  }else{
    return initCommonItemList(current,name,selectTemp)
  }
}

export const initCommonItemList = (current,name) => { //初始化数据
  let baseList = store.getState();
  let state = baseList.patInfo.message;
  // let searchVal = document.getElementById("searchTmp").value
  return (dispatch) => {
    axios.json('/templateInfo/getTemplateAlls', {
      "doctorId": state.doctorId,
      "hospitalDeptId": (name == '')?state.hospitalDeptId:null,
      "hospitalId": state.hospitalId,
      "hospitalCode": state.hospitalCode,
      "current": current,
      "sex":[1,2,3],
      "size": 9999,
      "name":name||''
    }).then((res) => {
      const data = res.data;
      if (data.code == 0) {
        // data.data.flg = flg||false  //获取下一页，暂时不用
        dispatch(initItems(data.data));
      } else {
        Notify.error(data.msg)
      }
    })
  }
};
export const initAdminItemList = (current,name,selectTemp) => { //初始化数据
  let baseList = store.getState();
  // let searchVal = document.getElementById("searchTmp").value
  let state = baseList.patInfo.message;
  return (dispatch) => {
    if(selectTemp == 2) {
      dispatch(findTemplateNorms(name))
    }else {
      dispatch(getFloderListAll())
    }
  }
};

export const saveTemplateDetail = (val,sex,spell) => { //保存为模板
  let baseList = store.getState();
  let jsonData = getAllDataList(baseList);
  let jsonStr = getAllDataStringList(baseList);
  const dConfig = baseList.typeConfig;
  const readMode = dConfig.readMode;          //回读模式
  let whichSign = readMode===-1||readMode===null?dConfig.mode:readMode;
  const docConfigs = dConfig.readConfig===-1||!dConfig.readConfig?dConfig.typeConfig:dConfig.readConfig;
  jsonData.docConfigs=docConfigs;     //保存当时的设置引用
  let state = baseList.patInfo.message;
  let preview = {
    "chief": jsonStr.chief,
    "present": jsonStr.present,
    "other": jsonStr.other,
    "vital": jsonStr.vital,
    "lis": jsonStr.lis,
    "pacs": jsonStr.pacs,
    "diag": jsonStr.diag,
    "advice": jsonStr.advice
  }
  function getdata(idx){
    let tmpObj = {
      "doctorId": state.doctorId,
      "hospitalDeptId": state.hospitalDeptId,
      "hospitalId": state.hospitalId,
      "dataJson": JSON.stringify(jsonData),
      "modeName": val,
      "modeType": whichSign,
      "preview": idx ? JSON.stringify(preview):preview,
      "sex":sex,
      "spell":spell
    }
    return tmpObj;
  }
  return (dispatch) => {
    axios.json('/templateInfo/saveTemplateInfo', getdata()).then((res) => {
      const data = res.data;
      if (data.code == 0) {
        Notify.success('模板保存成功');
        dispatch(initItemList(1,""));
        dispatch(keepPushData(getdata(1),'part'));
        dispatch({
          type: DIAG_SHOW,
          data:false
        });
      } else {
        if(data.msg == '该模板名存在'){         //存在不关闭弹窗
          dispatch({
            type: DIAG_SHOW,
            data:true
          });
        }else{
          dispatch({
            type: DIAG_SHOW,
            data:false
          });
        }
        Notify.error(data.msg);
      }
    })
  }
};
export const saveAdminTemplateDetail = (val,sex,id,fstName,folderId,folderName) => { //保存为模板
  let baseList = store.getState();
  let jsonData = getAllDataList(baseList);
  let jsonStr = getAllDataStringList(baseList);
  const dConfig = baseList.typeConfig;
  const readMode = dConfig.readMode;          //回读模式
  let whichSign = readMode===-1||readMode===null?dConfig.mode:readMode;
  const docConfigs = dConfig.readConfig===-1||!dConfig.readConfig?dConfig.typeConfig:dConfig.readConfig;
  jsonData.docConfigs=docConfigs;     //保存当时的设置引用
  let state = baseList.patInfo.message;
  let preview = {
    "chief": jsonStr.chief,
    "present": jsonStr.present,
    "other": jsonStr.other,
    "vital": jsonStr.vital,
    "lis": jsonStr.lis,
    "pacs": jsonStr.pacs,
    "diag": jsonStr.diag,
    "advice": jsonStr.advice,
  }
  function getdata(idx){
    let tmpObj = {
      "doctorId": state.doctorId,
      "hospitalDeptId": id,
      "hospitalId": state.hospitalId,
      "dataJson": JSON.stringify(jsonData),
      "modeName": val,
      "modeType": whichSign,
      "preview": idx ? JSON.stringify(preview):preview,
      "sex":sex,
      "modeSpell":fstName,
      "folderId": folderId,
    }
    return tmpObj;
  }
  return (dispatch) => {
    axios.json('/templateAdmin/saveTemplateNorms', getdata()).then((res) => {
      const data = res.data;
      if (data.code == 0) {
        Notify.success('模板保存成功');
        dispatch(initItemList(1,""));
        dispatch(keepPushData(getdata(1),'part'));
        dispatch({
          type: DIAG_SHOW,
          data:false
        });
      } else {
        if(data.msg == '该模板名存在'){         //存在不关闭弹窗
          dispatch({
            type: DIAG_SHOW,
            data:true
          });
        }else{
          dispatch({
            type: DIAG_SHOW,
            data:false
          });
        }
        Notify.error(data.msg);
      }
    })
  }
};

export const getFloderList = () => { //管理员文件夹列表获取
  let baseList = store.getState().patInfo.message;
  return (dispatch) => {
    axios.json('/templateFolderAdmin/list', {
      "doctorId": baseList.doctorId,
      "hospitalId": baseList.hospitalId,
    }).then((res) => {
      let data = res.data;
      if (data.code == 0) {
        dispatch(floderListAdmin(data.data))
      } else {
        Notify.error(data.msg);
      }
    })
  }
};
function getFloderLis(dispatch){
  let baseList = store.getState().patInfo.message;
  return (dispatch) => {
    axios.json('/templateFolderAdmin/list', {
      "doctorId": baseList.doctorId,
      "hospitalId": baseList.hospitalId,
    }).then((res) => {
      let data = res.data;
      if (data.code == 0) {
        dispatch(floderListAdmin(data.data))
      } else {
        Notify.error(data.msg);
      }
    })
  }
}
export const newFloder = (name,id,type) => { //新建管理员文件夹
  let baseList = store.getState().patInfo.message;
  return (dispatch) => {
    axios.json('/templateFolderAdmin/saveOrUpdate', {
      "doctorId": baseList.doctorId,
      "hospitalId": baseList.hospitalId,
      "id": id||'',
      "name": name,
      "templateType": 2  //模板类型（个人1，管理员2）
    }).then((res) => {
      let data = res.data;
      if (data.code == 0) {
        if(type=='modify') {
          Notify.success('修改成功');
        } else {
          Notify.success('新建成功');
        }
        dispatch(folderModal(false))
        dispatch(getFloderList())
        dispatch(getFloderListAll())
        dispatch(changeVisible(false))
      } else {
        Notify.error(data.msg);
      }
    })
  }
};
export const delFloder = (id) => { //文件夹删除
  let baseList = store.getState().patInfo.message;
  return (dispatch) => {
    axios.json('/templateFolderAdmin/delete', {
      "doctorId": baseList.doctorId,
      "hospitalId": baseList.hospitalId,
      "folderId": id,
    }).then((res) => {
      let data = res.data;
      if (data.code == 0) {
        Notify.success('文件夹删除成功');
        dispatch(getFloderListAll())
        // axios.json('/templateAdmin/getTemplateNorms').then((res) => {
        //   const data = res.data;
        //   if (data.code == 0) {
        //     // data.data.flg = flg||false  //获取下一页，暂时不用
        //     dispatch(initAdminItems(data.data));
        //   } else {
        //     Notify.error(data.msg)
        //   }
        // })
      } else {
        Notify.error(data.msg);
      }
    })
  }
};
export const orderFloder = (folderList) => { //文件夹排序
  let baseList = store.getState().patInfo.message;
  return (dispatch) => {
    axios.json('/templateFolderAdmin/sort', {templateFolderSortVOList:folderList}).then((res) => {
      let data = res.data;
      if (data.code == 0) {
        Notify.success('保存成功');
        dispatch(getFloderListAll())
      } else {
        Notify.error(data.msg);
      }
    })
  }
};
export const delItem = (id) => { //删除
  return (dispatch) => {
    axios.json('/templateInfo/cancelTemplateInfos', {
      ids: id
    }).then((res) => {
      let data = res.data;
      if (data.code == 0) {
        dispatch(delItems(id));
        Notify.success('模板删除成功');
      } else {
        Notify.error(data.msg);
      }
    })
  }
};
export const delItemAdmin = (id,folderId) => { //删除
  let baseList = store.getState().patInfo.message;
  return (dispatch) => {
    axios.json('/templateAdmin/cancelTemplateNorms', {
      "ids": id, 
      "doctorId": baseList.doctorId,
      "hospitalId": baseList.hospitalId,
    }).then((res) => {
      let data = res.data;
      if (data.code == 0) {
        // dispatch(delItemsAdmin(id,folderId));
        dispatch(initAdminItemList())
        Notify.success('模板删除成功');
      } else {
        Notify.error(data.msg);
      }
    })
  }
};
export const delBatchItem = (ids) => { //批量删除
  return (dispatch) => {
    axios.json('/templateInfo/cancelTemplateInfos', {
      ids: ids.join(",")
    }).then((res) => {
      let data = res.data;
      if (data.code == 0) {
        dispatch(batchDelItems(ids));
      } else {
        Notify.error(data.msg);
      }
    })
  }
};
export const delBatchItemAdmin = (ids) => { //批量删除
  let baseList = store.getState().patInfo.message;
  return (dispatch) => {
    axios.json('/templateAdmin/cancelTemplateNorms', {
      "ids": ids.join(","),
      "doctorId": baseList.doctorId,
      "hospitalId": baseList.hospitalId,
    }).then((res) => {
      let data = res.data;
      if (data.code == 0) {
        // dispatch(batchDelItemsAdmin(ids));
        dispatch(initAdminItemList())
      } else {
        Notify.error(data.msg);
      }
    })
  }
};

export const changeTitleAsyncAdmin = (obj) => { //改标题
  let baseList = store.getState();
  let whichSign = baseList.typeConfig.mode;
  let state = baseList.patInfo.message;
  return (dispatch) => {
    axios.json('/templateAdmin/updateTemplateNorms', {
      "doctorId": state.doctorId,
      "hospitalDeptId": obj.deptId,
      "hospitalId": state.hospitalId,
      "id": obj.id,
      "sex": obj.sex,
      "modeName": obj.title,
      "type": whichSign,
      "folderId": obj.folderId,
      "spell": obj.spell
    }).then((res) => {
      let data = res.data;
      if (data.code == 0) {
        dispatch(changeTitleAdmin(obj));
        Notify.success('标题修改成功');
        store.dispatch(changeVisible(false))
        dispatch(getFloderListAll())
      } else {
        // console.log(data)
        Notify.error(data.msg)
      }
    })
  }
};
export const changeTitleAsync = (obj) => { //改标题
  let baseList = store.getState();
  let whichSign = baseList.typeConfig.mode;
  let state = baseList.patInfo.message;
  return (dispatch) => {
    axios.json('/templateInfo/updateByIdUsNames', {
      "doctorId": state.doctorId,
      "hospitalDeptId": obj.deptId,
      "hospitalId": state.hospitalId,
      "id": obj.id,
      "modeName": obj.title,
      "type": whichSign,
      "spell": obj.spell
    }).then((res) => {
      let data = res.data;
      if (data.code == 0) {
        dispatch(changeTitle(obj));
        Notify.success('标题修改成功');
        store.dispatch(changeVisible(false))
        store.dispatch(initCommonItemList(1,""))
      } else {
        // console.log(data)
        Notify.error(data.msg)
      }
    })
  }
};

export const setPageView = (id) => { //获取模板结构化数据
  return (dispatch) => {
    axios.json('/templateInfo/getTemplateIdAlls', {
      id: id
    }).then((res) => {
      let data = res.data;
      if (data.code == 0) {
        //模板列表不筛选模式后，单个模式引用时看本身的模式
        pushAllDataList(data.data.type, 'push', data.data, 'template')//引用
        if(didPushParamChange()){     //诊断变化时会调推送，避免重复调
          dispatch(billing())
        }
        dispatch(getMRAnalyse())
      } else {
        Notify.error(data.msg);
      }
    })
  }
};
export const setPageViewAdmin = (id) => { //获取模板结构化数据
  return (dispatch) => {
    axios.json('/templateAdmin/getTemplateIdAlls', {
      id: id
    }).then((res) => {
      let data = res.data;
      if (data.code == 0) {
        //模板列表不筛选模式后，单个模式引用时看本身的模式
        pushAllDataList(data.data.type, 'push', data.data, 'template')//引用
        if(didPushParamChange()){     //诊断变化时会调推送，避免重复调
          dispatch(billing())
        }
      } else {
        Notify.error(data.msg);
      }
    })
  }
};

export const getDepartments = (value) => { //获取模板结构化数据
  return (dispatch) => {
    axios.json('/doctorInfo/getHospitalDeptInfoAll', {
      "deptInfoName": value,
      "hospitalCode": getUrlArgObject('hospitalId'),
      "thirdpartyName": ""
    }).then((res) => {
      let data = res.data;
      if (data.code == 0) {
        dispatch(getDptLis(data.data))
      } else {
        Notify.error(data.msg);
      }
    })
  }
};
export const findTemplateNorms = (name) => {//标准模板搜索
    return (dispatch) => {
      if(!name) {
        dispatch(setSearchTemplateNorms([]));
      } else {
        axios.json('/templateInfo/findTemplateNorms',{
          name,
          templateType: 2
        }).then((res) => {
          const data = res.data;
          if (data.code == 0) {
            dispatch(setSearchTemplateNorms(data.data));
          } else {
            Notify.error(data.msg)
          }
        })
      }
      
    }
  
}

export const getFloderListAll = () => {
    return (dispatch) => {
      axios.json('/templateAdmin/getTemplateNorms').then((res) => {
        const data = res.data;
        if (data.code == 0) {
          // data.data.flg = flg||false  //获取下一页，暂时不用
          dispatch(initAdminItems(data.data));
        } else {
          Notify.error(data.msg)
        }
      })
    }
}

export const addTemplateQuote = (templateId) => {
  let baseList = store.getState();
  let state = baseList.patInfo.message;
  return (dispatch) => {
    axios.json('/templateQuote/addTemplateQuote',{
        "doctorId": state.doctorId,
        "remark": "",
        "templateId": templateId
    }).then((res) => {
      const data = res.data;
      if (data.code == 0) {
        // data.data.flg = flg||false  //获取下一页，暂时不用
      } else {
        // Notify.error(data.msg)
      }
    })
  }
}