package com.bzd.system.service;

import com.bzd.common.config.dao.DaoBase;
import com.bzd.common.config.dao.DaoSupport;
import com.bzd.common.config.dao.PageData;
import com.bzd.common.utils.DateUtils;
import com.bzd.common.utils.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.bzd.common.utils.ShiroUtils.getSysUser;


/**
 * 药事服务管理 service
 */
@Service
public class PharmaceuticalService {

    @Autowired
    private DaoBase dao;

    @Resource(name = "daoSupport")
    private DaoSupport daoSupport;

//    public List<PageData> findArchivesList(PageData pd) throws Exception{//之前的档案查询所有患者
//        return (List<PageData>) daoSupport.findForList("PharmaceuticalServiceMapper.selectArchivesList", pd);
//    }

    public List<PageData> findArchivesList(PageData pd) throws Exception{

        return (List<PageData>) daoSupport.findForList("PharmaceuticalServiceMapper.selectArchivesListLinkDrugs", pd);
    }


    public List<PageData> getDrugPurchaseList(PageData pd) throws Exception{
        return (List<PageData>) daoSupport.findForList("PharmaceuticalServiceMapper.getDrugPurchaseList", pd);
    }

    public List<PageData> slectPatientByNameOrPhone(PageData pd) throws Exception{
       Object query= pd.get("query");
       if(StringUtil.isNotEmpty(query.toString())){
           return (List<PageData>) daoSupport.findForList("PharmaceuticalServiceMapper.slectPatientByNameOrPhone", pd);
       }else {
           List<PageData> list=new ArrayList();
           return list;
       }

    }
    public List<PageData> slectPatientByNameOrPhoneOrIdCard(PageData pd) throws Exception{
        return (List<PageData>) daoSupport.findForList("PharmaceuticalServiceMapper.slectPatientByNameOrPhoneOrIdCard", pd);

    }
    //先销售后登记 查询患者是否存在
    public PageData slectPatientByNameAndPhone(PageData pd) throws Exception{
        PageData pageData = (PageData) daoSupport.findForObject("PharmaceuticalServiceMapper.slectPatientByNameAndPhone", pd);
        return pageData;

    }
    public List<PageData> slectPatientById(PageData pd) throws Exception{
        return (List<PageData>) daoSupport.findForList("PharmaceuticalServiceMapper.slectPatientById", pd);

    }

    public List<PageData> findBasicInfomation(PageData pd) throws Exception{
        pd.put("archiveId", pd.get("id"));
        List<PageData> listBasicInfomation= (List<PageData>) daoSupport.findForList("PharmaceuticalServiceMapper.selectPatientBasicInfo", pd);
        return listBasicInfomation;

    }
    public Integer archivesRemove(PageData pd)throws Exception {
        return daoSupport.delete("PharmaceuticalServiceMapper.archivesRemove", pd);
    }

