package com.hzya.frame.sysnew.integtationTaskLivingDetails.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hzya.frame.base.PluginBaseEntity;
import com.hzya.frame.basedao.entity.ConditionType;
import com.hzya.frame.basedao.entity.ConnectType;
import com.hzya.frame.basedao.entity.WhereCriterion;
import com.hzya.frame.basedao.service.impl.BaseDaoUtilImpl;
import com.hzya.frame.sysnew.integtationTaskLivingDetails.entity.IntegrationTaskLivingDetailsEntity;
import com.hzya.frame.sysnew.integtationTaskLivingDetails.dao.IIntegrationTaskLivingDetailsDao;
import com.hzya.frame.sysnew.integtationTaskLivingDetails.entity.IntegrationTaskLivingDetailsVo;
import com.hzya.frame.sysnew.integtationTaskLivingDetails.service.IIntegrationTaskLivingDetailsService;
import com.hzya.frame.sysnew.integtationTaskLog.entity.IntegrationTaskLogEntity;
import com.hzya.frame.util.PluginUtils;
import com.hzya.frame.uuid.UUIDLong;
import com.hzya.frame.uuid.UUIDUtils;
import com.hzya.frame.web.entity.BaseResult;
import com.hzya.frame.web.entity.JsonResultEntity;
import com.hzya.frame.web.exception.BaseSystemException;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import javax.annotation.Resource;
import com.hzya.frame.basedao.service.impl.BaseService;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 集成任务-实例详情(IntegrationTaskLivingDetails)表服务实现类
 *
 * @author makejava
 * @since 2024-05-15 14:06:46
 */
@Service(value = "integrationTaskLivingDetailsService")
public class IntegrationTaskLivingDetailsServiceImpl extends BaseService<IntegrationTaskLivingDetailsEntity, String> implements IIntegrationTaskLivingDetailsService {

    private IIntegrationTaskLivingDetailsDao integrationTaskLivingDetailsDao;
    @Resource
    private TaskExecutor taskExecutor;

    @Autowired
    private BaseDaoUtilImpl baseDaoUtilImpl;
    @Autowired
	public void setIntegrationTaskLivingDetailsDao(IIntegrationTaskLivingDetailsDao dao) {
		this.integrationTaskLivingDetailsDao = dao;
		this.dao = dao;
	}
/**
 *
 * @content 完全用于测试，此接口不使用1
 * @author laborer
 * @date 2024/5/15 0015 16:00
 *
 */

    @Override
    public JsonResultEntity testLog(JSONObject jsonObject)throws Exception {
        IntegrationTaskLivingDetailsEntity entity = getData("jsonStr", jsonObject, IntegrationTaskLivingDetailsEntity.class);
        String def1 = entity.getDef1();
        switch (def1){
            case "1":
                return saveLogToSuccess(entity);
            case "2":
                return saveLogToFail(entity);
            case "3":
                return saveLogFailToSuccess(entity);
            case "4":
                return updateLogFailToSuccess(entity);
            default:
                break;
        }
        return null;
    }

    /**
     *
     * @content 成功日志公用接口
     * @author laborer
     * @date 2024/5/15 0015 15:05
     *
     */
    @Override
    public JsonResultEntity saveLogToSuccess(IntegrationTaskLivingDetailsEntity entity)throws Exception {
        entity.setId(String.valueOf(UUIDLong.longUUID()));
        checkDate(entity);
        entity.setNewState("Y");
        entity.setRepairPust("N");
        try {
            entity = integrationTaskLivingDetailsDao.saveSuccessLog(entity);
            return BaseResult.getSuccessMessageEntity(entity);
        } catch (Exception e) {
            e.printStackTrace();
            return BaseResult.getFailureMessageEntity("保存成功日志失败："+e.getMessage());
        }

    }


