package com.xy.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yitter.idgen.YitIdHelper;
import com.xy.collections.list.JArrayList;
import com.xy.collections.list.JList;
import com.xy.device.EnumDeviceActiveStatus;
import com.xy.device.EnumDeviceAlgorithmChargingType;
import com.xy.device.EnumDeviceBusyStatus;
import com.xy.dto.DeviceAdminActivateDto;
import com.xy.dto.UserInfoDto;
import com.xy.dto.be.MercDto;
import com.xy.entity.DeviceAdminActivate;
import com.xy.entity.DeviceAlgorithmCharging;
import com.xy.entity.DeviceCharging;
import com.xy.entity.DeviceInfo;
import com.xy.error.CommRuntimeException;
import com.xy.mapper.DeviceAdminActivateMapper;
import com.xy.service.be.MercService;
import com.xy.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static com.xy.utils.PlusBeans.toIPage;
import static com.xy.utils.PlusBeans.toPageBean;


/**
 * <p>
 * 管理员设备激活记录表 服务实现类
 * </p>
 *
 * @author lijin
 * @since 2023-11-17
 */
@Service
@AllArgsConstructor
@Api(tags = "管理员设备激活记录表")
public class DeviceAdminActivateServiceImpl extends ServiceImpl<DeviceAdminActivateMapper, DeviceAdminActivate> implements DeviceAdminActivateService {

    private DeviceInfoServiceImpl deviceInfoService;

    private DeviceChargingServiceImpl deviceChargingService;

    private DeviceAlgorithmChargingServiceImpl deviceAlgorithmChargingService;

    private MercService mercService;

    private UserInfoService userInfoService;

    @PostMapping("active")
    @ApiOperation("激活设备")
    public R active(@RequestBody @Validated DeviceAdminActivateDto.Active active) {
        List<Long> deviceIds = active.getDeviceId();
        List<DeviceInfo> list = deviceInfoService.list(new LambdaQueryWrapper<DeviceInfo>()
                .in(DeviceInfo::getDeviceId, deviceIds)
        );
        JList<DeviceInfo> deviceInfos = new JArrayList<>(list);
        LocalDateTime now = LocalDateTime.now();
        Integer activeState = SysDictUtils.getValue(EnumDeviceActiveStatus.Code.CODE.getCode(), EnumDeviceActiveStatus.N_1.getCode(), Integer.class);
        Integer busyState = SysDictUtils.getValue(EnumDeviceBusyStatus.Code.CODE.getCode(), EnumDeviceBusyStatus.N_1.getCode(), Integer.class);
        Integer type = SysDictUtils.getValue(EnumDeviceAlgorithmChargingType.Code.CODE.getCode(), EnumDeviceAlgorithmChargingType.N_2.getCode(), Integer.class);
        LocalDateTime timeout = DataTime.toLocal(DataTime.getStringAround(0, 0, active.getDeviceChargingDay(), 0, 0, 0));
        Integer beginTime = Integer.valueOf(DataTime.getSring("yyyyMMdd"));
        List<DeviceAdminActivate> deviceAdminActivates = new ArrayList<>(deviceInfos.size());
        List<DeviceCharging> deviceChargings = new ArrayList<>(deviceInfos.size());
        List<DeviceAlgorithmCharging> deviceAlgorithmChargings = new ArrayList<>(deviceInfos.size());
        deviceInfos.forEach(deviceInfo -> {
            if (deviceInfo.getActiveState() == 1) {
                throw new CommRuntimeException(deviceInfo.getDeviceId() + "已经激活,操作失败");
            }
            //激活对象
            deviceInfo.setActiveState(activeState)
                    .setBusyState(busyState)
                    .setActiveTime(now)
                    .setShowStatus(true);
            //记录
            DeviceAdminActivate deviceAdminActivate = new DeviceAdminActivate()
                    .setId(YitIdHelper.nextId())
                    .setDeviceId(deviceInfo.getDeviceId())
                    .setDeviceType(deviceInfo.getDeviceType())
                    .setMercId(deviceInfo.getMercId())
                    .setCreateTime(now)
                    .setBatchNo(active.getBatchNo())
                    .setNote(active.getNote())
                    .setFilePath(active.getFilePath())
                    .setCreateUser(AuthorizeUtils.getLoginId(Long.class));
            deviceAdminActivates.add(deviceAdminActivate);
            //设备管理费
            DeviceCharging deviceCharging = new DeviceCharging()
                    .setDeviceId(deviceInfo.getDeviceId())
                    .setChargingSumMoney(0)
                    .setTimeout(timeout)
                    .setCreateTime(now);
            deviceChargings.add(deviceCharging);
            //卡包
            DeviceAlgorithmCharging deviceAlgorithmCharging = new DeviceAlgorithmCharging()
                    .setId(YitIdHelper.nextId())
                    .setMercId(deviceInfo.getMercId())
                    .setDeviceId(deviceInfo.getDeviceId())
                    .setAlgorithmId(active.getAlgorithmId())
                    .setName("手动激活")
                    .setMakeSize(0)
                    .setUnusedSize(active.getDeviceAlgorithmChargingSize())
                    .setType(type)
                    .setTimeout(-1)
                    .setBeginTime(beginTime)
                    .setCreateTime(now)
                    .setUpdateTime(now);
            deviceAlgorithmChargings.add(deviceAlgorithmCharging);
        });
        //激活
        deviceInfoService.updateBatchById(deviceInfos);
        //添加记录
        saveBatch(deviceAdminActivates);
        //设备管理费
        deviceChargingService.saveOrUpdateBatch(deviceChargings);
        //卡包
        deviceAlgorithmChargingService.saveBatch(deviceAlgorithmChargings);
        return R.ok();
    }

    @PostMapping("page")
    @ApiOperation("分页查询")
    public R<PageBean<DeviceAdminActivateDto.Vo>> page(@RequestBody DeviceAdminActivateDto.Page page) {
        PageBean pageBean = page.getPage();
        LambdaQueryWrapper<DeviceAdminActivate> lambdaQueryWrapper = new MybatisPlusQuery().eqWrapper(page, DeviceAdminActivate.class)
                .like(DeviceAdminActivate::getNote)
                .build();
        IPage<DeviceAdminActivate> iPage = page(toIPage(pageBean), lambdaQueryWrapper);
        PageBean<DeviceAdminActivateDto.Vo> voPageBean = toPageBean(DeviceAdminActivateDto.Vo.class, iPage);
        List<DeviceAdminActivateDto.Vo> records = voPageBean.getRecords();
        //翻译数据
        JList<DeviceAdminActivateDto.Vo> vos = new JArrayList<>(records);
        Beans.copy(records)
                .target(() -> mercService.list(new MercDto.SelectList().setMercIds(vos.getProperty(DeviceAdminActivateDto.Vo::getMercId).comparing())).getData(), DeviceAdminActivateDto.Vo::getMercId, DeviceAdminActivateDto.Vo::getMercName, MercDto.Vo::getId, MercDto.Vo::getName)
                .target(() -> userInfoService.list(new UserInfoDto.SelectListDto().setUserIds(vos.getProperty(DeviceAdminActivateDto.Vo::getCreateUser))).getData(), DeviceAdminActivateDto.Vo::getCreateUser, DeviceAdminActivateDto.Vo::getCreateUserName, UserInfoDto.Vo::getUserId, UserInfoDto.Vo::getName)
                .builder();
        return R.ok(voPageBean);
    }

}