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.SnowflakeIdGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
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.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();
        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("creator", getSysUser().getLoginName());
                        pageData.put("createTime", DateUtils.getTime());
                        pageData.put("productName", lxr.get("productName"));
                        pageData.put("genericName", lxr.get("genericName"));
                        pageData.put("mdmCode", lxr.get("mdmCode"));
                        pageData.put("specification", lxr.get("specification"));
                        pageData.put("isFlipItem", lxr.get("isFlipItem"));
                        pageData.put("soptemplateId", templateId);
                        addList.add(pageData);
                    }
                    final HashMap<String, Object> addMap = new HashMap<String, Object>();
                    addMap.put("dataList", addList);
                    int resultDrug= dao.executeBatch("DTPMapper.batchAddPrescriptionDrug", 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 (Map<String, Object> lxr : nodesList) {
                    PageData pageData = new PageData();
                    pageData.put("creator", getSysUser().getLoginName());
                    pageData.put("createTime", DateUtils.getTime());
                    pageData.put("sopTemplateId", templateId);
                    pageData.put("nodeName", lxr.get("nodeName"));
                    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("creator",getSysUser().getLoginName());
                    pageData.put("createTime",DateUtils.getTime());
                    pageData.put("status",0);//0已创建 1启用，2禁用
                    pageData.put("deliveryChannel",lxr.get("createTaskStructures"));
                    // 处理 过滤条件 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);
                    }

                    nodeList.add(pageData);
                }
                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已创建 1启用，2禁用
        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 Integer SDtpYypzFollowUpSopRemove(PageData pd)throws Exception {
        return daoSupport.delete("SDtpYypzFollowUpSopMapper.SDtpYypzFollowUpSopRemove", pd);
    }


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

}
