package cn.wise.sc.acquisition.business.service.impl;

import cn.wise.sc.acquisition.business.constant.Rcode;
import cn.wise.sc.acquisition.business.entity.TSampleList;
import cn.wise.sc.acquisition.business.enumation.ProjectEnum;
import cn.wise.sc.acquisition.business.mapper.TSampleListMapper;
import cn.wise.sc.acquisition.business.model.query.TSampleListQuery;
import cn.wise.sc.acquisition.business.service.ITSampleListService;
import cn.wise.sc.acquisition.business.util.ImageUtil;
import cn.wise.sc.acquisition.business.wrapper.page.Query;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.Optional;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author renchao
 * @since 2021-04-22
 */
@Service
@Slf4j
public class TSampleListServiceImpl extends ServiceImpl<TSampleListMapper, TSampleList> implements ITSampleListService {

    @Override
    public R getPage(TSampleListQuery tSampleListQuery, Query query) {
        log.info(JSON.toJSONString(tSampleListQuery));
        //参数校验
        //分页
        Page<TSampleList> page = new Page<>(query.getPageNum(), query.getPageSize());
        //条件封装 因为图片字节太长，排除QR_CODE,RECORD_CODE
        QueryWrapper<TSampleList> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(
                ProjectEnum.TSampleListType.HOLES_ID.getLabel(),
                ProjectEnum.TSampleListType.START.getLabel(),
                ProjectEnum.TSampleListType.END_TO.getLabel(),
                ProjectEnum.TSampleListType.YH.getLabel(),
                ProjectEnum.TSampleListType.SYR.getLabel(),
                ProjectEnum.TSampleListType.SYRQ.getLabel()
        );
        queryWrapper
                .like(StringUtils.isNotBlank(tSampleListQuery.getSearch()), ProjectEnum.TSampleListType.YH.getLabel(), tSampleListQuery.getSearch())
                .or()
                .like(StringUtils.isNotBlank(tSampleListQuery.getSearch()), ProjectEnum.TSampleListType.HOLES_ID.getLabel(), tSampleListQuery.getSearch());
        //查询
        Page<TSampleList> tSampleListPage = baseMapper.selectPage(page, queryWrapper);
        return R.ok(tSampleListPage);
    }


    @Override
    @Transactional
    public R getByYh(TSampleListQuery query) {
        log.info(JSON.toJSONString(query));
        //参数校验
        Rcode.NOT_PARAM.assertNotNull(query);
        Rcode.NOT_PARAM.assertNotEmpty(query.getYh());
        //查询并且返回
        return R.ok(baseMapper.selectById(query.getYh()));
    }


