package com.bzd.web.controller.gxhpz;

import com.bzd.common.annotation.Log;
import com.bzd.common.config.dao.PageData;
import com.bzd.common.core.controller.BaseController;
import com.bzd.common.core.domain.AjaxResult;
import com.bzd.common.core.page.TableDataInfo;
import com.bzd.common.enums.BusinessType;
import com.bzd.common.utils.DateUtils;
import com.bzd.common.utils.StringUtils;
import com.bzd.system.service.PharmaceuticalService;
import com.bzd.system.service.gxhpz.FollowPlanService;
import com.bzd.system.service.gxhpz.FollowTaskService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 随访任务任务控制层
 * creator wsp
 */
@Controller
@RequestMapping("/task/followTask")
public class FollowTaskController extends BaseController {
    private String prefix = "task";
    @Autowired
    private FollowTaskService followTaskService;

    @Autowired
    private FollowPlanService followPlanService;
    @Autowired
    private PharmaceuticalService pharmaceuticalService;

    // 随访任务
    private String prefix_followUp = "dtp/followUp";
    /**
     *
     * 任务查询
     */
    @RequiresPermissions("gxhpz:task:list")
    @PostMapping("/followTaskList")
    @ResponseBody
    public TableDataInfo TaskList() throws Exception {
        PageData pd = this.getPageData();
        startPage();
        //随访任务表单展示信息：只展示任务动作为表单任务的数据，不显示触达任务的数据
        pd.put("taskActionTaskType","表单任务");//任务动作(任务类型) 触达任务 表单任务
        List<PageData> pageData = followTaskService.findForList(pd);
        return  getDataTable(pageData);
    }
    /**
     *
     * 计划查询
     */
    @RequiresPermissions("gxhpz:task:list")
    @PostMapping("/followPlanList")
    @ResponseBody
    public TableDataInfo PlanList() throws Exception {
        PageData pd = this.getPageData();
        startPage();

        List<PageData> pageData = followPlanService.findForList(pd);
        return  getDataTable(pageData);
    }

    /**
     * 任务新增保存
     */
    @Log(title = "任务新增", businessType = BusinessType.INSERT)
    @PostMapping("/saveFollowTask")
    @ResponseBody
    public AjaxResult saveFollowTask() throws Exception {
        PageData pd = this.getPageData();
        int result = followTaskService.save(pd);
        if(result>0){
            return AjaxResult.success("成功");
        }else {
            return AjaxResult.error("失败");
        }

    }
    /**
     * 计划新增保存
     */
    @Log(title = "计划新增", businessType = BusinessType.INSERT)
    @PostMapping("/saveFollowPlan")
    @ResponseBody
    public AjaxResult saveFollowPlan() throws Exception {
        PageData pd = this.getPageData();
        int result = followPlanService.save(pd);
        if(result>0){
            return AjaxResult.success("成功");
        }else {
            return AjaxResult.error("失败");
        }

    }
    @Log(title = "任务删除", businessType = BusinessType.DELETE)
    @PostMapping("/removeTask")
    @ResponseBody
    public AjaxResult removeTask() throws Exception
    {
        PageData pd = new PageData();
        pd = this.getPageData();
       Object id = pd.get("ids");
       if(StringUtils.isNotNull(id)){
           String[] split = id.toString().split(",");
           List<String> ids = Arrays.asList(split);
           Integer integer = followTaskService.del(ids);
           return toAjax(integer);

       }
        return AjaxResult.success("请选择要删除的数据");
    }
    @Log(title = "计划删除", businessType = BusinessType.DELETE)
    @PostMapping("/removePlan")
    @ResponseBody
    public AjaxResult removePlan() throws Exception
    {
        PageData pd = new PageData();
        pd = this.getPageData();
        Object id = pd.get("ids");
        if(StringUtils.isNotNull(id)){
            String[] split = id.toString().split(",");
            List<String> ids = Arrays.asList(split);
            Integer integer = followPlanService.del(ids);
            return toAjax(integer);

        }
        return AjaxResult.success("请选择要删除的数据");
    }

