package com.bzd.system.service.gxhpz;

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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

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

@Service
public class FollowPlanService {
    @Autowired
    private DaoBase dao;
    @Resource(name = "daoSupport")
    private DaoSupport daoSupport;

    /**
     * 查询列表 
     * @param pd
     * @return 
     * @throws Exception
     */
    public List<PageData> findForList(final PageData pd) throws Exception {
        return (List<PageData>) daoSupport.findForList("followPlanMapper.selectFollowPlans", pd);
    }
    /**
     * 根据药品编码和患者id,业务归属 查询计划 只能出现一条数据
     * @param pd
     * @return
     * @throws Exception
     */
    public PageData selectPlanByCPB(final PageData pd) throws Exception {
        PageData pdo= (PageData) daoSupport.findForObject("followPlanMapper.selectPlanByCPB", pd);
        return pdo;
    }
    /**
     * 查询单个
     * @param pd
     * @return
     * @throws Exception
     */
    public Object selectOneById(final PageData pd) throws Exception {
        return daoSupport.findForObject("followPlanMapper.selectOneById", pd);
    }

    /**
     * 添加
     * @param pd
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public int save(final PageData pd) throws Exception {
      return  daoSupport.save("followPlanMapper.insertFollowPlan", pd);

    }

    /**
     *
     * @param ids
     * @return
     * @throws Exception
     */
    public Integer del(List<String> ids) throws Exception {
        return daoSupport.delete("followPlanMapper.deleteFollowPlansByIds", ids);
    }

    /**
     * 修改配置
     * @param pd
     * @return
     * @throws Exception
     */
    public Integer update(PageData pd) throws Exception {
        return daoSupport.update("followPlanMapper.updateFollowPlan", pd);
    }


    /**
     * 统计患者档案完善度
     * filledFieldsCount 字段完成数量 completenessPercentage完成百分比 id 患者id name 患者姓名
     * @param pd
     * @return
     * @throws Exception
     */
    public PageData getPerfectionDegree(PageData pd) throws Exception {
        PageData pjd= (PageData) daoSupport.findForObject("PharmaceuticalServiceMapper.statisticsPerfectionDegree", pd);
        return pjd;
    }

    /**
     * 关闭计划
     * @param pd
     * @return
     * @throws Exception
     */
    public Integer closePlan(PageData pd) throws Exception {
        pd.put("status", 0);
        pd.put("taskStatus", "已取消");
        pd.put("updatedAt", DateUtils.getTime());
        pd.put("updatedTime", DateUtils.getTime());
        pd.put("updatedBy", getSysUser().getLoginName());
        pd.put("closePlanTime", DateUtils.getTime());
        pd.put("storeId", getSysUser().getDeptId());
        pd.put("operator", getSysUser().getLoginName());
        pd.put("createdAt", DateUtils.getTime());


        //关闭原因: 1 计划错误 2 用药状态调整 3 随访不配合 4 电话号码错  5 误患者换药 6 其他
        //用药状态调整为: 1永久停药 2无需购药永久领取援助用药 3回到地级市医院购药
        //随访不配合原因: 1患者周期观念不强 2因不良反应患者自主决定延迟用药 3因经济原因患者延迟用药
        //关闭范围: 1仅关闭当前计划 2关闭当前药品的全部计划 3关闭患者当前的全部计划
        //永久停药类型: 1离世 2已结束该药治疗疗程 3疾病康复好转 4经济原因无购买可能 5不良反应严重 6疾病进展（耐药、效果不明显）更换治疗用药
        //是否禁用此品的计划: 1是 2否 (选择是，购买相同D值品不会自动触发新计划)
        //关闭类型: 1全部类型 2指定类型
        //指定类型: 1常规随访 2脱落召回
        String reason = pd.getString("reason");
        String drugsStatus = pd.getString("drugsStatus");
        String closeType = pd.getString("closeType");
        String drugsStop = pd.getString("drugsStop");
        String specifiedType = pd.getString("specifiedType");

        // 根据条件判断执行关闭逻辑
        if ("计划错误".equals(reason) || "电话号码错".equals(reason) || "误患者换药".equals(reason) || "其他".equals(reason)) {
          int closeCurrentPlan =  closeCurrentPlan(pd);
          if(closeCurrentPlan>0){
              int closeReason = daoSupport.update("closePlanReasonMapper.insertCloseplanReason", pd);
              System.out.println("添加原因：" + closeReason);
          }
            return closeCurrentPlan;
        } else if ("全部类型".equals(closeType)) {
            int closePatientCurrentPlan =  closePatientCurrentPlan(pd);
            if(closePatientCurrentPlan>0){
                int closeReason = daoSupport.update("closePlanReasonMapper.insertCloseplanReason", pd);
                System.out.println("添加原因：" + closeReason);
            }
            return closePatientCurrentPlan;
        } else if ("指定类型".equals(closeType)) {
            // 处理指定类型，拆分为列表后调用
            String[] types = specifiedType.split(",");
            for (String type : types) {
                pd.put("specifiedType", type.trim());
                pd.put("businessBelonging", type.trim());
                int closeByTypePlan =  closeByTypePlan(pd);
                if(closeByTypePlan>0){
                    int closeReason = daoSupport.update("closePlanReasonMapper.insertCloseplanReason", pd);
                    System.out.println("添加原因：" + closeReason);
                }
            }
        } else if ("永久停药".equals(drugsStatus)) { // 永久停药
            int closeCurrentDrugsPlan =  closeCurrentDrugsPlan(pd);
            if(closeCurrentDrugsPlan>0){
                int closeReason = daoSupport.update("closePlanReasonMapper.insertCloseplanReason", pd);
                System.out.println("添加原因：" + closeReason);
            }
            return closeCurrentDrugsPlan;
        } else if ("无需购药永久领取援助用药".equals(drugsStatus)) { // 无需购药
            int closeCurrentPlan =  closeCurrentPlan(pd);
            if(closeCurrentPlan>0){
                int closeReason = daoSupport.update("closePlanReasonMapper.insertCloseplanReason", pd);
                System.out.println("添加原因：" + closeReason);
            }
            return closeCurrentPlan;
        } else if ("离世".equals(drugsStop)) { // 离世
            int closePatientCurrentPlan =  closePatientCurrentPlan(pd);
            if(closePatientCurrentPlan>0){
                int closeReason = daoSupport.update("closePlanReasonMapper.insertCloseplanReason", pd);
                System.out.println("添加原因：" + closeReason);
            }
            return closePatientCurrentPlan;
        } else {
            int closeCurrentPlan =  closeCurrentPlan(pd);
            if(closeCurrentPlan>0){
                int closeReason = daoSupport.update("closePlanReasonMapper.insertCloseplanReason", pd);
                System.out.println("添加原因：" + closeReason);
            }
            return closeCurrentPlan;
        }
        return null;
    }

