/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.depotTruckLade.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.modular.login.service.AuthService;
import vip.xiaonuo.biz.api.cloud.param.DepotCloudAlarmAddParam;
import vip.xiaonuo.biz.api.cloud.service.CloudService;
import vip.xiaonuo.biz.core.Const.BizStr;
import vip.xiaonuo.biz.core.exception.BizExceptionEnum;
import vip.xiaonuo.biz.modular.depotGrain.service.DepotGrainService;
import vip.xiaonuo.biz.modular.depotTruckBook.service.DepotTruckBookService;
import vip.xiaonuo.biz.modular.depotTruckLade.param.*;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.biz.modular.depotTruckLade.entity.DepotTruckLade;
import vip.xiaonuo.biz.modular.depotTruckLade.mapper.DepotTruckLadeMapper;
import vip.xiaonuo.common.prop.CommonProperties;
import vip.xiaonuo.common.util.DatesUtil;
import vip.xiaonuo.dev.api.DevFileApi;
import vip.xiaonuo.dev.modular.file.util.MultipartFileUtils;
import vip.xiaonuo.sys.modular.user.entity.SysUser;
import vip.xiaonuo.sys.modular.user.service.SysUserService;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * 车辆装卸货管理表Service接口实现类
 *
 * @author xiang
 * @date 2023/10/16 14:18
 **/
@Service
public class DepotTruckLadeService extends ServiceImpl<DepotTruckLadeMapper, DepotTruckLade> {

    @Resource
    DevFileApi devFileApi;
    @Resource
    DepotGrainService depotGrainService;
    @Resource
    DepotTruckBookService truckBookService;
    @Resource
    CommonProperties commonProperties;
    @Resource
    private CloudService cloudService;
    @Resource
    AuthService authService;

    public Page<DepotTruckLade> page(DepotTruckLadePageParam param) {
        QueryWrapper<DepotTruckLade> wrapper = new QueryWrapper<>();
        wrapper.and(Strings.isNotEmpty(param.getSearchKey()), w ->
                w.lambda().like(DepotTruckLade::getLicensePlate, param.getSearchKey())
                        .or().like(DepotTruckLade::getLicensePlateBack, param.getSearchKey())
                        .or().like(DepotTruckLade::getDriverName, param.getSearchKey()));
        List<String> depotIdLst = depotGrainService.lstOrgGrep();
        wrapper.lambda().in(CollUtil.isNotEmpty(depotIdLst), DepotTruckLade::getDepotId, depotIdLst);
        if (ObjectUtil.isNotEmpty(param.getDepotId())) {
            wrapper.lambda().eq(DepotTruckLade::getDepotId, param.getDepotId());
        }
        if (ObjectUtil.isNotEmpty(param.getTruckBookId())) {
            wrapper.lambda().like(DepotTruckLade::getTruckBookId, param.getTruckBookId());
        }
        if (ObjectUtil.isNotEmpty(param.getLicensePlate())) {
            wrapper.lambda().like(DepotTruckLade::getLicensePlate, param.getLicensePlate());
        }
        if (ObjectUtil.isNotEmpty(param.getDriverName())) {
            wrapper.lambda().like(DepotTruckLade::getDriverName, param.getDriverName());
        }
        if (ObjectUtil.isNotEmpty(param.getShedName())) {
            wrapper.lambda().like(DepotTruckLade::getShedName, param.getShedName());
        }
        if (ObjectUtil.isAllNotEmpty(param.getSortField(), param.getSortOrder())) {
            CommonSortOrderEnum.validate(param.getSortOrder());
            wrapper.orderBy(true, param.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(param.getSortField()));
        } else {
            wrapper.lambda().orderByDesc(DepotTruckLade::getId);
        }
        Page page = this.page(CommonPageRequest.defaultPage(), wrapper);
        //匹配粮库名称
        depotGrainService.putDepotName(page.getRecords());
        //匹配图片
        putPicUrl(page.getRecords());
        return page;
    }

