package com.xxfc.platform.order.biz;

import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.xxfc.platform.order.entity.OrderRentVehicleDetail;
import com.xxfc.platform.order.entity.OrderViolation;
import com.xxfc.platform.order.mapper.OrderRentVehicleDetailMapper;
import com.xxfc.platform.order.mapper.OrderViolationMapper;
import com.xxfc.platform.vehicle.constant.RedisKey;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 订单违章记录biz
 *
 * @author Administrator
 */
@Service
@Slf4j
public class OrderViolationBiz extends BaseBiz<OrderViolationMapper, OrderViolation> {
    @Autowired
    private OrderRentVehicleDetailMapper detailMapper;

    @Value("order.violation.upload")
    private String ovUpload;

    public static final DateTimeFormatter DEFAULT_DATE_TIME_FORMATTER = DateTimeFormat.forPattern("yyyy-MM-dd");

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 保存违章记录
     *
     * @param orderViolation
     */
    @Transactional(rollbackFor = Exception.class)
    public void insertOrderViolation(OrderViolation orderViolation) {
        OrderRentVehicleDetail orderRentVehicleDetail = new OrderRentVehicleDetail();
        orderRentVehicleDetail.setId(orderViolation.getDetailId());
        orderRentVehicleDetail.setHandelViolation(0);
        Map<String, Object> status = mapper.getOrderAndVehicleStatus(orderViolation.getDetailId());
        Integer orderStatus = (Integer) status.get("status");
        Integer refundStatus = (Integer) status.get("refundStatus");
        if (orderStatus >= 6 || (refundStatus <= 2 && refundStatus != 1)) {
            insertSelective(orderViolation);
            detailMapper.updateByPrimaryKeySelective(orderRentVehicleDetail);
        } else {
            throw new BaseException("The operation cannot be changed at this time");
        }

    }

    /**
     * 修改违章记录
     *
     * @param orderViolation
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateOrderViolation(OrderViolation orderViolation) {
        Map<String, Object> status = mapper.getOrderAndVehicleStatus(orderViolation.getDetailId());
        Integer orderStatus = (Integer) status.get("status");
        Integer refundStatus = (Integer) status.get("refundStatus");
        if (orderStatus >= 6 || (refundStatus <= 2 && refundStatus != 1)) {
            updateSelectiveByIdRe(orderViolation);
        } else {
            throw new BaseException("The operation cannot be changed at this time");
        }

    }

    public ObjectRestResponse uploadViolation(MultipartFile file) throws IOException {
        DateTime now = DateTime.now();
        String dirPathToday = File.separator + now.toString(DEFAULT_DATE_TIME_FORMATTER);
        String redisNoKey = RedisKey.UPLOAD_FILE_NO_PREFIX + now.toString(DEFAULT_DATE_TIME_FORMATTER);
        Long no = redisTemplate.opsForValue().increment(redisNoKey);
        if (no.equals(1L)) {
            redisTemplate.expire(redisNoKey, 1, TimeUnit.DAYS);
        }
        String fileName = file.getOriginalFilename();
        String realFileRelPath = dirPathToday + File.separator + no + fileName.substring(fileName.lastIndexOf("."));

        String filePath = ovUpload + realFileRelPath;

        FileUtils.copyInputStreamToFile(file.getInputStream(), new File(filePath));
        return ObjectRestResponse.succ(filePath);
    }


    /**
     * 下载行驶证图片
     *
     * @param realFileRelPath
     * @return
     * @throws Exception
     */
    public ResponseEntity<byte[]> downloadViolation(String realFileRelPath) throws Exception {
        String filePath = ovUpload + realFileRelPath;
        File file = new File(filePath);//新建一个文件
        HttpHeaders headers = new HttpHeaders();//http头信息
        String downloadFileName = new String(file.getName());//设置编码
        headers.setContentDispositionFormData("attachment", downloadFileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
    }


    /**
     * 根据订单详情查询违章记录
     */
    public OrderViolation getOneByDetailId(Integer detailId) {
        return mapper.getOneByDetailId(detailId);
    }
}
