package com.bzd.system.service.dtp;

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.bzd.common.utils.uuid.IdUtils;
import com.bzd.common.utils.uuid.SnowflakeIdGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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


/**
*
* 随访SOP表 service
* @author wsp
* @since 2024-10-15
*/

@Service
public class SDtpYypzFollowUpSopService {

    @Autowired
    private DaoBase dao;

    @Resource(name = "daoSupport")
    private DaoSupport daoSupport;
    @Transactional(rollbackFor = Exception.class)
    public Integer addSDtpYypzFollowUpSop(PageData pd) throws Exception {
        //Long templateId = SnowflakeIdGenerator.newId();弃用
        Integer templateId = IdUtils.get7randomNumber();//生成7位随机数
        Object nodesDataList = pd.get("nodesData");
        List<PageData> nodeList = new ArrayList<>();
        List<PageData> addList = new ArrayList<>();
        Object drugList = pd.get("applicableDrug");//获取药品信息列表

        if (StringUtils.isNotNull(drugList)) {
            try {
                // 将 JSON 字符串转换为 List<Map<String, Object>>
                ObjectMapper objectMapper = new ObjectMapper();
                List<Map<String, Object>> rowsdrugList = objectMapper.readValue(drugList.toString(), List.class);
                // 遍历列表并调用插入数据接口
                if (rowsdrugList.size() > 0) {
                    for (Map<String, Object> lxr : rowsdrugList) {
                        PageData pageData = new PageData();
                        pageData.put("storeId", getSysUser().getDeptId());
                        pageData.put("createTime", DateUtils.getTime());
                        pageData.put("productName", lxr.get("productName"));
                        pageData.put("productCode", lxr.get("productCode"));
                        pageData.put("specification", lxr.get("specification"));
                        pageData.put("templateId", templateId);
                        pageData.put("templateName", pd.get("templateName"));
                        addList.add(pageData);
                    }
                    final HashMap<String, Object> addMap = new HashMap<String, Object>();
                    addMap.put("dataList", addList);
                    int resultDrug= dao.executeBatch("SDtpYypzFollowUpSopMapper.batchAddTemplateDrugDynamic", addMap);
                    if (resultDrug <= 0) {
                        throw new RuntimeException("药品信息插入失败");
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
       if (StringUtils.isNotNull(nodesDataList)) {
        try {
            // 将 JSON 字符串转换为 List<Map<String, Object>>
            ObjectMapper objectMapper = new ObjectMapper();
            List<Map<String, Object>> nodesList = objectMapper.readValue(nodesDataList.toString(), List.class);
            // 遍历列表并调用插入数据接口
            if (nodesList.size() > 0) {
                for (int i = 0; i < nodesList.size(); i++) {
                    Map<String, Object> lxr = nodesList.get(i);
                    PageData pageData = new PageData();

                // 自动生成节点名称和编码
                String nodeName = "节点" + (i + 1); // 节点名称从节点1开始
                String nodeCode = String.valueOf(i + 1); // 编码从1开始
                    pageData.put("creator", getSysUser().getLoginName());
                    pageData.put("createTime", DateUtils.getTime());
                    pageData.put("templateId", templateId);
                    pageData.put("nodeName", nodeName);
                    pageData.put("nodeCode", nodeCode);
                    pageData.put("activateStructures", lxr.get("activateStructures"));
                    pageData.put("activateWhichDay", lxr.get("activateWhichDay"));
                    pageData.put("activateNodeRule", lxr.get("activateNodeRule"));
                    pageData.put("createTaskStructures", lxr.get("createTaskStructures"));
                    pageData.put("createTaskWhen", lxr.get("createTaskWhen"));
                    pageData.put("createTaskEvery", lxr.get("createTaskEvery"));
                    pageData.put("createTaskDi", lxr.get("createTaskDi"));
                    pageData.put("createTaskTriggerValue", lxr.get("createTaskTriggerValue"));
                    pageData.put("createTaskExecutionTimes", lxr.get("createTaskExecutionTimes"));
                    pageData.put("taskActionMode", lxr.get("taskActionMode"));
                    pageData.put("taskActionTaskType", lxr.get("taskActionTaskType"));
                    pageData.put("taskActionRole", lxr.get("taskActionRole"));
                    pageData.put("generationDaysAfter", lxr.get("generationDaysAfter"));
                    pageData.put("generationHMS", lxr.get("generationHMS"));
                    pageData.put("followUpSubject", lxr.get("followUpSubject"));
                    pageData.put("taskValidity", lxr.get("taskValidity"));
                    pageData.put("taskMaterial", lxr.get("taskMaterial"));
                    pageData.put("deliveryChannel", lxr.get("deliveryChannel"));
                    pageData.put("smsId",lxr.get("smsId"));
                    pageData.put("useForm",lxr.get("useForm"));
                    pageData.put("status",0);//状态: 0已创建 1启用，2禁用 默认为已创建0
                    // 处理 过滤条件 filtersData
                    @SuppressWarnings("unchecked")
                    List<Map<String, Object>> filtersData = (List<Map<String, Object>>) lxr.get("filtersData");
                    if (filtersData != null && !filtersData.isEmpty()) {
                        String filtersDataJson = objectMapper.writeValueAsString(filtersData);
                        pageData.put("filterCondition", filtersDataJson);
                    }
                    System.out.println("pageData:"+pageData);
                    int node1= dao.executeBatch("SDtpYypzFollowUpSopMapper.insertNodeConfig", pageData);
                    nodeList.add(pageData);
                    if (node1 <= 0) {
                        throw new RuntimeException("节点配置插入失败");
                    }
                }
        //                final HashMap<String, Object> addMap = new HashMap<String, Object>();
        //                addMap.put("dataList", nodeList);
                          //批量插入暂时不用
        //                int node= dao.executeBatch("SDtpYypzFollowUpSopMapper.batchAddNodeConfig", addMap);
        //                if (node <= 0) {
        //                    throw new RuntimeException("节点配置插入失败");
        //                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
        System.out.println("getSysUser().getDeptId():"+getSysUser().getDeptId());
        pd.put("createdTime", DateUtils.getTime());//创建时间
        pd.put("createdBy", getSysUser().getLoginName());//'创建人
        pd.put("storeId",getSysUser().getDeptId().toString());//门店id
        pd.put("storeName",getSysUser().getDept().getDeptName());//门店名称
        pd.put("status",0);//状态: 0已创建 1启用，2禁用 默认为已创建0
        pd.put("templateId", templateId);
        int result =  daoSupport.update("SDtpYypzFollowUpSopMapper.addSDtpYypzFollowUpSop", pd);
        if (result <= 0) {
            throw new RuntimeException("主记录插入失败");
        }
        return result;
    }

    public List<PageData> findSDtpYypzFollowUpSopList(PageData pd) throws Exception{
        return (List<PageData>) daoSupport.findForList("SDtpYypzFollowUpSopMapper.selectSDtpYypzFollowUpSopList", pd);
    }
    public List<PageData> selectDrugsByTemplateId(PageData pd) throws Exception{
        return (List<PageData>) daoSupport.findForList("SDtpYypzFollowUpSopMapper.selectDrugsByTemplateId", pd);
    }
    public List<PageData> selectNodeConfigByTemplateId(PageData pd) throws Exception{
        List<PageData> nodeList= (List<PageData>) daoSupport.findForList("SDtpYypzFollowUpSopMapper.selectNodeConfigByTemplateId", pd);
        // 遍历 nodeList 并处理每个节点的 filterCondition 字段
                for (PageData node : nodeList) {
                Object filterConditionBlob = node.get("filterCondition");
                if (filterConditionBlob instanceof Blob) {
                    try {
                        Blob blob = (Blob) filterConditionBlob;
                        String jsonString = IOUtils.toString(blob.getBinaryStream(), StandardCharsets.UTF_8);
                        // 将 JSON 字符串解析为 Map 或其他合适的对象类型
                        // 将解析后的对象设置回 PageData
                        node.put("filterCondition", jsonString);
                    } catch (IOException | SQLException e) {
                        // 处理异常
                        System.out.println("处理 filterCondition BLOB 数据失败: "+ e);
                        node.put("filterCondition", null); // 或者设置默认值
                    }
                }

             }
          return nodeList;
    }
    public PageData selectTemplateById(PageData pd) throws Exception{
        PageData pdObj= (PageData) daoSupport.findForObject("SDtpYypzFollowUpSopMapper.selectTemplateById", pd);
        return pdObj ;
    }

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

    public Integer updateSDtpYypzFollowUpSop(PageData pd)throws Exception {
        PageData pda =new PageData();
        Integer statusFla=null;
        String switchFlag = (String) pd.get("switchFlag");
        if(StringUtils.isNotEmpty(switchFlag)){
            if(switchFlag.equals("已创建")){
                statusFla=0;
            }
            if(switchFlag.equals("启用中")){
                statusFla=1;
            }
            if(switchFlag.equals("禁用中")){
                statusFla=2;
            }
        }
        Object nodesDataList = pd.get("nodesData");
        String templateId = (String) pd.get("templateId");
        if (StringUtils.isNotNull(templateId)) {
            pda.put("templateId", templateId);
        }else {
            throw new RuntimeException("模板ID不能为空");
        }
        List<PageData> nodeList = new ArrayList<>();
        List<PageData> addList = new ArrayList<>();
        Object drugList = pd.get("applicableDrug");//获取药品信息列表
        try {
            //更新药品信息
        if (StringUtils.isNotNull(drugList)) {
            List<PageData> ylist= (List<PageData>) daoSupport.findForList("SDtpYypzFollowUpSopMapper.selectDrugsByTemplateId", pda);
            if (ylist.size() > 0) {
                int a=  daoSupport.update("SDtpYypzFollowUpSopMapper.deleteTemplateDrugByTemplateId", pda);
                if (a <= 0) {
                    throw new RuntimeException("药品更新删除失败");
                }
             }
                // 将 JSON 字符串转换为 List<Map<String, Object>>
                ObjectMapper objectMapper = new ObjectMapper();
                List<Map<String, Object>> rowsdrugList = objectMapper.readValue(drugList.toString(), List.class);
                // 遍历列表并调用插入数据接口
                if (rowsdrugList.size() > 0) {
                    for (Map<String, Object> lxr : rowsdrugList) {
                        PageData pageData = new PageData();
                        pageData.put("storeId", getSysUser().getDeptId());
                        pageData.put("createTime", DateUtils.getTime());
                        pageData.put("productName", lxr.get("productName"));
                        pageData.put("productCode", lxr.get("productCode"));
                        pageData.put("specification", lxr.get("specification"));
                        pageData.put("templateId", templateId);
                        pageData.put("templateName", pd.get("templateName"));
                        addList.add(pageData);
                    }
                    final HashMap<String, Object> addMap = new HashMap<String, Object>();
                    addMap.put("dataList", addList);
                    int resultDrug= dao.executeBatch("SDtpYypzFollowUpSopMapper.batchAddTemplateDrugDynamic", addMap);
                    if (resultDrug <= 0) {
                        throw new RuntimeException("药品信息插入失败");
                    }
                }

        }
            //修改节点信息
        if (StringUtils.isNotNull(nodesDataList)) {
                List<PageData> ylist= (List<PageData>) daoSupport.findForList("SDtpYypzFollowUpSopMapper.selectNodeConfigByTemplateId", pda);
                if (ylist.size() > 0) {
                    int b=  daoSupport.update("SDtpYypzFollowUpSopMapper.deleteNodeConfigByTemplateId", pda);
                    if (b <= 0) {
                        throw new RuntimeException("节点信息更新删除失败");
                    }
                }
                // 将 JSON 字符串转换为 List<Map<String, Object>>
                ObjectMapper objectMapper = new ObjectMapper();
                List<Map<String, Object>> nodesList = objectMapper.readValue(nodesDataList.toString(), List.class);
                // 遍历列表并调用插入数据接口
                if (nodesList.size() > 0) {
                    for (int i = 0; i < nodesList.size(); i++) {
                        Map<String, Object> lxr = nodesList.get(i);
                        PageData pageData = new PageData();

                        // 自动生成节点名称和编码
                        String nodeName = "节点" + (i + 1); // 节点名称从节点1开始
                        String nodeCode = String.valueOf(i + 1); // 编码从1开始
                        pageData.put("nodeName", nodeName);
                        pageData.put("nodeCode", nodeCode);
                        pageData.put("templateId", templateId);
                        pageData.put("activateStructures", lxr.get("activateStructures"));
                        pageData.put("activateWhichDay", lxr.get("activateWhichDay"));
                        pageData.put("activateNodeRule", lxr.get("activateNodeRule"));
                        pageData.put("createTaskStructures", lxr.get("createTaskStructures"));
                        pageData.put("createTaskWhen", lxr.get("createTaskWhen"));
                        pageData.put("createTaskEvery", lxr.get("createTaskEvery"));
                        pageData.put("createTaskDi", lxr.get("createTaskDi"));
                        pageData.put("createTaskTriggerValue", lxr.get("createTaskTriggerValue"));
                        pageData.put("createTaskExecutionTimes", lxr.get("createTaskExecutionTimes"));
                        pageData.put("taskActionMode", lxr.get("taskActionMode"));
                        pageData.put("taskActionTaskType", lxr.get("taskActionTaskType"));
                        pageData.put("taskActionRole", lxr.get("taskActionRole"));
                        pageData.put("generationDaysAfter", lxr.get("generationDaysAfter"));
                        pageData.put("generationHMS", lxr.get("generationHMS"));
                        pageData.put("followUpSubject", lxr.get("followUpSubject"));
                        pageData.put("taskValidity", lxr.get("taskValidity"));
                        pageData.put("taskMaterial", lxr.get("taskMaterial"));
                        pageData.put("deliveryChannel", lxr.get("deliveryChannel"));
                        pageData.put("smsId",lxr.get("smsId"));
                        pageData.put("useForm",lxr.get("useForm"));
                        if(StringUtils.isNotEmpty(switchFlag)){
                            pageData.put("status",statusFla);//状态: 0已创建 1启用，2禁用 默认为已创建0
                        }else{
                            pageData.put("status",0);//状态: 0已创建 1启用，2禁用 默认为已创建0
                        }

                        // 处理 过滤条件 filtersData
                        @SuppressWarnings("unchecked")
                        List<Map<String, Object>> filtersData = (List<Map<String, Object>>) lxr.get("filtersData");
                        if (filtersData != null && !filtersData.isEmpty()) {
                            String filtersDataJson = objectMapper.writeValueAsString(filtersData);
                            pageData.put("filterCondition", filtersDataJson);
                        }
                        System.out.println("pageData:"+pageData);
                        int node1= dao.executeBatch("SDtpYypzFollowUpSopMapper.insertNodeConfig", pageData);
                        nodeList.add(pageData);
                        if (node1 <= 0) {
                            throw new RuntimeException("节点配置插入失败");
                        }
                    }
                    //                final HashMap<String, Object> addMap = new HashMap<String, Object>();
                    //                addMap.put("dataList", nodeList);
                    //批量插入暂时不用
                    //                int node= dao.executeBatch("SDtpYypzFollowUpSopMapper.batchAddNodeConfig", addMap);
                    //                if (node <= 0) {
                    //                    throw new RuntimeException("节点配置插入失败");
                    //                }
                }

        }

        } catch (Exception e) {
        e.printStackTrace();
    }   //修改模版信息
        pd.put("updatedBy",getSysUser().getLoginName());
        pd.put("updatedTime",DateUtils.getTime());
        pd.put("storeId",getSysUser().getDeptId().toString());//门店id
        pd.put("storeName",getSysUser().getDept().getDeptName());//门店名称
        if(StringUtils.isNotEmpty(switchFlag)){
            pd.put("status",statusFla);//状态: 0已创建 1启用，2禁用 默认为已创建0
        }else{
            pd.put("status",0);//状态: 0已创建 1启用，2禁用 默认为已创建0
        }
        int result =  daoSupport.update("SDtpYypzFollowUpSopMapper.updateSDtpYypzFollowUpSop", pd);
        if (result <= 0) {
            throw new RuntimeException("模版修改失败");
        }
        return result;

    }

    public Integer updateSopStatusByTemplateId(PageData pd)throws Exception {
        pd.put("updatedBy",getSysUser().getLoginName());
        pd.put("updatedTime",DateUtils.getTime());
        int b=0;
       int a=  daoSupport.update("SDtpYypzFollowUpSopMapper.updateSopStatusByTemplateId", pd);
       if(a>0){
           b=  daoSupport.update("SDtpYypzFollowUpSopMapper.updateNodeconfigStatusByTemplateId", pd);
       }
        System.out.println("a:"+a+"b:"+b);
       if(a>0 && b>0){
           return 2;
       }else{
           return 0;
       }
   }
}