    /**
     * 保存任务修改信息/保存随访表单信息/保存随访计划信息
     */
    @RequiresPermissions("gxhpz:task:edit")
    @Log(title = "任务管理", businessType = BusinessType.UPDATE)
    @PostMapping("/followTaskEdit")
    @ResponseBody
    public AjaxResult followTaskEdit() throws Exception
    {
        PageData pd = this.getPageData();
        String id = (String) pd.get("id");
        String patientId = (String)pd.get("patientId");
        String returnMethod = (String)pd.get("returnMethod");
        String iscoordinate = (String)pd.get("iscoordinate");
        String returnObject = (String)pd.get("returnObject");
        String medicationStatus = (String)pd.get("medicationStatus");//用药状态
        boolean newTask = false;
        if(StringUtils.isNotEmpty(returnMethod) && StringUtils.isNotEmpty(iscoordinate)
         && StringUtils.isNotEmpty(returnObject) && StringUtils.isNotEmpty(patientId) && StringUtils.isNotEmpty(id)){
            pd.put("taskStatus", "已完成");//任务状态：\r\n,0待执行，\r\n1已完成，\r\n2未完成，\r\n3已下发，\r\n4已取消
        }
        String next_follow_time = (String) pd.get("next_follow_time");
        if (StringUtils.isNotEmpty(next_follow_time)) {
            try {
                // 获取当前时间
                String currentTime = DateUtils.getTime(); // 假设返回格式为 "yyyy-MM-dd HH:mm:ss"
                // 解析日期字符串
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date nextFollowTimeDate = dateFormat.parse(next_follow_time);
                Date currentDateTime = dateFormat.parse(currentTime);
                // 比较两个日期
                if (nextFollowTimeDate.after(currentDateTime)) {
                    // 如果下次随访时间大于当前时间，则任务状态为“待执行”
                    pd.put("taskStatus", "待执行");
                    // 计算间隔天数
                    long diffInMillies = Math.abs(nextFollowTimeDate.getTime() - currentDateTime.getTime());
                    long intervalDays = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);

                    // 将间隔天数放入 pd 中
                    pd.put("interval_this_time", (int) intervalDays);

                    newTask=true;//=true符合条件 下次任务随访时间 意味着生成一个新的任务

                } else {
                    // 如果下次随访时间小于或等于当前时间，则任务状态为“已完成”
                    pd.put("taskStatus", "已完成");
                    pd.put("interval_this_time", 0); // 已完成的任务不需要显示间隔天数
                }
            } catch (ParseException e) {
                e.printStackTrace();
                // 处理日期解析异常
                pd.put("taskStatus", "解析错误");
                pd.put("interval_this_time", null);
            }
        }
//        else {
//            // 如果下次随访时间为空，则默认任务状态为“未完成”
//            pd.put("taskStatus", "未完成");
//            pd.put("interval_this_time", null);
//        }
        pd.put("storeId", getSysUser().getDeptId());//登记人
        pd.put("operator", getSysUser().getLoginName());//登记人
        pd.put("updatedAt", DateUtils.getTime());//更新时间
        pd.put("actualFollowUpTime", DateUtils.getTime());//实际随访时间
        pd.put("completionTime", DateUtils.getTime());//完成时间
        PageData pdTask=new PageData();
        if(StringUtils.isNotEmpty(id)){
            pdTask.put("id", id);
            PageData pageDataTask = followTaskService.selectOneById(pdTask);//根据任务id查询随访任务数据
            if(StringUtils.isNotNull(pageDataTask)){
                pd.put("useForm", pageDataTask.get("useForm"));
            }
        }

