package com.zt.plat.module.qms.resource.device.service;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zt.plat.framework.common.pojo.CommonResult;
import com.zt.plat.framework.security.core.LoginUser;
import com.zt.plat.framework.security.core.util.SecurityFrameworkUtils;
import com.zt.plat.module.bpm.api.task.BpmProcessInstanceApi;
import com.zt.plat.module.bpm.api.task.dto.BpmProcessInstanceCreateReqDTO;
import com.zt.plat.module.qms.api.task.BMPCallbackInterface;
import com.zt.plat.module.qms.api.task.dto.QmsBpmDTO;
import com.zt.plat.module.qms.common.data.dal.dataobject.DataCommonType;
import com.zt.plat.module.qms.common.data.dal.dataobject.DataTemplateDO;
import com.zt.plat.module.qms.common.data.service.DataKeyCheckService;
import com.zt.plat.module.qms.common.data.service.DataOpinionService;
import com.zt.plat.module.qms.common.data.service.DataTemplateService;
import com.zt.plat.module.qms.common.dic.service.DictionaryBusinessService;
import com.zt.plat.module.qms.common.service.BusinessFileService;
import com.zt.plat.module.qms.enums.QmsBpmConstant;
import com.zt.plat.module.qms.enums.QmsCommonConstant;
import com.zt.plat.module.qms.resource.device.common.DeviceConstant;
import com.zt.plat.module.qms.resource.device.controller.vo.*;
import com.zt.plat.module.qms.resource.device.dal.dataobject.*;
import com.zt.plat.module.qms.resource.material.dal.dataobject.MaterialInfoWithBizConfigVO;
import com.zt.plat.module.qms.resource.material.service.MaterialInfomationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;

import java.text.SimpleDateFormat;
import java.util.*;

import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.framework.common.util.object.BeanUtils;

import com.zt.plat.module.qms.resource.device.dal.mapper.DevicePeriodCheckMapper;

import static com.zt.plat.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.zt.plat.framework.common.exception.util.ServiceExceptionUtil.exception0;
import static com.zt.plat.framework.common.util.collection.CollectionUtils.convertList;
import static com.zt.plat.module.qms.enums.ErrorCodeConstants.DEVICE_PERIOD_CHECK_NOT_EXISTS;
import static com.zt.plat.module.qms.enums.QmsBpmConstant.BPM_CALLBACK_BEAN_NAME;

/**
 * 设备-期间核查 Service 实现类
 *
 * @author 后台管理-1
 */
@Service("devicePeriodCheckService")
@Validated
@Slf4j
public class DevicePeriodCheckServiceImpl implements DevicePeriodCheckService, BMPCallbackInterface {

    @Resource private DevicePeriodCheckMapper devicePeriodCheckMapper;
    @Resource private DeviceInfomationService deviceInfomationService;
    @Resource private MaterialInfomationService materialInfomationService;
    @Resource private DictionaryBusinessService dictionaryBusinessService;
    @Resource private BpmProcessInstanceApi bpmProcessInstanceApi;
    @Resource private DataKeyCheckService dataKeyCheckService;
    @Resource private DataOpinionService dataOpinionService;
    @Resource private DataTemplateService dataTemplateService;
    @Resource private BusinessFileService businessFileService;
    private final String wfDicKey = "DevicePeriodCheckWfKey";
    private final String formDicKey = "DevicePeriodCheckFormfKey";