    /**
     *
     * @content 失败日志公用接口
     * @author laborer
     * @date 2024/5/15 0015 15:05
     *
     */
    @Override
    public JsonResultEntity saveLogToFail(IntegrationTaskLivingDetailsEntity entity)throws Exception {
        entity.setId(String.valueOf(UUIDLong.longUUID()));
        //验证必填字段如果不满足返回数据
        checkDate(entity);
        entity.setNewState("N");
        entity.setRepairPust("Y");
        try {
            entity = integrationTaskLivingDetailsDao.save(entity);
            return BaseResult.getSuccessMessageEntity(entity);
        } catch (Exception e) {
            e.printStackTrace();
            return BaseResult.getFailureMessageEntity("保存失败日志错误："+e.getMessage());
        }
    }
    /**
     *
     * @content 重推成功接口(成功数据挪到成功日志表)
     * @author laborer
     * @date 2024/5/15 0015 15:05
     *
     */
    @Override
    public JsonResultEntity saveLogFailToSuccess(IntegrationTaskLivingDetailsEntity entity)throws Exception {
        //验证必填字段如果不满足返回数据
        checkDate(entity);
        entity.setNewState("Y");
        entity.setRepairPust("N");
        try {
            //先根据主键删除错误日志表数据，在进行成功表写入
            integrationTaskLivingDetailsDao.delete(entity.getId());
            //将数据写入成功日志表
            entity = integrationTaskLivingDetailsDao.saveSuccessLog(entity);
            return BaseResult.getSuccessMessageEntity(entity);
        } catch (Exception e) {
            e.printStackTrace();
            return BaseResult.getFailureMessageEntity("保存失败日志错误："+e.getMessage());
        }
    }
    /**
     *
     * @content 重推失败更新接口
     * @author laborer
     * @date 2024/5/15 0015 15:05
     *
     */
    @Override
    public JsonResultEntity updateLogFailToSuccess(IntegrationTaskLivingDetailsEntity entity)throws Exception {
        //验证必填字段如果不满足返回数据
        checkDate(entity);
        entity.setNewState("N");
        entity.setRepairPust("Y");
        try {
            //将数据写入成功日志表
            entity = integrationTaskLivingDetailsDao.update(entity);
            return BaseResult.getSuccessMessageEntity(entity);
        } catch (Exception e) {
            e.printStackTrace();
            return BaseResult.getFailureMessageEntity("更新失败日志错误："+e.getMessage());
        }
    }
    /**
     *
     * @content 验证数据必填项
     * @author laborer
     * @date 2024/5/15 0015 15:42
     *
     */

    private void checkDate(IntegrationTaskLivingDetailsEntity entity)throws Exception{
        //todo 除了必填字段理论都可以为空 根据业务需求自己定义
        //验证必填字段如果不满足返回数据
        String id = entity.getId();//不可为空，数据主键
        if (StrUtil.isEmpty(id)) {
            throw new BaseSystemException("主键不可为空，请传入");
        }
        String rootAppPk = entity.getRootAppPk();//源系统主键（通过该条件进行重推时数据查询不可为空）
        if (StrUtil.isEmpty(rootAppPk)) {
            throw new BaseSystemException("源系统主键不可为空，请传入");
        }
        String rootAppBill = entity.getRootAppBill();//源系统单号（通过该条件进行重查询条件不可为空）
        if (StrUtil.isEmpty(rootAppBill)) {
            throw new BaseSystemException("源系统单号不可为空，请传入");
        }
        String pluginId = entity.getPluginId();//插件ID 用于任务寻找插件方法字段（不可为空）
        if (StrUtil.isEmpty(pluginId)) {
            throw new BaseSystemException("插件ID不可为空，请传入");
        }
        String rootAppNewData = entity.getRootAppNewData();//推送数据-最新（不可为空）
        if (StrUtil.isEmpty(rootAppNewData)) {
            throw new BaseSystemException("推送数据-最新不可为空，请传入");
        }
        String newTransmitInfo = entity.getNewTransmitInfo();//三方系统返回数据（不可为空）
        if (StrUtil.isEmpty(newTransmitInfo)) {
            throw new BaseSystemException("三方系统返回数据不可为空，请传入");
        }
//        String repairPust = entity.getRepairPust();//是否补推(Y是N不是) 成功情况下默认N不需要补退
//        if (StrUtil.isEmpty(repairPust)) {
//            throw new BaseSystemException("是否补推不可为空，请传入");
//        }
//        String newState = entity.getNewState();//推送状态 成功情况下默认Y
//        if (StrUtil.isEmpty(newState)) {
//            throw new BaseSystemException("推送状态不可为空，请传入");
//        }
    }
    /**
     * @param object
     * @return com.hzya.frame.web.entity.JsonResultEntity
     * @Author lvleigang
     * @Description 查询列表 分页
     * @Date 2:18 下午 2023/7/17
     **/
    @Override
    public JsonResultEntity queryPage(JSONObject object) {
        IntegrationTaskLivingDetailsVo entity = getData("jsonStr", object, IntegrationTaskLivingDetailsVo.class);
        //判断分页
        if (entity == null || entity.getPageNum() == null || entity.getPageSize() == null) {
            return BaseResult.getFailureMessageEntity("分页查询参数不存在");
        }
        if(entity.getNew_state() == null  || "".equals(entity.getNew_state()) ){
            return BaseResult.getFailureMessageEntity("请先选择数据状态");
        }
        PageHelper.startPage(entity.getPageNum(), entity.getPageSize());
        List<IntegrationTaskLivingDetailsVo> integrationTaskLivingDetailsEntityList = integrationTaskLivingDetailsDao.queryPageLeftTask(entity);
        if (integrationTaskLivingDetailsEntityList != null && integrationTaskLivingDetailsEntityList.size() > 0) {
            for (int i = 0; i < integrationTaskLivingDetailsEntityList.size(); i++) {
                PluginBaseEntity pluginBaseEntity = PluginUtils.getPluginsById(integrationTaskLivingDetailsEntityList.get(i).getPlugin_id());
                if (pluginBaseEntity != null) {
                    integrationTaskLivingDetailsEntityList.get(i).setPlugin_name(pluginBaseEntity.getPluginName());
                }
            }
        }
        PageInfo pageInfo = new PageInfo(integrationTaskLivingDetailsEntityList);
        return BaseResult.getSuccessMessageEntity("查询数据成功", pageInfo);
    }