    public DepotTruckLade getOneByBookId(String bookId) {
        return getOne(new LambdaQueryWrapper<>(new DepotTruckLade(bookId)));
    }

    /**
     * 添加车辆装卸货一次照片
     *
     * @author xiang
     * @date 2023/10/16 11:40
     */
    public void addOnePic(DepotTruckLadeAddPicParam param) {
        DepotTruckLade one = getById(param.getId());
        //车辆状态校验
        truckBookService.check_state(one.getTruckBookId(), BizStr.FLOW_GUO_BANG_ONE, BizStr.STATE_TRUCK_Y);
        //超时
        if (Strings.isNotEmpty(one.getLimitInTime()) && DatesUtil.overTimeFlag(DatesUtil.forDateTime(one.getLimitInTime()))) {
            cloudService.depotWorkAlarmAdd(new DepotCloudAlarmAddParam(one.getTruckBookId(), "21", String.format("完成一次过磅到达卸货区拍照上传校验超时，规定时间：%s，校验时间：%s", one.getLimitInTime(), DatesUtil.forDateTime())));
            throw new CommonException(BizExceptionEnum.ERROR13005.getMessage());
        }
        one.setShedName(param.getShedName());
        //处理图片
        if (Strings.isBlank(param.getOnePicUrl()) && Strings.isBlank(param.getFile()))
            throw new CommonException(String.format("请添加装卸货前的照片。车牌:%s;预约号:%s", one.getLicensePlate(), one.getTruckBookId()));
        else if (Strings.isNotBlank(param.getOnePicUrl()) && param.getOnePicUrl().length() == 19)
            one.setOnePicUrl(devFileApi.storageFilePathReturnUrlById(param.getOnePicUrl()));
        else if (Strings.isNotBlank(param.getFile()))
            one.setOnePicUrl(devFileApi.storageFilePathReturnUrl(MultipartFileUtils.base64ToMultipart(param.getFile())));
        one.setOnePicTime(DatesUtil.forDateTime());
        one.setUnloadBeforeState(BizStr.STATE_PROCESS_E);
        one.setOnePicUser(authService.getLoginUser().getId());
        this.updateById(one);
    }

    /**
     * 添加车辆装卸货二次照片
     *
     * @author xiang
     * @date 2023/10/16 11:40
     */
    public void addTwoPic(DepotTruckLadeAddPicParam param) {
        DepotTruckLade one = getById(param.getId());
        //车辆状态校验
        truckBookService.check_state(one.getTruckBookId(), BizStr.FLOW_GUO_BANG_ONE, BizStr.STATE_TRUCK_Y);
        //处理图片
        if (!BizStr.STATE_PROCESS_E.equals(one.getUnloadBeforeState()))
            throw new CommonException(String.format("请先添加装卸货前的照片。车牌:%s;预约号:%s", one.getLicensePlate(), one.getTruckBookId()));
        else if (Strings.isBlank(param.getTwoPicUrl()) && Strings.isBlank(param.getFile()))
            throw new CommonException(String.format("请添加装卸货后的照片。车牌:%s;预约号:%s", one.getLicensePlate(), one.getTruckBookId()));
        else if (Strings.isNotBlank(param.getTwoPicUrl()) && param.getTwoPicUrl().length() == 19)
            one.setTwoPicUrl(devFileApi.storageFilePathReturnUrlById(param.getTwoPicUrl()));
        else if (Strings.isNotBlank(param.getFile()))
            one.setTwoPicUrl(devFileApi.storageFilePathReturnUrl(MultipartFileUtils.base64ToMultipart(param.getFile())));
        one.setTwoPicTime(DatesUtil.forDateTime());
        one.setUnloadAfterState(BizStr.STATE_PROCESS_E);
        one.setTwoPicUser(authService.getLoginUser().getId());
        this.updateById(one);
        //车辆进程更新
        truckBookService.upTruckBookFlow(one.getTruckBookId(), BizStr.FLOW_LADE_FINISH, one.getTwoPicTime());
    }