    /*
     * 创建本年度的期间核查列表
     * 1、取所有需要期间核查的设备、物料
     * 2、计算下次日期
     * 3、标识不能计算下次日期的数据
     * 4、保存数据
     * */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createListByPlanDevice(DevicePeriodCheckPlanDO plan) {
        Long planId = plan.getId();
        String checkYear = plan.getCheckYear();
        JSONObject ruleParam = new JSONObject();
        ruleParam.put("businessType", DeviceConstant.PERIOD_TYPE);
        List<DevicePeriodCheckDO> checkList = new ArrayList<>();
        String wfStatus = QmsCommonConstant.COMPLETED;
        //处理设备
        List<DeviceInfoWithBizConfigVO> deviceList = deviceInfomationService.getListNeedByRule(ruleParam);
        List<Long> deviceIds = convertList(deviceList, DeviceInfoWithBizConfigVO::getId);
        List<DevicePeriodCheckVO> lastDeviceDataList = getLastDataCheckList(deviceIds, wfStatus).getData();
        String formKey = dictionaryBusinessService.getValueByDataKey(formDicKey);
        DataTemplateDO formTemplate = dataTemplateService.getLatestDataByKey(formKey);
        Long formTemplateId = formTemplate.getId();
        for (DeviceInfoWithBizConfigVO device : deviceList) {
            DeviceConfigBusinessRuleDO rule = device.getRule();
            Long deviceId = device.getId();
            initPeriodCheckData(planId, checkList, lastDeviceDataList, rule, deviceId, formTemplateId, DeviceConstant.PERIOD_CHECK_TAGET_DEVICE);
        }

        devicePeriodCheckMapper.insertBatch(checkList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createListByPlanMaterial(DevicePeriodCheckPlanDO plan) {
        Long planId = plan.getId();
        String checkYear = plan.getCheckYear();
        JSONObject ruleParam = new JSONObject();
        ruleParam.put("businessType", DeviceConstant.PERIOD_TYPE);
        List<DevicePeriodCheckDO> checkList = new ArrayList<>();
        String wfStatus = QmsCommonConstant.COMPLETED;

        String formKey = dictionaryBusinessService.getValueByDataKey(formDicKey);
        DataTemplateDO formTemplate = dataTemplateService.getLatestDataByKey(formKey);
        Long formTemplateId = formTemplate.getId();

        //处理物料试剂
        List<MaterialInfoWithBizConfigVO> materialList = materialInfomationService.getListNeedByRule(ruleParam);
        List<Long> materialIds = convertList(materialList, MaterialInfoWithBizConfigVO::getId);
        List<DevicePeriodCheckVO> lastMaterialDataList = getLastDataCheckList(materialIds, wfStatus).getData();
        for (MaterialInfoWithBizConfigVO material : materialList) {
            DeviceConfigBusinessRuleDO rule = material.getRule();
            Long deviceId = material.getId();
            initPeriodCheckData(planId, checkList, lastMaterialDataList, rule, deviceId, formTemplateId, DeviceConstant.PERIOD_CHECK_TAGET_MATERIAL);
        }
        devicePeriodCheckMapper.insertBatch(checkList);
    }

    private void initPeriodCheckData(Long planId, List<DevicePeriodCheckDO> checkList, List<DevicePeriodCheckVO> lastCheckList, DeviceConfigBusinessRuleDO rule, Long deviceId,
                                     Long formTemplateId, String checkTarget) {
        DevicePeriodCheckDO data = new DevicePeriodCheckDO();
        DevicePeriodCheckVO lastCheck = null;
        for(DevicePeriodCheckVO check : lastCheckList){
            if(check.getDeviceId().equals(deviceId)){
                lastCheck = check;
                break;
            }
        }
        if(lastCheck != null)
            data.setLastCheckDate(lastCheck.getCheckDate());
        //todo 计算计划执行日期
        //todo 过滤当前年度已执行过期间核查的数据
        data.setPlanId(planId);
        data.setDeviceId(deviceId);
        data.setCheckPersonRemark(rule.getTreatmentUser());
        data.setCheckAccording(rule.getTreatmentMethod());
        data.setFrequencyRemark(rule.getFrequencyRemark());
        data.setFlowStatus(QmsCommonConstant.NOT_START);
        data.setFormId(formTemplateId);
        data.setCheckTarget(checkTarget);
        checkList.add(data);
    }

    @Override
    public CommonResult<List<DevicePeriodCheckVO>> getLastDataCheckList(List<Long> deviceIds, String flowStatus) {
        JSONObject param = new JSONObject();
        param.put("deviceIds", deviceIds);
        param.put("flowStatus", flowStatus);
        List<DevicePeriodCheckVO> list = devicePeriodCheckMapper.getLastDataCheckList(param);
        return CommonResult.success(list);
    }


    @Override
    public IPage<DevicePeriodCheckVO> queryPageListDevice(Page<DevicePeriodCheckPageReqVO> page, DevicePeriodCheckPageReqVO pageReqVO) {
        return devicePeriodCheckMapper.queryPageListDevice(page, pageReqVO);
    }

    @Override
    public IPage<DevicePeriodCheckVO> queryPageListMaterial(Page<DevicePeriodCheckPageReqVO> page, DevicePeriodCheckPageReqVO pageReqVO) {
        return devicePeriodCheckMapper.queryPageListMaterial(page, pageReqVO);
    }

    @Override
    public void updateEffectiveFlag(Long planId, String effectiveFlag) {
        LambdaUpdateWrapper<DevicePeriodCheckDO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(DevicePeriodCheckDO::getPlanId, planId);
        updateWrapper.set(DevicePeriodCheckDO::getEffectiveFlag, effectiveFlag);
        devicePeriodCheckMapper.update(updateWrapper);
    }

    @Override
    public List<DevicePeriodCheckDO> getListByPlanId(Long planId) {
        LambdaQueryWrapper<DevicePeriodCheckDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DevicePeriodCheckDO::getPlanId, planId);
        return devicePeriodCheckMapper.selectList(queryWrapper);
    }

    @Override
    public CommonResult<DevicePeriodCheckRespVO> submitApply(DevicePeriodCheckSaveReqVO paramVO) {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        //当前登录用户昵称
        String nickName = SecurityFrameworkUtils.getLoginUserNickname();
        Long id = paramVO.getId();
        DevicePeriodCheckDO entity = getDevicePeriodCheck(id);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String processDefKey = dictionaryBusinessService.getValueByDataKey(wfDicKey);
        if(ObjectUtils.isEmpty(processDefKey))
            throw exception0(DEVICE_PERIOD_CHECK_NOT_EXISTS.getCode(), "请先配置流程定义");
        Map<String, Object> variables = new JSONObject();
        variables.put("mainId",  id);
        variables.put("applyUser",  nickName);
        variables.put("applyUserId",  loginUser.getId());
        variables.put("applyDepartment",  loginUser.getVisitDeptName());
        variables.put("applyDepartmentId",  loginUser.getVisitDeptId());
        variables.put("applyTime",  sdf.format(new Date()));
        variables.put(BPM_CALLBACK_BEAN_NAME, "devicePeriodCheckService"); //流程回调时使用的service
        BpmProcessInstanceCreateReqDTO reqDTO = new BpmProcessInstanceCreateReqDTO();
        reqDTO.setBusinessKey(String.valueOf(id));
        reqDTO.setProcessDefinitionKey(processDefKey);
        reqDTO.setVariables(variables);
        CommonResult<String> result = bpmProcessInstanceApi.createProcessInstance(loginUser.getId(), reqDTO);
        if(!result.isSuccess()){
            throw exception0(DEVICE_PERIOD_CHECK_NOT_EXISTS.getCode(), result.getMsg());
        }
        String wfInsId = result.getData();
        entity.setFlowInstanceId(wfInsId);
        entity.setFlowStatus(QmsCommonConstant.IN_PROGRESS);
        devicePeriodCheckMapper.updateById(entity);
        DevicePeriodCheckRespVO respVO = BeanUtils.toBean(entity, DevicePeriodCheckRespVO.class);
        return CommonResult.success(respVO);
    }

    @Override
    public DevicePeriodCheckVO getVoDevice(Long id) {
        Page<DevicePeriodCheckPageReqVO> page = new Page<>(1,10);
        DevicePeriodCheckPageReqVO param = new DevicePeriodCheckPageReqVO();
        param.setId( id);
        IPage<DevicePeriodCheckVO> pageList = queryPageListDevice(page, param);
        PageResult<DevicePeriodCheckVO> pageResult = new PageResult<>(pageList.getRecords(), pageList.getTotal());
        if(pageResult.getList().isEmpty())
            return null;
        DevicePeriodCheckVO vo = pageResult.getList().get(0);
        //处理审批意见
        JSONObject opinion = dataOpinionService.assembleOpinion(id);
        vo.setSignatureData( opinion);
        return vo;
    }

    @Override
    public DevicePeriodCheckVO getVoMaterial(Long id) {
        Page<DevicePeriodCheckPageReqVO> page = new Page<>(1,10);
        DevicePeriodCheckPageReqVO param = new DevicePeriodCheckPageReqVO();
        param.setId( id);
        IPage<DevicePeriodCheckVO> pageList = queryPageListMaterial(page, param);
        PageResult<DevicePeriodCheckVO> pageResult = new PageResult<>(pageList.getRecords(), pageList.getTotal());
        if(pageResult.getList().isEmpty())
            return null;
        DevicePeriodCheckVO vo = pageResult.getList().get(0);
        //处理审批意见
        JSONObject opinion = dataOpinionService.assembleOpinion(id);
        vo.setSignatureData( opinion);
        return vo;
    }

    @Override
    public DevicePeriodCheckRespVO createDevicePeriodCheck(DevicePeriodCheckSaveReqVO createReqVO) {
        // 插入
        DevicePeriodCheckDO devicePeriodCheck = BeanUtils.toBean(createReqVO, DevicePeriodCheckDO.class);
        devicePeriodCheckMapper.insert(devicePeriodCheck);
        // 返回
        return BeanUtils.toBean(devicePeriodCheck, DevicePeriodCheckRespVO.class);
    }

    @Override
    public DevicePeriodCheckRespVO createByDeviceId(DevicePeriodCheckSaveReqVO createReqVO) {
        Long deviceId = createReqVO.getDeviceId();
        if(deviceId == null)
            throw exception0(DEVICE_PERIOD_CHECK_NOT_EXISTS.getCode(), "请选择设备或标准物质");
        JSONObject ruleParam = new JSONObject();
        ruleParam.put("businessType", DeviceConstant.PERIOD_TYPE);
        ruleParam.put("deviceId", deviceId);
        List<DeviceInfoWithBizConfigVO> deviceList = deviceInfomationService.getListNeedByRule(ruleParam);
        if(deviceList.isEmpty()){
            throw exception0(DEVICE_PERIOD_CHECK_NOT_EXISTS.getCode(), "当前设备未配置期间核查规则，请配置后再操作");
        }
        DeviceInfoWithBizConfigVO configVO = deviceList.get(0);
        DeviceConfigBusinessRuleDO rule = configVO.getRule();
        if(rule == null){
            throw exception0(DEVICE_PERIOD_CHECK_NOT_EXISTS.getCode(), "当前设备未配置期间核查规则，请配置后再操作");
        }
        String formKey = dictionaryBusinessService.getValueByDataKey(formDicKey);
        DataTemplateDO formTemplate = dataTemplateService.getLatestDataByKey(formKey);
        Long formTemplateId = formTemplate.getId();
        DevicePeriodCheckDO entity = new DevicePeriodCheckDO();
        entity.setDeviceId(deviceId);
        entity.setPlanId(0L);
        entity.setEffectiveFlag("1");
        entity.setFormId(formTemplateId);
        entity.setFlowStatus(QmsCommonConstant.NOT_START);
        entity.setCheckTarget(DeviceConstant.PERIOD_CHECK_TAGET_DEVICE);

        entity.setFrequencyRemark(rule.getFrequencyRemark());
        entity.setCheckPersonRemark(rule.getTreatmentUser());
        entity.setCheckAccording(rule.getTreatmentMethod());
        entity.setFrequencyRemark(rule.getFrequencyRemark());
        devicePeriodCheckMapper.insert(entity);
        return BeanUtils.toBean(entity, DevicePeriodCheckRespVO.class);
    }

    @Override
    public DevicePeriodCheckRespVO createByMaterialId(DevicePeriodCheckSaveReqVO createReqVO) {
        Long deviceId = createReqVO.getDeviceId();
        if(deviceId == null)
            throw exception0(DEVICE_PERIOD_CHECK_NOT_EXISTS.getCode(), "请选择设备或标准物质");
        JSONObject ruleParam = new JSONObject();
        ruleParam.put("businessType", DeviceConstant.PERIOD_TYPE);
        ruleParam.put("deviceId", deviceId);
        List<MaterialInfoWithBizConfigVO> materialList = materialInfomationService.getListNeedByRule(ruleParam);
        if(materialList.isEmpty()){
            throw exception0(DEVICE_PERIOD_CHECK_NOT_EXISTS.getCode(), "当前物料未配置期间核查规则，请配置后再操作");
        }
        MaterialInfoWithBizConfigVO configVO = materialList.get(0);
        DeviceConfigBusinessRuleDO rule = configVO.getRule();
        if(rule == null){
            throw exception0(DEVICE_PERIOD_CHECK_NOT_EXISTS.getCode(), "当前物料未配置期间核查规则，请配置后再操作");
        }
        String formKey = dictionaryBusinessService.getValueByDataKey(formDicKey);
        DataTemplateDO formTemplate = dataTemplateService.getLatestDataByKey(formKey);
        Long formTemplateId = formTemplate.getId();
        DevicePeriodCheckDO entity = new DevicePeriodCheckDO();
        entity.setDeviceId(deviceId);
        entity.setPlanId(0L);
        entity.setEffectiveFlag("1");
        entity.setFormId(formTemplateId);
        entity.setFlowStatus(QmsCommonConstant.NOT_START);
        entity.setCheckTarget(DeviceConstant.PERIOD_CHECK_TAGET_MATERIAL);
        entity.setFrequencyRemark(rule.getFrequencyRemark());
        entity.setCheckPersonRemark(rule.getTreatmentUser());
        entity.setCheckAccording(rule.getTreatmentMethod());
        entity.setFrequencyRemark(rule.getFrequencyRemark());
        devicePeriodCheckMapper.insert(entity);
        return BeanUtils.toBean(entity, DevicePeriodCheckRespVO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DevicePeriodCheckDO updateDevicePeriodCheck(DevicePeriodCheckSaveReqVO updateReqVO) {
        // 校验存在
        validateDevicePeriodCheckExists(updateReqVO.getId());
        // 更新
        DevicePeriodCheckDO updateObj = BeanUtils.toBean(updateReqVO, DevicePeriodCheckDO.class);
        devicePeriodCheckMapper.updateById(updateObj);
        businessFileService.deleteBusinessFileList(updateReqVO.getDeleteFileIdList());
        return updateObj;
    }

    @Override
    public void deleteDevicePeriodCheck(Long id) {
        // 校验存在
        validateDevicePeriodCheckExists(id);
        // 删除
        devicePeriodCheckMapper.deleteById(id);
    }

    @Override
        public void deleteDevicePeriodCheckListByIds(List<Long> ids) {
        // 校验存在
        validateDevicePeriodCheckExists(ids);
        // 删除
        devicePeriodCheckMapper.deleteByIds(ids);
        }

    private void validateDevicePeriodCheckExists(List<Long> ids) {
        List<DevicePeriodCheckDO> list = devicePeriodCheckMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(DEVICE_PERIOD_CHECK_NOT_EXISTS);
        }
    }

    private void validateDevicePeriodCheckExists(Long id) {
        if (devicePeriodCheckMapper.selectById(id) == null) {
            throw exception(DEVICE_PERIOD_CHECK_NOT_EXISTS);
        }
    }

    @Override
    public DevicePeriodCheckDO getDevicePeriodCheck(Long id) {
        return devicePeriodCheckMapper.selectById(id);
    }

    @Override
    public PageResult<DevicePeriodCheckDO> getDevicePeriodCheckPage(DevicePeriodCheckPageReqVO pageReqVO) {
        return devicePeriodCheckMapper.selectPage(pageReqVO);
    }

    @Override
    public void updateBatch(List<DevicePeriodCheckDO> list) {
        devicePeriodCheckMapper.updateBatch(list);
    }

    @Override
    public void insertBatch(List<DevicePeriodCheckDO> list) {
        devicePeriodCheckMapper.insertBatch(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<JSONObject> callback(QmsBpmDTO reqDTO) {
        log.error("流程回调：{}", JSONObject.toJSONString(reqDTO));
        JSONObject variables = reqDTO.getVariables();
        JSONObject taskVariables = variables.getJSONObject("taskVariables");
        String processInsId = variables.getString(QmsBpmConstant.BPM_PROCESS_INS_ID);
        String currentActivityInsId = variables.getString(QmsBpmConstant.BPM_CUR_ACTIVITY_INS_ID);
        String currentActivityId = variables.getString(QmsBpmConstant.BPM_CALLBACK_ACTIVITY_ID);
        String currentActivityName = variables.getString(QmsBpmConstant.BPM_CALLBACK_ACTIVITY_NAME);
        String returnFlag = variables.getString(QmsBpmConstant.BPM_REJECT_TO_FIRST_FLAG); //退回标识。在任务监听中设置
        //同一个节点实例只触发一次
        String checkKey = currentActivityInsId;
        if(ObjectUtils.isEmpty(currentActivityInsId))
            checkKey = processInsId + "-create";
        if("1".equals(returnFlag))
            checkKey += "-reject";
        try{
            dataKeyCheckService.create(checkKey, this.getClass().getName());
        }catch (Exception e){
//            e.printStackTrace();
            log.error("checkKey 重复：key={}", checkKey);
            return CommonResult.success(new JSONObject());
        }
        //流程状态  1-提交（含退回）  4-取消流程
        String PROCESS_STATUS = variables.getString(QmsBpmConstant.PROCESS_INSTANCE_VARIABLE_STATUS);
        String mainId = variables.getString("mainId");
        JSONArray fieldExtensions = new JSONArray();
        if(variables.containsKey(QmsBpmConstant.BPM_FIELD_EXTENSIONS)){
            fieldExtensions = variables.getJSONArray(QmsBpmConstant.BPM_FIELD_EXTENSIONS);
        }
        DevicePeriodCheckDO entity = getDevicePeriodCheck(Long.valueOf(mainId));

        //判断是否最后一个节点
        String lastActivityFlag = "0";
        String firstActivityFlag = "0";
        if(!fieldExtensions.isEmpty()){
            for(int i = 0; i < fieldExtensions.size(); i++){
                JSONObject fieldExtension = fieldExtensions.getJSONObject(i);
                String stringValue = fieldExtension.getString("stringValue");
                if(fieldExtension.getString("fieldName").equalsIgnoreCase(QmsBpmConstant.BPM_LAST_ACTIVITY_FLAG) && "1".equals(stringValue)){
                    lastActivityFlag = "1";
                }
                if(fieldExtension.getString("fieldName").equalsIgnoreCase(QmsBpmConstant.BPM_FIRST_ACTIVITY_FLAG) && "1".equals(stringValue)){
                    firstActivityFlag = "1";
                }
            }
        }
        //"RETURN_FLAG_Activity_001": true 标识驳回到发起环节
        if(("1").equals(returnFlag)){
            //驳回。流程需要配置退回到发起节点
            entity.setFlowStatus(QmsCommonConstant.REJECTED);
            dataOpinionService.disableOpinionsByBusId(entity.getId());
        }else if("4".equals(PROCESS_STATUS)){
            //作废
            entity.setFlowStatus(QmsCommonConstant.VOID);
        }else if("1".equals(PROCESS_STATUS)){
            //通过
//            assembleSignature(currentActivityId, entity);
            DataCommonType dataCommonType = new DataCommonType();
            dataCommonType.setBusinessId(entity.getId());
            dataCommonType.setFlowInstanceId(entity.getFlowInstanceId());
            dataOpinionService.saveOpinionByWfCallback(dataCommonType, currentActivityId, currentActivityName, taskVariables);
            if("1".equals(firstActivityFlag))
                entity.setFlowStatus(QmsCommonConstant.IN_PROGRESS);    //驳回后重新提交
            if("1".equals(lastActivityFlag)){
                entity.setFlowStatus(QmsCommonConstant.COMPLETED);      //结束审批
            }
        }
        devicePeriodCheckMapper.updateById(entity);
        JSONObject ret = new JSONObject();
        return CommonResult.success(ret);
    }

    @Override
    public DevicePeriodCheckVO getLastDataMaterial(JSONObject param) {
        return devicePeriodCheckMapper.getLastDataMaterial(param);
    }

    @Override
    public DevicePeriodCheckVO getLastDataDevice(JSONObject param) {
        return devicePeriodCheckMapper.getLastDataDevice(param);
    }
}