    /**
     * @param object
     * @return com.hzya.frame.web.entity.JsonResultEntity
     * @Author lvleigang
     * @Description 获取数据 根据id
     * @Date 2:18 下午 2023/7/17
     **/
    @Override
    public JsonResultEntity queryEntity(JSONObject object) {
        IntegrationTaskLivingDetailsEntity entity = getData("jsonStr", object, IntegrationTaskLivingDetailsEntity.class);
        //判断分页
        if (entity == null || entity.getId() == null || "".equals(entity.getId())) {
            return BaseResult.getFailureMessageEntity("请先传递请求主键");
        }
        if(entity.getNewState() == null  || "".equals(entity.getNewState()) ){
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        IntegrationTaskLivingDetailsEntity appApi = integrationTaskLivingDetailsDao.queryEntity(entity);
        return BaseResult.getSuccessMessageEntity("查询数据成功", appApi);
    }

    /**
     * @param object
     * @return com.hzya.frame.web.entity.JsonResultEntity
     * @Author lvleigang
     * @Description 批量推送
     * @Date 2:18 下午 2023/7/17
     **/
    @Override
    public JsonResultEntity batchPush(JSONObject object) {
        if(object.get("jsonStr") == null ){
            return BaseResult.getFailureMessageEntity("请先选择要推送的数据");
        }
        List<IntegrationTaskLivingDetailsEntity> jsonArray = JSONArray.parseArray(object.getString("jsonStr"),IntegrationTaskLivingDetailsEntity.class);
      if(jsonArray != null && jsonArray.size() > 0){
          for (int i = 0; i < jsonArray.size(); i++) {
              String plugin_id = jsonArray.get(i).getPluginId();
              PluginBaseEntity pluginBaseEntity = PluginUtils.getPluginsById(plugin_id);
              JSONObject send = new JSONObject();
              send.put("type", "details_error");
              send.put("pluginId", plugin_id);
              send.put("integration_task_living_details_id", jsonArray.get(i).getId());
              try {
                  taskExecutor.execute(() -> {
                      try {
                          pluginBaseEntity.executeBusiness(send);
                      } catch (Exception e) {
                          logger.error("执行任务失败"+e.getMessage());
                      }
                  });

              } catch (Exception e) {
                  logger.error("执行任务失败"+e.getMessage());
              }
          }
      }

        return BaseResult.getSuccessMessageEntity("重新推送成功");
    }

    /**
     * @param object
     * @return com.hzya.frame.web.entity.JsonResultEntity
     * @Author lvleigang
     * @Description 重新推送
     * @Date 2:18 下午 2023/7/17
     **/
    @Override
    public JsonResultEntity repush(JSONObject object) {
        JSONObject jsonObject = getstrObj("jsonStr", object);
        String id = jsonObject.getString("id");
        String status = jsonObject.getString("new_state");
        if (!checkStr(id)) {
            return BaseResult.getFailureMessageEntity("请先选择要推送的数据");
        }
        if (!checkStr(status)) {
            return BaseResult.getFailureMessageEntity("请先选择要推送的数据");
        }
        IntegrationTaskLivingDetailsEntity queryEntity = new IntegrationTaskLivingDetailsEntity();
        queryEntity.setNewState(status);
        queryEntity.setId(id);
        IntegrationTaskLivingDetailsEntity entity = integrationTaskLivingDetailsDao.queryEntity(queryEntity);
        String plugin_id = entity.getPluginId();
        PluginBaseEntity pluginBaseEntity = PluginUtils.getPluginsById(plugin_id);
        JSONObject send = new JSONObject();
        send.put("type", "details_error");
        send.put("pluginId", plugin_id);
        send.put("integration_task_living_details_id", id);
        try {
            pluginBaseEntity.executeBusiness(send);
            return BaseResult.getSuccessMessageEntity("重新推送成功");
        } catch (Exception e) {
            return BaseResult.getFailureMessageEntity("重新推送失败");
        }
    }

    /**
     * @param object
     * @return com.hzya.frame.web.entity.JsonResultEntity
     * @Author lvleigang
     * @Description 手工处理
     * @Date 2:18 下午 2023/7/17
     **/
    @Override
    public JsonResultEntity manualProcessing(JSONObject object) {
        IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity = getData("jsonStr", object, IntegrationTaskLivingDetailsEntity.class);
        if (integrationTaskLivingDetailsEntity == null && integrationTaskLivingDetailsEntity.getId() != null && !"".equals(integrationTaskLivingDetailsEntity.getId())) {
            return BaseResult.getFailureMessageEntity("请求参数不存在");
        }
        IntegrationTaskLivingDetailsEntity entity = integrationTaskLivingDetailsDao.queryEntity(integrationTaskLivingDetailsEntity);
        if("N".equals(integrationTaskLivingDetailsEntity.getNewState())){
            integrationTaskLivingDetailsDao.deleteById(integrationTaskLivingDetailsEntity.getId());
            entity.setId(UUIDUtils.getUUID());
        }
        entity.setModify_user_id(StpUtil.getLoginIdAsString());
        entity.setModify_time(new Date());
        entity.setProcessor(StpUtil.getLoginIdAsString());
        //检查用户名密码是否正确
        List<WhereCriterion> whereList = new ArrayList<>();
        WhereCriterion passwordCondition = new WhereCriterion("", "id", ConditionType.等于.getValue(), StpUtil.getLoginIdAsString(), "", ConnectType.AND);
        whereList.add(passwordCondition);
        HashMap<String, Object> userMap = baseDaoUtilImpl.selectOne("sys_user", whereList);
        entity.setProcessorName(userMap.get("login_code").toString());
        entity.setProcessingTime(new Date());
        entity.setNewState("H");
        entity.setProcessingRemarks(integrationTaskLivingDetailsEntity.getProcessingRemarks());
        if("N".equals(integrationTaskLivingDetailsEntity.getNewState())){
            integrationTaskLivingDetailsDao.saveSuccessLog(entity);
        }else {
            integrationTaskLivingDetailsDao.update(entity);
        }
        return BaseResult.getSuccessMessageEntity("手工处理成功");
    }

    /**
     * @param object
     * @return com.hzya.frame.web.entity.JsonResultEntity
     * @Author lvleigang
     * @Description 删除
     * @Date 2:18 下午 2023/7/17
     **/
    @Override
    public JsonResultEntity deleteEntity(JSONObject object) {
        IntegrationTaskLivingDetailsEntity entity = getData("jsonStr", object, IntegrationTaskLivingDetailsEntity.class);
        //判断编码是否重复
        if (entity == null) {
            return BaseResult.getFailureMessageEntity("请先选择数据");
        }
        if (entity.getId() == null || "".equals(entity.getId())) {
            return BaseResult.getFailureMessageEntity("请先选择数据");
        }
        if (entity.getNewState() == null || "".equals(entity.getNewState())) {
            return BaseResult.getFailureMessageEntity("请先选择数据");
        }
        //删除
        IntegrationTaskLivingDetailsEntity deleteEntity = new IntegrationTaskLivingDetailsEntity();
        deleteEntity.setId(entity.getId());
        deleteEntity.setModify_user_id(StpUtil.getLoginIdAsString());
        deleteEntity.setModify_time(new Date());
        deleteEntity.setSts("Y");
        deleteEntity.setNewState(entity.getNewState());
        integrationTaskLivingDetailsDao.deleteEntity(deleteEntity);
        return BaseResult.getSuccessMessageEntity("删除成功");
    }
}