    @Transactional(rollbackFor = Exception.class)
    public Integer updateArchives(PageData pd)throws Exception {
        pd.put("archiveId", pd.get("id"));
        pd.put("createdBy", getSysUser().getLoginName());
        pd.put("createdAt", DateUtils.getTime());
        if(StringUtils.isNotNull(pd.get("realNameStatus"))){
            pd.remove("realNameStatus");
        }
        Object rowsRcordsObj = pd.get("rowsRcords");

        // 用药情况 直接删除后新增
        if(StringUtils.isNotNull(rowsRcordsObj)){
            try {
                daoSupport.update("PharmaceuticalServiceMapper.DeleteMedicationRecord", pd);
                // 将 JSON 字符串转换为 List<Map<String, Object>>
                ObjectMapper objectMapper = new ObjectMapper();
                List<Map<String, Object>> rowsList = objectMapper.readValue(rowsRcordsObj.toString(), List.class);
                // 遍历列表并调用插入数据接口
                for (Map<String, Object> Rcords : rowsList) {
                    pd.put("medicationDescription", Rcords.get("medicationDescription"));
                    pd.put("medicationType", Rcords.get("medicationType"));
                    daoSupport.update("PharmaceuticalServiceMapper.insertMedicationRecord", pd);
                    //daoSupport.update("PharmaceuticalServiceMapper.updateMedicationRecord", pd);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        pd.put("archiveCreator", getSysUser().getLoginName());//档案更新人
        pd.put("updateTime", DateUtils.getTime());//更新时间
        return daoSupport.update("PharmaceuticalServiceMapper.updateArchives", pd);
    }
    public Integer ShaoMaShangFan(PageData pd)throws Exception {
        //微信扫码绑定为会员 状态改为 上翻 flipStatus=1
        pd.put("flipStatus",1);
        pd.put("updateTime",DateUtils.getTime());
        pd.put("archiveCreator", getSysUser().getLoginName());
        return daoSupport.update("PharmaceuticalServiceMapper.ShaoMaShangFan", pd);
    }
    public Integer unbound(PageData pd)throws Exception {
        //解除绑定会员 状态改为 未上翻 flipStatus=2
        pd.put("flipStatus",2);
        pd.put("updateTime",DateUtils.getTime());
        pd.put("archiveCreator", getSysUser().getLoginName());
        return daoSupport.update("PharmaceuticalServiceMapper.unbound", pd);
    }

    public List<PageData> findrecordsByarchiveId(PageData pd) throws Exception{
        return (List<PageData>) daoSupport.findForList("PharmaceuticalServiceMapper.findrecordsByarchiveId", pd);

    }
    public List<PageData> findhistoryByarchiveId(PageData pd) throws Exception{
        return (List<PageData>) daoSupport.findForList("PharmaceuticalServiceMapper.findhistoryByarchiveId", pd);

    }
    public List<PageData> findcontactsByarchiveId(PageData pd) throws Exception{
        return (List<PageData>) daoSupport.findForList("PharmaceuticalServiceMapper.findcontactsByarchiveId", pd);

    }
    public List<PageData> findFollowUpList(PageData pd) throws Exception{
        return (List<PageData>) daoSupport.findForList("PharmaceuticalServiceMapper.selectFollowUpList", pd);

    }
    public Object findBasicInfoById(PageData pd) throws Exception{
        return  daoSupport.findForObject("PharmaceuticalServiceMapper.selectPatientBasicInfoById", pd);

    }
    public Integer followUpRemove(PageData pd)throws Exception {
        return daoSupport.delete("PharmaceuticalServiceMapper.followUpRemove", pd);
    }


    public Integer updateFollowUp(PageData pd)throws Exception {
        return daoSupport.update("PharmaceuticalServiceMapper.updateFollowUp", pd);
    }

    public List<PageData> findFollowUpAssignList(PageData pd) throws Exception{
        return (List<PageData>) daoSupport.findForList("PharmaceuticalServiceMapper.selectFollowUpAssignList", pd);

    }

    public Integer followUpAssignRemove(PageData pd)throws Exception {
        return daoSupport.delete("PharmaceuticalServiceMapper.followUpAssignRemove", pd);
    }


    public Integer updateFollowUpAssign(PageData pd)throws Exception {
        return daoSupport.update("PharmaceuticalServiceMapper.updateFollowUpAssign", pd);
    }

    public List<PageData> findPatientCounselingList(PageData pd) throws Exception{
        pd.put("storeId",getSysUser().getDeptId());
        return (List<PageData>) daoSupport.findForList("PharmaceuticalServiceMapper.selectConsultationAndDrug", pd);

    }
    public List<PageData> findPatientCounselingById(PageData pd) throws Exception{
        return (List<PageData>) daoSupport.findForList("PharmaceuticalServiceMapper.findPatientCounselingById", pd);

    }
    public List<PageData> getAllPatients(PageData pd) throws Exception{
        return (List<PageData>) daoSupport.findForList("PharmaceuticalServiceMapper.getAllPatients", pd);

    }

    public Integer insertPatientConsultation(PageData pd) throws Exception{
        Object patientIdObj = pd.get("patientId");
        Object KnowledgeLinksValue = pd.get("KnowledgeLinksValue");
        if (StringUtils.isNotNull(KnowledgeLinksValue)) {
            pd.put("KnowledgeLink", KnowledgeLinksValue);
        }

        if (StringUtils.isNotNull(patientIdObj)) {
            List<PageData> patientList = (List<PageData>) daoSupport.findForList("PharmaceuticalServiceMapper.selectPatientById", pd);
            if (patientList != null && !patientList.isEmpty()) {
                PageData patientData = patientList.get(0);
                pd.put("gender", patientData.get("gender"));
                pd.put("age", patientData.get("age"));
                pd.put("patientName", patientData.get("name"));
                pd.put("patientPhone", patientData.get("phoneNumber"));
                pd.put("disease", patientData.get("diseaseType"));
            }
        }
        pd.put("storeId", getSysUser().getDeptId());
        pd.put("storeName", getSysUser().getDept().getDeptName());
        return daoSupport.update("PharmaceuticalServiceMapper.insertPatientConsultation", pd);

    }

    public Integer patientCounselingRemove(PageData pd)throws Exception {
        return daoSupport.delete("PharmaceuticalServiceMapper.patientCounselingRemove", pd);
    }


    public Integer updatePatientCounseling(PageData pd)throws Exception {
        Object KnowledgeLinksValue = pd.get("KnowledgeLinksValue");
        if (StringUtils.isNotNull(KnowledgeLinksValue)) {
            pd.put("KnowledgeLink", KnowledgeLinksValue);
        }
        pd.put("updateDate", DateUtils.getTime());
        pd.put("regenerator", getSysUser().getLoginName());
        return daoSupport.update("PharmaceuticalServiceMapper.updatePatientCounseling", pd);
    }

    public List<PageData> findFollowUpEvaluationList(PageData pd) throws Exception{
        return (List<PageData>) daoSupport.findForList("PharmaceuticalServiceMapper.selectFindFollowUpEvaluationList", pd);

    }

    public Integer followUpEvaluationRemove(PageData pd)throws Exception {
        return daoSupport.delete("PharmaceuticalServiceMapper.findFollowUpEvaluationRemove", pd);
    }


    @Transactional(rollbackFor = Exception.class)
    public Integer updateFollowUpEvaluation(PageData pd)throws Exception {
        return daoSupport.update("PharmaceuticalServiceMapper.updateFindFollowUpEvaluation", pd);
    }

    public boolean checkPatientIsExist(PageData pd) throws Exception{
        List<PageData> pdlist = (List<PageData>) daoSupport.findForList("PharmaceuticalServiceMapper.checkPatientIsExist", pd);
        if(pdlist.size()>0){
            return true;
        }else{
            return false;
        }
    }
    public Object selectPatientById(PageData pd) throws Exception{
        Object PageData =daoSupport.findForList("PharmaceuticalServiceMapper.selectPatientById", pd);
        return PageData;

    }

    /**
     * 新建患者档案
     */
    public Integer addArchives(PageData pd)throws Exception {
        Object storeName = pd.get("storeName");
        if (StringUtils.isNull(storeName)) {
            pd.put("storeName", getSysUser().getDept().getDeptName());
        }
        String name = (String) pd.get("name");
        String smName = (String) pd.get("smName");
        if (StringUtils.isNotEmpty(smName)) {
            if(name.equals(smName)){
                pd.put("realNameStatus", 1);
            }else{
                pd.put("realNameStatus", 0);
            }
        }else{
            pd.put("realNameStatus", 2);
        }
        pd.put("storeId", getSysUser().getDeptId());//这里系统先自动获取系统所登录的门店
        pd.put("creator", getSysUser().getLoginName());//创建人
        pd.put("createTime", DateUtils.getTime());//创建时间
        pd.put("archiveCreator", getSysUser().getLoginName());//档案创建人
        pd.put("archiveCompleteStatus", 0);//档案是否完善 1已完善 0未完善

        return daoSupport.update("PharmaceuticalServiceMapper.insertArchiveRecord", pd);
    }

    /**
     * 新建患者档案
     */
    public PageData addArchivesCallback(PageData pd)throws Exception {
        Object storeName = pd.get("storeName");
        if (StringUtils.isNull(storeName)) {
            pd.put("storeName", getSysUser().getDept().getDeptName());
        }
        String name = (String) pd.get("name");
        String smName = (String) pd.get("smName");
        if (StringUtils.isNotEmpty(smName)) {
            if(name.equals(smName)){
                pd.put("realNameStatus", 1);
            }else{
                pd.put("realNameStatus", 0);
            }
        }else{
            pd.put("realNameStatus", 2);
        }
        pd.put("storeId", getSysUser().getDeptId());//这里系统先自动获取系统所登录的门店
        pd.put("creator", getSysUser().getLoginName());//创建人
        pd.put("createTime", DateUtils.getTime());//创建时间
        pd.put("archiveCreator", getSysUser().getLoginName());//档案创建人
        pd.put("archiveCompleteStatus", 0);//档案是否完善 1已完善 0未完善
      int result =  daoSupport.update("PharmaceuticalServiceMapper.insertArchiveRecord", pd);

      if(result>0){
          PageData pageData = (PageData) daoSupport.findForObject("PharmaceuticalServiceMapper.slectPatientByNameAndPhone", pd);
          if(StringUtils.isNotNull(pageData)){
              PageData pd1=new PageData();
              pd1.put("patientName",pd.get("name"));
              pd1.put("patientPhone",pd.get("phoneNumber"));
              pd1.put("age",pd.get("age"));
              pd1.put("gender",pd.get("gender"));
              PageData pageData1 = (PageData) daoSupport.findForObject("DTPCFDJMapper.selectCFOneByNameAndPhone", pd1);
              if(StringUtils.isNotNull(pageData1)){
                  pd1.put("id",pageData1.get("id"));
                  int result2 =  daoSupport.update("DTPCFDJMapper.updateXSCFHZXXById", pd1);
                  System.err.println("result2:修改销售处方的患者结果:"+result2);
              }
              pageData.put("result","200");
              pageData.put("msg","新建成功");
              return pageData;
          }
      }else{
          pd.put("result","301");
          pd.put("msg","新建失败");
          return pd;
      }
        pd.put("result","301");
        pd.put("msg","新建失败");
        return pd;
    }
}
