package com.ho.flow.service.impl;

import cn.hutool.core.codec.Base64;
import com.ho.common.tools.constant.CommonConstant;
import com.ho.common.tools.entity.WorkOrderPicture;
import com.ho.common.tools.exception.BaseResponseCode;
import com.ho.common.tools.exception.BusinessException;
import com.ho.common.tools.util.CommonBytesUtil;
import com.ho.flow.mapper.WorkOrderPictureMapper;
import com.ho.flow.service.WorkOrderPictureService;
import com.ho.flow.vo.req.workorder.WorkOrderAddReqVO;
import com.ho.flow.vo.req.workorder.WorkOrderUpdateReqVO;
import com.ho.flow.vo.resp.workorder.PictureRespVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description 工单图片
 * Author yule
 * Date 2023/2/4 14:24
 */
@Service
@Slf4j
public class WorkOrderPictureServiceImpl implements WorkOrderPictureService {

    @Autowired
    WorkOrderPictureMapper pictureMapper;

    @Autowired
    CommonBytesUtil bytesUtil;


    @Value("${flow.maxPicUploadNum}")
    Integer maxPicUploadNum;


    @Override
    public WorkOrderPicture insertPicture(String url) {
        //创建文件对象
        File file = new File(url);
        //把图片的地址转化为图片的实体类对象
        WorkOrderPicture picture = new WorkOrderPicture();
        picture.setUrl(url);
        picture.setCreateTime(new Date());
        picture.setFileName(file.getName());
        //将实体对象入库存储
        pictureMapper.insertSelective(picture);
        //根据url查询到返回的实体对象
        return picture;
    }

    @Override
    public void insertWorkOrderIdAndType(WorkOrderAddReqVO vo) {
        List<Integer> pictureIds = vo.getPictureIds();

        if (pictureIds != null && !pictureIds.isEmpty()) {
            if (pictureIds.size() > maxPicUploadNum) {
                throw new BusinessException(BaseResponseCode.FILE_NOT_MORE_THAN_NINE);
            }
            for (Integer pictureId : pictureIds) {
                WorkOrderPicture picture = new WorkOrderPicture();
                picture.setId(pictureId);
                picture.setWorkOrderId(vo.getId());
                picture.setType(CommonConstant.PICTURE.STATION);
                picture.setCreateTime(new Date());
                pictureMapper.updateByPrimaryKeySelective(picture);
            }
        }
    }

    @Override
    public WorkOrderPicture selectById(Integer id) {
        WorkOrderPicture picture = pictureMapper.selectByPrimaryKey(id);
        return picture;
    }

    @Override
    public List<PictureRespVO> selectByOrderId(Long workOrderId) {

        List<WorkOrderPicture> list = pictureMapper.selectByWorkOrderIdAndType(workOrderId, CommonConstant.PICTURE.WORK_ORDER);

        List<PictureRespVO> pictureResps = list.stream().map(s -> {
            byte[] bytes = null;
            //读取图片字节
            try {
                bytes = bytesUtil.readBlock(s.getUrl(), 0);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //获取文件类型
            File file = new File(s.getUrl());
            //文件后缀名
            String type = FilenameUtils.getExtension(file.getName());

            PictureRespVO pictureResp = new PictureRespVO();
            //图片才会设置base64
            if (CommonConstant.PICTURE_TYPE.contains(type)) {
                StringBuilder sb = new StringBuilder();
                String base64 = sb.append("data:image/").append(type).append(";base64,").append(Base64.encode(bytes)).toString();
                pictureResp.setBase(base64);
            }
            pictureResp.setPictureId(s.getId());
            pictureResp.setPictureType(type);
            pictureResp.setFileName(s.getFileName());
            return pictureResp;
        }).collect(Collectors.toList());
        return pictureResps;
    }

    @Override
    public void deletedById(Integer id) {
        pictureMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void deletedByWorkOrderIds(List<Long> ids) {
        if (!ids.isEmpty()) {
            //先删除文件
            List<WorkOrderPicture> pictures = new ArrayList<>();
            for (Long id : ids) {
                List<WorkOrderPicture> list = pictureMapper.selectByWorkOrderIdAndType(id, CommonConstant.PICTURE.WORK_ORDER);
                pictures.addAll(list);
            }
            for (WorkOrderPicture picture : pictures) {
                File file = new File(picture.getUrl());
                if (!file.exists()) {
                    file.delete();
                }
            }
            //再删除数据库文件数据
            pictureMapper.deletedBySrcIdsAndType(ids, CommonConstant.PICTURE.WORK_ORDER);
        }
    }

    @Override
    public void updatePicture(WorkOrderUpdateReqVO vo) {
        //判断是否有图片更新
        if (vo.getPictureIds() != null) {
            if (!vo.getPictureIds().isEmpty()) {
                //先对之前的图片workOrderId 进行赋空值
                List<WorkOrderPicture> pictures = pictureMapper.selectByWorkOrderIdAndType(vo.getId(), CommonConstant.PICTURE.STATION);
                List<Integer> pictureIds = pictures.stream().map(WorkOrderPicture::getId).collect(Collectors.toList());
                if (!pictureIds.isEmpty()) {
                    pictureMapper.setUpWorkOrderIdIdNUll(pictureIds);
                }
                //在新增
                WorkOrderAddReqVO workOrderAddReqVO = new WorkOrderAddReqVO();
                BeanUtils.copyProperties(vo, workOrderAddReqVO);
                insertWorkOrderIdAndType(workOrderAddReqVO);
            } else {
                //直接之前的图片workOrderId 进行赋空值
                List<WorkOrderPicture> pictures = pictureMapper.selectByWorkOrderIdAndType(vo.getId(), CommonConstant.PICTURE.STATION);
                List<Integer> pictureIds = pictures.stream().map(WorkOrderPicture::getId).collect(Collectors.toList());
                if (!pictureIds.isEmpty()) {
                    pictureMapper.setUpWorkOrderIdIdNUll(pictureIds);
                }
            }
        }
    }

    @Override
    public List<WorkOrderPicture> selectAll() {
        List<WorkOrderPicture> workOrderPictures = pictureMapper.selectAll();
        return workOrderPictures;
    }

    @Override
    public void deletedByIds(List<Long> workOrderPictureIds) {
        if (workOrderPictureIds != null && !workOrderPictureIds.isEmpty()) {
            pictureMapper.deletedBySrcIdsAndType(workOrderPictureIds, null);
        }
    }
}