        Integer update = followTaskService.update(pd);
        if(StringUtils.isNotEmpty(medicationStatus)){
          String perpetual_stopdrug_cause = (String)  pd.get("perpetual_stopdrug_cause");//永久停药原因
            if(StringUtils.isNotEmpty(perpetual_stopdrug_cause)  && perpetual_stopdrug_cause.equals("离世")){
                //=离世时 关闭该患者所有计划任务
                String planId =(String) pd.get("bc_planId");
                pd.put("planId", planId);
                pd.put("storeId", getSysUser().getDeptId());
                Integer closeResult = followPlanService.closeAllPlan(pd);//关闭该患者所有计划任务
                System.out.println(pd+"<参数操作结果>"+closeResult);
            }
        }

        if(newTask){
            String planId =(String) pd.get("bc_planId");
            pd.put("planId", planId);
            //生成新任务 int FollowTask = dao.executeBatch("followTaskMapper.insertFollowTask", pdCPB);//预存数据任务
            int addResult = followTaskService.addNewFollowTask(pd);//生成下次随访任务
            System.out.println(pd+"生成新任务结果="+addResult);
        }
        if(update<=0){
            return error("保存失败");
        }
        return toAjax(update);
    }
    /**
     * 关闭计划原因页面
     * @return
     * @throws Exception
     */
    @RequiresPermissions("gxhpz:task:edit")
    @GetMapping("/closePlanPage/{id}")
    public String closePlanPage(@PathVariable("id") Long id, ModelMap mmap) throws Exception {
            return prefix_followUp + "/closePlanPage";
    }
    /**
     * 随访任务数据修改返回数据页面
     *
     * @return
     * @throws Exception
     */
    @RequiresPermissions("gxhpz:task:edit")
    @GetMapping("/FollowTaskEdit/{id}")
    public String FollowTaskEdit(@PathVariable("id") Long id, ModelMap mmap) throws Exception {
        PageData pd = this.getPageData();
        pd.put("id", id);
        PageData pd1 =new PageData();
        PageData pd2 =new PageData();
        PageData pd3=new PageData();
        PageData pd4=new PageData();
        PageData pd5=new PageData();
        PageData pd6=new PageData();
        PageData pdt1=new PageData();
        PageData pdt2=new PageData();
        PageData pageData = followTaskService.selectOneById(pd);//根据任务id查询随访任务数据
       String pagIndex="精简表单";//默认为精简表单
        if (StringUtils.isNotNull(pageData)) {
            String useForm= (String) pageData.get("useForm");
            if(StringUtils.isNotEmpty(useForm)){
                pagIndex=useForm;
            }
            pd2.put("patientId", pageData.get("patientId"));
            pd2.put("storeId", getSysUser().getDeptId());
            pd3.put("patientId", pageData.get("patientId"));//去查计划的条件 常规随访的
            pd3.put("mdmCode", pageData.get("mdmCode"));//去查计划的条件 常规随访的
            pd3.put("businessBelonging", "常规随访");//去查计划的条件 常规随访的

            pd4.put("patientId", pageData.get("patientId"));//去查计划的条件 脱落召回
            pd4.put("mdmCode", pageData.get("mdmCode"));//去查计划的条件 脱落召回
            pd4.put("businessBelonging", "脱落召回");//去查计划的条件 脱落召回

            pd5.put("id", pageData.get("patientId"));//去查购药记录的条件
            PageData Plan1 = followPlanService.selectPlanByCPB(pd3);//去查计划 常规随访的
            //pd1 = pharmaceuticalService.selectPatientById(pd2);//查询患者信息
            pd1 = pharmaceuticalService.selectFollowUpPerson(pd2);//查询跟进人数据信息
            if(StringUtils.isNotNull(Plan1)){

                pdt1.put("planId", Plan1.get("planId"));
                pageData.put("planId_cg", Plan1.get("planId"));
                pageData.put("mdmCode_cg", Plan1.get("mdmCode"));
                pageData.put("Plan1",Plan1);//常规随访的 类型的计划
                pageData.put("follow_up_person",Plan1.get("follow_up_person"));
                pageData.put("follow_up_person_id",Plan1.get("follow_up_person_id"));
                pageData.put("productName",Plan1.get("productName"));
                pageData.put("specification",Plan1.get("specification"));
                pageData.put("businessBelonging",Plan1.get("businessBelonging"));
                pageData.put("createdBy",Plan1.get("createdBy"));
                pageData.put("createdTime",  Plan1.get("createdTime1"));
                pageData.put("updatedBy",Plan1.get("updatedBy"));
                pageData.put("updatedTime",Plan1.get("updatedTime1"));
                // 获取原始的状态值并进行处理
                Integer status  = (Integer) Plan1.get("status");
                if (status != null) {
                    switch (status) {
                        case 0:
                            pageData.put("status","关闭");
                            break;
                        case 1:
                            pageData.put("status","进行中");
                            break;
                        case 2:
                            pageData.put("status","待开启");
                            break;
                        default:
                            pageData.put("status","待开启");
                            break;
                    }
                }
                List<PageData> listTask1= followTaskService.findForList(pdt1);//去查任务 常规随访
                if(listTask1.size()>0){
                    pageData.put("listTask1",listTask1);
                }
            }

            PageData Plan2 = followPlanService.selectPlanByCPB(pd4);//去查计划 脱落召回
            if(StringUtils.isNotNull(Plan2)){
               String planIdrw = (String) Plan2.get("planId");
               if(StringUtils.isNotEmpty(planIdrw)){
                   pdt2.put("planId", planIdrw);
                   List<PageData> listTask2= followTaskService.findForList(pdt2);//去查任务 脱落召回
                   if(listTask2.size()>0){
                       pageData.put("listTask2",listTask2);
                   }
               }
                pageData.put("planId_tl", Plan2.get("planId"));
                pageData.put("mdmCode_tl", Plan2.get("mdmCode"));
                pageData.put("follow_up_person2",Plan2.get("follow_up_person"));
                pageData.put("productName2",Plan2.get("productName"));
                pageData.put("specification2",Plan2.get("specification"));
                pageData.put("businessBelonging2",Plan2.get("businessBelonging"));
                pageData.put("createdBy2",Plan2.get("createdBy"));
                pageData.put("createdTime2",Plan2.get("createdTime1"));
                pageData.put("updatedBy2",Plan2.get("updatedBy"));
                pageData.put("updatedTime2",Plan2.get("updatedTime1"));
                pageData.put("Plan2",Plan2);//脱落召回 类型的计划
                //pd1.put("status2",Plan2.get("status"));
                // 获取原始的状态值并进行处理
                Integer status2  = (Integer) Plan2.get("status");
                if (status2 != null) {
                    switch (status2) {
                        case 0:
                            pageData.put("status2","关闭");
                            break;
                        case 1:
                            pageData.put("status2","进行中");
                            break;
                        case 2:
                            pageData.put("status2","待开启");
                            break;
                        default:
                            pageData.put("status2","待开启");
                            break;
                    }
                }

            }
            pd6.put("patientId", pageData.get("patientId"));
            pd6.put("storeId", getSysUser().getDeptId());
            List<PageData>  dValueList =pharmaceuticalService.getPatienDvalueList(pd6);//查询患者购药D值用药天数
            pageData.put("dValueList",dValueList);
            PageData  Degree =followPlanService.getPerfectionDegree(pd2);//查询档案完善度百分比
            List<PageData>  records =pharmaceuticalService.getDrugPurchaseList(pd5);//去查购药记录
            if(StringUtils.isNotNull(Degree)){
                pageData.put("filledFieldsCount",Degree.get("filledFieldsCount"));//字段完成数量
                // 获取原始的完成度百分比并四舍五入
                Object completenessObj = Degree.get("completenessPercentage");
                if (completenessObj instanceof BigDecimal) {
                    BigDecimal completenessPercentage = (BigDecimal) completenessObj;
                    // 使用 BigDecimal 的setScale 方法进行四舍五入
                    BigDecimal roundedPercentage = completenessPercentage.setScale(0, BigDecimal.ROUND_HALF_UP);
                    pageData.put("completenessPercentage", roundedPercentage.intValue()); // 将四舍五入后的值放入 pd1
                }
            }
           if(records.size()>0){
               pageData.put("recordsData",records);
           }
            //任务跟进人数据
            if(StringUtils.isNotNull(pd1)){
                pageData.put("followUpPersonName",pd1.get("followUpPersonName"));//随访跟进人姓名
                pageData.put("followUpPersonId",pd1.get("id"));//随访跟进id
            }

            //本次任务单个
            pageData.put("bc_id",pageData.get("id"));//本次任务id
            pageData.put("bc_planId",pageData.get("planId"));//本次任务的计划id
            pageData.put("bc_appointmentDate",pageData.get("appointmentDate1"));//预约日期
            pageData.put("bc_businessBelonging",pageData.get("businessBelonging"));//businessBelonging
            pageData.put("bc_taskName",pageData.get("taskName"));//任务名称
            pageData.put("bc_taskTheme",pageData.get("taskTheme"));//任务主题
            pageData.put("bc_productName",pageData.get("productName"));//商品名
            pageData.put("bc_taskFollower",pageData.get("taskFollower"));//任务跟进人
            pageData.put("timeFirstDiagnosis",pageData.get("timeFirstDiagnosis2"));//确诊后首次用药日期
            pageData.put("FirstDiagnosis",pageData.get("FirstDiagnosis"));//首次确诊时间
            pageData.put("bc_next_follow_time",pageData.get("next_follow_time2"));//下次随访时间
            pageData.put("bc_next_taskTheme",pageData.get("next_taskTheme"));//下次任务主题
            pageData.put("interval_this_time",pageData.get("interval_this_time"));//间隔时间

            pageData.put("bc_taskStatus",pageData.get("taskStatus"));//任务状态 0待执行，\r\n1已完成，\r\n2未完成，\r\n3已下发，\r\n4已取消
            mmap.putAll(pageData);
        }else{
            mmap.put("未查询到数据 id",id);
        }
        if(pagIndex.equals("全量表单")){
            return prefix_followUp + "/followUpEditAll";//全量表单
        }else {
            return prefix_followUp + "/followUpEdit";//followUpEdit 精简的表单
        }

    }

    /**
     * 保存计划修改信息
     */
    @RequiresPermissions("gxhpz:task:edit")
    @Log(title = "计划管理", businessType = BusinessType.UPDATE)
    @PostMapping("/followPlanEdit")
    @ResponseBody
    public AjaxResult followPlanEdit() throws Exception
    {
        PageData pd = this.getPageData();
        Integer update = followPlanService.update(pd);
        if(update<=0){
            return error("修改失败");
        }
        return toAjax(update);
    }



    /**
     * 关闭计划
     */
    @RequiresPermissions("gxhpz:task:edit")
    @Log(title = "关闭计划", businessType = BusinessType.UPDATE)
    @PostMapping("/closePlan")
    @ResponseBody
    public AjaxResult closePlan() throws Exception
    {
        PageData pd = this.getPageData();
        System.out.println("关闭计划"+pd);
        Integer update = followPlanService.closePlan(pd);
        if(update>0){
            return AjaxResult.success("关闭计划成功");
        }else{
            return AjaxResult.error("关闭计划失败");
        }
    }
    /**
     * 关闭任务
     */
    @RequiresPermissions("gxhpz:task:edit")
    @Log(title = "关闭任务", businessType = BusinessType.UPDATE)
    @PostMapping("/closeTask")
    @ResponseBody
    public AjaxResult closeTask() throws Exception
    {
        PageData pd = this.getPageData();
        Integer update = followTaskService.closeTask(pd);
        if(update>0){
            return AjaxResult.success("关闭任务成功");
        }else{
            return AjaxResult.error("关闭任务划失败");
        }

    }



}