    // 示例关闭方法（需根据实际Mapper实现）
    private Integer closeCurrentPlan(PageData pd) throws Exception {
        // 更新计划、任务和定时任务状态
        int plan = daoSupport.update("followPlanMapper.closeFollowPlan", pd);
        int task = daoSupport.update("followTaskMapper.stopFollowTask", pd);
        PageData pdJob = new PageData();
        pdJob.put("planId", pd.get("planId"));
        pdJob.put("status", 1);
        pdJob.put("updateBy", getSysUser().getLoginName());
        pdJob.put("remark", "按指定类型关闭计划");
        int job = daoSupport.update("followTaskMapper.updateJobByPlanId", pdJob);
        return job;
    }

    private Integer closePatientCurrentPlan(PageData pd) throws Exception {
        daoSupport.update("followTaskMapper.closePatientCurrentTask", pd);
        daoSupport.update("followTaskMapper.closePatientCurrentPLan", pd);
       return daoSupport.update("followTaskMapper.updateJobByPatientId", pd);
    }

    private Integer closeCurrentDrugsPlan(PageData pd) throws Exception {
        int b =  daoSupport.update("followTaskMapper.closeTaskCurrentDrugsPlan", pd);
        int a =  daoSupport.update("followTaskMapper.closePLanCurrentDrugsPlan", pd);
        List<PageData> pdList= (List<PageData>) daoSupport.findForList("followTaskMapper.getPlanByMdmCode", pd);
        for(PageData list: pdList){
            PageData pdJob = new PageData();
            pdJob.put("planId", list.get("planId"));
            pdJob.put("status", 1);
            pdJob.put("updateBy", getSysUser().getLoginName());
            pdJob.put("remark", "计划关闭更据药品查询到的");
            daoSupport.update("followTaskMapper.updateJobByPlanId", pdJob);
        }
        return a;
    }

    private Integer closeByTypePlan(PageData pd) throws Exception {

        List<PageData> TaskList= (List<PageData>)  daoSupport.findForList("followTaskMapper.getTaskByPlanId", pd);
        for(PageData list: TaskList){
            PageData pdJob = new PageData();
            pd.put("taskStatus", "已取消");
            pdJob.put("updatedAt", DateUtils.getTime());
            pdJob.put("updatedTime", DateUtils.getTime());
            pdJob.put("storeId", getSysUser().getDeptId());
            pdJob.put("operator", getSysUser().getLoginName());
            pdJob.put("createdAt", DateUtils.getTime());
            pdJob.put("planId", list.get("planId"));
            pdJob.put("taskId", list.get("taskId"));
            pdJob.put("status", 1);
            pdJob.put("updateBy", getSysUser().getLoginName());
            pdJob.put("remark", "计划关闭更据根据类型关闭");
            daoSupport.update("followTaskMapper.updateJobByTaskId", pdJob);
            daoSupport.update("followTaskMapper.closeTaskByTaskId", pdJob);

        }
        int a=  daoSupport.update("followTaskMapper.closeByPlanTypePlan", pd);
        return a;
    }

    /**
     * 关闭该患者的所有计划
     * @param pd
     * @return
     * @throws Exception
     */
    public Integer closeAllPlan(PageData pd) throws Exception {
        pd.put("status", 0);
        pd.put("storeId", getSysUser().getDeptId());
        pd.put("taskStatus", "已取消");//0待执行，\r\n1已完成，\r\n2未完成，\r\n3已下发，\r\n4已取消
        pd.put("updatedAt", DateUtils.getTime());//'更新时间'
        pd.put("operator", getSysUser().getLoginName());//'操作人'
        pd.put("updatedTime", DateUtils.getTime());//'更新时间'
        pd.put("updatedBy", getSysUser().getLoginName());//更新人
        int plan = daoSupport.update("followTaskMapper.closeFollowPlanByPatientId", pd);
        //pd.put("id", pd.get("taskId"));//设置真确的任务计划id
        int task = daoSupport.update("followTaskMapper.stopFollowTaskByPatientId", pd);
        PageData pd1 = new PageData();
        pd1.put("patientId", pd.get("patientId"));
        pd1.put("storeId", getSysUser().getDeptId());
        pd1.put("status", 1);//暂停任务
        pd1.put("updateBy", getSysUser().getLoginName());
        pd1.put("remark", "所有该患者的计划关闭");
        //更改job表状态
        int job = daoSupport.update("followTaskMapper.updateJobByPatientId", pd1);
        if (task > 0 && plan > 0 || job > 0) {
            return 1;
        } else {
            return -1;
        }
    }


}
