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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.qms.common.service.BusinessFileService;
import com.zt.plat.module.qms.resource.device.common.DeviceUtil;
import com.zt.plat.module.qms.resource.device.controller.vo.*;
import com.zt.plat.module.qms.resource.device.dal.dataobject.DeviceConfigBusinessRuleDO;
import com.zt.plat.module.qms.resource.device.dal.dataobject.DeviceMaintainItemDO;
import org.springframework.beans.factory.annotation.Autowired;
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.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import com.zt.plat.module.qms.resource.device.dal.dataobject.DeviceMaintainDO;
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.DeviceMaintainMapper;

import static com.zt.plat.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.zt.plat.framework.common.util.collection.CollectionUtils.convertList;
import static com.zt.plat.module.qms.enums.ErrorCodeConstants.DEVICE_MAINTAIN_NOT_EXISTS;

/**
 * 设备-点检、保养记录 Service 实现类
 *
 * @author 后台管理-1
 */
@Service
@Validated
public class DeviceMaintainServiceImpl implements DeviceMaintainService {

    @Resource private DeviceMaintainMapper deviceMaintainMapper;
    @Resource private DeviceMaintainItemService deviceMaintainItemService;
    @Resource private DeviceProductService deviceProductService;
    @Resource private DeviceInfomationService deviceInfomationService;
    @Autowired private DeviceConfigBusinessRuleService deviceConfigBusinessRuleService;
    @Resource private BusinessFileService businessFileService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<DeviceMaintainDO> saveMaintainVo(DeviceMaintainVO vo) {
        DeviceMaintainDO data = new DeviceMaintainDO();
        BeanUtil.copyProperties(vo, data);
        deviceMaintainMapper.updateById(data);
        List<DeviceMaintainItemDO> maintainItemList = vo.getMaintainItemList();
        deviceMaintainItemService.updateBatch(maintainItemList);
        return CommonResult.success(data);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<DeviceMaintainVO> createOrGet(Long deviceId, String date, String dataType){
        LocalDateTime curDate = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        if(!ObjectUtils.isEmpty(date))
            curDate = LocalDateTime.parse( date + " 00:00:00", formatter);
        String dateStr = curDate.toLocalDate().toString();
        //查询上一个点检记录
        DeviceMaintainDO lastData = getLastData(deviceId, dataType, dateStr).getData();
        if(lastData != null && (lastData.getFrequencyTimeStart() == null || lastData.getFrequencyTimeEnd() == null))
            return getMaintainDetail(lastData.getId());
        if(lastData != null && curDate.compareTo(lastData.getFrequencyTimeStart()) >=0 && curDate.compareTo(lastData.getFrequencyTimeEnd()) <=0 ){
            return getMaintainDetail(lastData.getId());
        }
        LocalDateTime lastDate = null;
        if(lastData != null)
            lastDate = lastData.getFrequencyTimeEnd();

        //比较lastDate与curDate
        if(lastDate != null ){
            if(lastDate.isBefore(curDate))
                lastDate = curDate;
        }
        return  create(deviceId, lastDate, dataType);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<DeviceMaintainVO> create(Long deviceId, LocalDateTime lastDate, String dataType) {
        //当前登录人
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        //当前登录用户昵称
        String nickName = SecurityFrameworkUtils.getLoginUserNickname();
        //获取配置
        CommonResult<DeviceConfigBusinessRuleDO> ruleRet = deviceConfigBusinessRuleService.getRuleByDeviceIdAndType(deviceId, dataType);
        if(!ruleRet.isSuccess())
            return CommonResult.error(ruleRet.getCode(), ruleRet.getMsg());
        DeviceConfigBusinessRuleDO rule = ruleRet.getData();
        //根据周期判断当前日期是否存在数据
        LocalDateTime[] dateRange = null;
        if(lastDate != null){
            dateRange = DeviceUtil.getDateRangeByFrequency(lastDate, false, rule.getFrequencyType(), rule.getFrequency());
        }
        DeviceMaintainDO data = new DeviceMaintainDO();
        data.setDeviceId(deviceId);
        data.setDataType(dataType);
        data.setCheckDate(LocalDateTime.now());
        data.setRuleId(rule.getId());
        data.setCheckUserId(loginUser.getId());
        data.setCheckUserName(nickName);
        data.setFrequencyType(rule.getFrequencyType());
        data.setFrequency(rule.getFrequency());
        data.setFrequencyRemark(rule.getFrequencyRemark());
        if(dateRange != null){
            data.setFrequencyTimeStart(dateRange[0]);
            data.setFrequencyTimeEnd(dateRange[1]);
        }
        deviceMaintainMapper.insert(data);

        //创建明细项
        deviceMaintainItemService.createItems(data, rule.getId());

        return getMaintainDetail(data.getId());
    }

    @Override
    public CommonResult<DeviceMaintainVO> getMaintainDetail(Long id) {
        DeviceMaintainDO entity = deviceMaintainMapper.selectById( id);
        if(entity == null)
            throw exception(DEVICE_MAINTAIN_NOT_EXISTS);
        DeviceMaintainVO vo = new DeviceMaintainVO();
        BeanUtils.copyProperties(entity, vo);
        List<DeviceMaintainItemDO> itemList = deviceMaintainItemService.getListByParId( id);
        vo.setMaintainItemList(itemList);
        vo.setBusinessFileRet(businessFileService.getBusinessFileList(id));
        return CommonResult.success( vo);
    }

    @Override
    public CommonResult<DeviceMaintainDO> getLastData(Long deviceId, String dataType, String date) {
        LambdaQueryWrapper<DeviceMaintainDO> query = new LambdaQueryWrapper<>();
        query.eq(DeviceMaintainDO::getDeviceId, deviceId);
        query.eq(DeviceMaintainDO::getDataType, dataType);
        if(!ObjectUtils.isEmpty(date)){
            query.ge(DeviceMaintainDO::getCheckDate, date);
            query.le(DeviceMaintainDO::getCheckDate, date + " 23:59:59");
        }
        query.orderByDesc(DeviceMaintainDO::getCheckDate);
        query.last("limit 1");
        DeviceMaintainDO maintainDO = deviceMaintainMapper.selectOne(query);
        return CommonResult.success(maintainDO);
    }

    @Override
    public PageResult<DeviceInfomationMaintainVO> queryPageListWithCount(DeviceMaintainPageReqVO reqVO) {
        Long productId = reqVO.getProductId();
        if(productId != null){
            List<Long> productIds = deviceProductService.getIdListByIdPath(productId);
            List<Long> deviceIds = deviceInfomationService.getIdListByProductIdList(productIds);
            if(!deviceIds.isEmpty()){
                reqVO.setProductId(null);
                reqVO.setDeviceIdList(deviceIds);
            }
        }
        Page<DeviceInfomationMaintainVO> page = new Page<>(reqVO.getPageNo(), reqVO.getPageSize());

        IPage<DeviceInfomationMaintainVO> pageList = deviceMaintainMapper.queryPageListWithCount(page, reqVO);
        return new PageResult<>(pageList.getRecords(), pageList.getTotal());
    }

    @Override
    public DeviceMaintainRespVO createDeviceMaintain(DeviceMaintainSaveReqVO createReqVO) {
        // 插入
        DeviceMaintainDO deviceMaintain = BeanUtils.toBean(createReqVO, DeviceMaintainDO.class);
        deviceMaintainMapper.insert(deviceMaintain);
        // 返回
        return BeanUtils.toBean(deviceMaintain, DeviceMaintainRespVO.class);
    }

    @Override
    public void updateDeviceMaintain(DeviceMaintainSaveReqVO updateReqVO) {
        // 校验存在
        validateDeviceMaintainExists(updateReqVO.getId());
        // 更新
        DeviceMaintainDO updateObj = BeanUtils.toBean(updateReqVO, DeviceMaintainDO.class);
        deviceMaintainMapper.updateById(updateObj);
    }

    @Override
    public void deleteDeviceMaintain(Long id) {
        // 校验存在
        validateDeviceMaintainExists(id);
        // 删除
        deviceMaintainMapper.deleteById(id);
    }

    @Override
        public void deleteDeviceMaintainListByIds(List<Long> ids) {
        // 校验存在
        validateDeviceMaintainExists(ids);
        // 删除
        deviceMaintainMapper.deleteByIds(ids);
        }

    private void validateDeviceMaintainExists(List<Long> ids) {
        List<DeviceMaintainDO> list = deviceMaintainMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(DEVICE_MAINTAIN_NOT_EXISTS);
        }
    }

    private void validateDeviceMaintainExists(Long id) {
        if (deviceMaintainMapper.selectById(id) == null) {
            throw exception(DEVICE_MAINTAIN_NOT_EXISTS);
        }
    }

    @Override
    public DeviceMaintainDO getDeviceMaintain(Long id) {
        return deviceMaintainMapper.selectById(id);
    }

    @Override
    public PageResult<DeviceMaintainDO> getDeviceMaintainPage(DeviceMaintainPageReqVO pageReqVO) {
        return deviceMaintainMapper.selectPage(pageReqVO);
    }

}