    public void add(DepotTruckLadeAddParam depotTruckLadeAddParam) {
        DepotTruckLade depotTruckLade = BeanUtil.toBean(depotTruckLadeAddParam, DepotTruckLade.class);
        this.save(depotTruckLade);
    }

    public void editLimitInTimeByBookId(String bookId, BigDecimal grossWeight, String grossTime, String limitInTime) {
        this.update(new LambdaUpdateWrapper<>(new DepotTruckLade(bookId))
                .set(DepotTruckLade::getLimitInTime, limitInTime)
                .set(grossWeight != null, DepotTruckLade::getGrossWeight, grossWeight)
                .set(Strings.isNotBlank(grossTime), DepotTruckLade::getGrossTime, grossTime));
    }

    public void edit(DepotTruckLadeEditParam depotTruckLadeEditParam) {
        DepotTruckLade depotTruckLade = this.queryEntity(depotTruckLadeEditParam.getId());
        BeanUtil.copyProperties(depotTruckLadeEditParam, depotTruckLade);
        this.updateById(depotTruckLade);
    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(List<DepotTruckLadeIdParam> depotTruckLadeIdParamList) {
        // 执行删除
        this.removeBatchByIds(CollStreamUtil.toList(depotTruckLadeIdParamList, DepotTruckLadeIdParam::getId));
    }

    @Resource
    SysUserService sysUserService;

    public DepotTruckLade detail(DepotTruckLade param) {
        DepotTruckLade one = null;
        if (Strings.isNotEmpty(param.getId()))
            one = this.queryEntity(param.getId());
        if (one == null && Strings.isNotEmpty(param.getTruckBookId()))
            one = this.getOneByBookId(param.getTruckBookId());
        if (one != null) {
            one.setDepotGrainName(depotGrainService.getNameByDepotId(one.getDepotId()));
            putPicUrl(one);
            //人员账号
            SysUser sysUser = sysUserService.getOneById(one.getOnePicUser());
            if (sysUser != null) {
                one.setOnePicUserName(sysUser.getName());
                one.setOnePicUserAccount(sysUser.getAccount());
            }
            sysUser = sysUserService.getOneById(one.getTwoPicUser());
            if (sysUser != null) {
                one.setTwoPicUserName(sysUser.getName());
                one.setTwoPicUserAccount(sysUser.getAccount());
            }
        }
        return one == null ? new DepotTruckLade() : one;
    }

    public DepotTruckLade detail(DepotTruckLadeIdParam depotTruckLadeIdParam) {
        DepotTruckLade one = this.queryEntity(depotTruckLadeIdParam.getId());
        one.setDepotGrainName(depotGrainService.getNameByDepotId(one.getDepotId()));
        putPicUrl(one);
        return this.queryEntity(depotTruckLadeIdParam.getId());
    }

    public DepotTruckLade queryEntity(String id) {
        DepotTruckLade depotTruckLade = this.getById(id);
        if (ObjectUtil.isEmpty(depotTruckLade)) {
            throw new CommonException("车辆装卸货管理表不存在，id值为：{}", id);
        }
        return depotTruckLade;
    }

    /**
     * 匹配完整图片地址
     *
     * @author xiang
     * @date 2023/09/27 19:31
     **/
    public void putPicUrl(DepotTruckLade one) {
        if (Strings.isNotEmpty(one.getOnePicUrl()))
            one.setOnePicUrl(commonProperties.getBackendUrl() + one.getOnePicUrl());
        if (Strings.isNotEmpty(one.getTwoPicUrl()))
            one.setTwoPicUrl(commonProperties.getBackendUrl() + one.getTwoPicUrl());
    }

    /**
     * 匹配完整图片地址
     *
     * @author xiang
     * @date 2023/09/27 19:31
     **/
    public void putPicUrl(List<DepotTruckLade> list) {
        list.forEach(one -> {
            putPicUrl(one);
        });
    }

}
