package com.fuint.common.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
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.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fuint.common.dto.AccountInfo;
import com.fuint.common.dto.VersionDto;
import com.fuint.common.util.AuthUserUtil;
import com.fuint.common.vo.IngredientVo;
import com.fuint.common.vo.VersionVo;
import com.fuint.framework.annoation.OperationServiceLog;
import com.fuint.framework.exception.BusinessCheckException;
import com.fuint.framework.pagination.PaginationRequest;
import com.fuint.framework.pagination.PaginationResponse;
import com.fuint.framework.web.PageResult;
import com.fuint.repository.model.MtIngredient;
import com.fuint.repository.model.MtVersion;
import com.fuint.common.service.VersionService;
import com.fuint.common.enums.StatusEnum;
import com.fuint.repository.mapper.MtVersionMapper;
import com.github.pagehelper.PageHelper;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;

/**
 * 版本控制表服务接口
 *
 * Created by pzg
 * CopyRight https://www.fuint.cn
 */
@Service
@AllArgsConstructor
public class VersionServiceImpl extends ServiceImpl<MtVersionMapper, MtVersion> implements VersionService {

    private static final Logger logger = LoggerFactory.getLogger(VersionServiceImpl.class);

    private MtVersionMapper mtVersionMapper;

    /**
     * 分页查询数据列表
     *
     * @param versionDto
     * @return
     */
    @Override
    public PageResult<VersionVo> queryVersionPageList(VersionDto versionDto) {
        AccountInfo accountInfo = AuthUserUtil.get();
        Assert.isTrue(ObjectUtils.isNotEmpty(accountInfo), "请登录");


        IPage page = new Page(versionDto.getPageNo(), versionDto.getPageSize());
        IPage iPage = mtVersionMapper.selectPage(page, new LambdaQueryWrapper<MtVersion>());
        List<VersionVo> versionVos = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(iPage.getRecords())){
            versionVos = BeanUtil.copyToList(iPage.getRecords(), VersionVo.class);
        }
        return PageResult.<VersionVo>builder().data(versionVos).currentPage((int) iPage.getCurrent()).total((int) iPage.getTotal()).build();
    }

    /**
     * 添加版本控制表
     *
     * @param versionDto 版本控制表信息
     * @return
     */
    @OperationServiceLog(description = "新增版本控制表")
    @Override
    @Transactional(rollbackFor = Exception.class)
    public VersionVo addVersion(VersionDto versionDto) {

        AccountInfo accountInfo = AuthUserUtil.get();
        Assert.isTrue(ObjectUtils.isNotEmpty(accountInfo), "请登录");

        Assert.isTrue(ObjectUtils.isNotEmpty(versionDto), "参数不能为空");
        List<MtVersion> mtVersions = mtVersionMapper.selectList(new LambdaQueryWrapper<MtVersion>()
                .eq(MtVersion::getName, versionDto.getName()));
        Assert.isTrue(ObjectUtils.isEmpty(mtVersions), "版本名称已存在");
        MtVersion mtVersion = BeanUtil.copyProperties(versionDto, MtVersion.class);
//        mtVersion.setCreateTime(new Date());
//        mtVersion.setCreateUserId(String.valueOf(accountInfo.getId()));

        int insert = mtVersionMapper.insert(mtVersion);
        Assert.isFalse(insert!=1, "添加失败");

        return BeanUtil.copyProperties(mtVersion, VersionVo.class);
    }

    /**
     * 根据ID获版本控制表取息
     *
     * @param id 版本控制表ID
     * @return
     */
    @Override
    public VersionVo queryVersionById(Long id) {

        AccountInfo accountInfo = AuthUserUtil.get();
        Assert.isTrue(ObjectUtils.isNotEmpty(accountInfo), "请登录");

        Assert.isTrue(ObjectUtils.isNotEmpty(id), "请选择版本");
        MtVersion mtVersion = mtVersionMapper.selectById(id);
        if (ObjectUtils.isNotEmpty(mtVersion)){
            VersionVo versionVo = BeanUtil.copyProperties(mtVersion, VersionVo.class);
            return versionVo;
        }
        return null;
    }


    /**
     * 根据ID删除版本控制表
     *
     * @param id 版本控制表ID
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @OperationServiceLog(description = "删除版本控制表")
    public void deleteVersionById(Long id) {
        AccountInfo accountInfo = AuthUserUtil.get();
        Assert.isTrue(ObjectUtils.isNotEmpty(accountInfo), "请登录");

        Assert.isTrue(ObjectUtils.isNotEmpty(id), "请选择版本");

        MtVersion mtVersion = mtVersionMapper.selectById(id);
        Assert.isTrue(ObjectUtils.isNotEmpty(mtVersion), "版本不存在");

        int delete = mtVersionMapper.deleteById(id);
        Assert.isFalse(delete!=1, "删除失败");
    }


    /**
     * 修改版本控制表数据
     *
     * @param versionDto
     * @throws BusinessCheckException
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @OperationServiceLog(description = "更新版本控制表")
    public VersionVo updateVersion(VersionDto versionDto) {

        AccountInfo accountInfo = AuthUserUtil.get();
        Assert.isTrue(ObjectUtils.isNotEmpty(accountInfo), "请登录");

        Assert.isTrue(ObjectUtils.isNotEmpty(versionDto), "参数不能为空");
        Assert.isTrue(ObjectUtils.isNotEmpty(versionDto.getId()), "请选择版本");

        MtVersion mtVersion = mtVersionMapper.selectById(versionDto.getId());
        Assert.isTrue(ObjectUtils.isNotEmpty(mtVersion), "版本不存在");

        Assert.isTrue(ObjectUtils.isNotEmpty(versionDto.getName()), "版本名称不能为空");

        List<MtVersion> mtVersions = mtVersionMapper.selectList(new LambdaQueryWrapper<MtVersion>()
                .eq(MtVersion::getName, versionDto.getName()));
        Assert.isTrue(ObjectUtils.isEmpty(mtVersions), "版本名称已存在");

        Assert.isTrue(mtVersion.getName().equals(versionDto.getName()), "不能修改版本名");

        Assert.isTrue(ObjectUtils.isNotEmpty(versionDto.getStatus()), "请选择状态");

        //只存在一个当前版本
        if (versionDto.getStatus() == 1 && mtVersion.getStatus() != 1){
            mtVersionMapper.update(MtVersion.builder().status(0).build(), new LambdaUpdateWrapper<MtVersion>().eq(MtVersion::getStatus, 1));
        }

//        versionDto.setUpdateTime(new Date());
//        versionDto.setUpdateUserId(String.valueOf(accountInfo.getId()));

        int i = mtVersionMapper.updateById(BeanUtil.copyProperties(versionDto, MtVersion.class));
        Assert.isFalse(i!=1, "更新失败");

        return BeanUtil.copyProperties(mtVersion, VersionVo.class);
    }

}