    @Override
    @Transactional
    public R updateByYh(TSampleListQuery query) {
        log.info(JSON.toJSONString(query));
        //参数校验
        Rcode.NOT_PARAM.assertNotNull(query);
        Rcode.NOT_PARAM.assertNotEmpty(query.getYh());
        //判断数据是否存在
        TSampleList temp = baseMapper.selectById(query.getYh());
        if (temp == null) {
            return R.failed("送样单中->数据不存在，样号：" + query.getYh());
        }
        //条件封装
        TSampleList tSampleList = new TSampleList();
        BeanUtils.copyProperties(query, tSampleList);

        QueryWrapper<TSampleList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ProjectEnum.TSampleListType.YH.getLabel(), query.getYh());
        //修改
        int update = baseMapper.update(tSampleList, queryWrapper);
        if (update > 0) {
            return R.ok("送样单中->修改成功");
        } else {
            log.error("送样单中->修改失败 {}",JSON.toJSONString(tSampleList));
            return R.failed("送样单中->修改失败");
        }

    }


    @Override
    @Transactional
    public R insertSampleList(TSampleListQuery query) {
        log.info(JSON.toJSONString(query));
        //参数校验
        Rcode.NOT_PARAM.assertNotNull(query);
        Rcode.NOT_PARAM.assertNotEmpty(query.getYh());
        //判断数据是否已存在，如果存在不能添加
        TSampleList temp = baseMapper.selectById(query.getYh());
        if (temp != null) {
            return R.failed("送样单中->送验单样号已存在，样号：" + query.getYh());
        }
        //继续判断参数
        Rcode.NOT_PARAM.assertNotEmpty(query.getHolesID());
        Rcode.NOT_PARAM.assertNotEmpty(query.getStart());
        Rcode.NOT_PARAM.assertNotEmpty(query.getEndTo());
        //Rcode.NOT_PARAM.assertNotEmpty(query.getRecordName());
        Rcode.NOT_PARAM.assertNotEmpty(query.getBz());
        Rcode.NOT_PARAM.assertNotEmpty(query.getSyr());
        //条件封装
        TSampleList tSampleList = new TSampleList();
        BeanUtils.copyProperties(query, tSampleList);
        //若时间送样为空，创建当前时间
        Optional<LocalDateTime> ofNullable = Optional.ofNullable(tSampleList.getSyrq());
        if (!ofNullable.isPresent()) {
            tSampleList.setSyrq(LocalDateTime.now());
        }
        //增加
        log.info(JSON.toJSONString(tSampleList));
        int insert = baseMapper.insert(tSampleList);
        if (insert > 0) {
            return R.ok("送样单中->增加成功");
        } else {
            log.error("送样单中->增加失败：{}",JSON.toJSONString(tSampleList));
            return R.failed("送样单中->增加失败");
        }

    }


    @Override
    @Transactional
    public R deleteByYh(TSampleListQuery query) {
        log.info(JSON.toJSONString(query));
        //参数校验
        Rcode.NOT_PARAM.assertNotNull(query);
        Rcode.NOT_PARAM.assertNotEmpty(query.getYh());
        TSampleList temp = baseMapper.selectById(query.getYh());
        if (temp == null) {
            return R.failed("送样单中->数据不存在，样号：" + query.getYh());
        }
        //删除
        int delete = baseMapper.delete(new QueryWrapper<TSampleList>().eq(ProjectEnum.TSampleListType.YH.getLabel(), query.getYh()));
        if (delete > 0) {
            return R.ok("送样单中->删除成功");
        } else {
            return R.failed("送样单中->删除失败");
        }

    }

    @Override
    @Transactional
    public R saveImage(TSampleListQuery query, MultipartFile file) {
        log.info(JSON.toJSONString(query));
        //参加校验
        Rcode.NOT_PARAM.assertNotNull(query);
        Rcode.NOT_PARAM.assertNotEmpty(query.getYh());
        //判断数据是否存在
        TSampleList temp = baseMapper.selectById(query.getYh());
        if (temp == null) {
            return R.failed("送样单中->数据不存在，样号：" + query.getYh());
        }
        Rcode.NOT_PARAM.assertNotNull(file);
        //封装
        TSampleList tSampleList = new TSampleList();
        BeanUtils.copyProperties(query, tSampleList);
        //转化图片
        ImageUtil.setImage(ProjectEnum.ImageType.RECORD_CODE.getValue(), tSampleList, file);
        //保存
        int update = baseMapper.updateById(tSampleList);
        if (update > 0) {
            return R.ok("送样单中->保存成功");
        } else {
            return R.failed("送样单中->保存失败");
        }

    }

    /**
     * 获取图片记录形式
     *
     * @param query
     * @param response
     */
    @Override
    @Transactional
    public R getImage(TSampleListQuery query, final HttpServletResponse response) {
        log.info(JSON.toJSONString(query));
        //参加校验
        Rcode.NOT_PARAM.assertNotNull(query);
        Rcode.NOT_PARAM.assertNotEmpty(query.getYh());
        TSampleList tSampleList = baseMapper.selectById(query.getYh());
        if (tSampleList == null) {
            return R.failed("送样单中->数据不存在，样号：" + query.getYh());
        }
        //获取二维码或者记录形式
        ImageUtil.getImage(ProjectEnum.ImageType.RECORD_CODE.getValue(), tSampleList, response);
        //如果下载失败才会执行return
        return R.failed("送样单中->该条数据没有图片");
    }


}
