package com.xxfc.platform.order.biz;

import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.github.wxiaoqi.security.admin.feign.dto.UserDTO;
import com.github.wxiaoqi.security.admin.feign.rest.UserRestInterface;
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.github.wxiaoqi.security.common.util.process.ResultCode;
import com.xxfc.platform.order.entity.BaseOrder;
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.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

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

    @Autowired
    BaseOrderBiz baseOrderBiz;

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

    @Autowired
    UserFeign userFeign;

    @Autowired
    OrderAccountBiz orderAccountBiz;

    public static final DateTimeFormatter DEFAULT_DATE_TIME_FORMATTER = DateTimeFormat.forPattern("yyyy-MM-dd");
    @Override
    public UserFeign getUserFeign() {
        return userFeign;
    }

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 保存违章记录
     *
     * @param orderViolation
     */
    @Transactional(rollbackFor = Exception.class)
    public void insertOrderViolation(OrderViolation orderViolation) {
        UserDTO userDTO = getBusinessUserByAppUser();
        if (userDTO == null ) {
            throw new BaseException(ResultCode.RSTOKEN_EXPIRED_CODE);
        }
        OrderViolation old = mapper.selectOne(new OrderViolation(){{setDetailId(orderViolation.getDetailId());}});
        if (old  != null) {
            throw new BaseException("违章记录已存在!");
        } else {
            OrderRentVehicleDetail orderRentVehicleDetail = new OrderRentVehicleDetail();
            orderRentVehicleDetail.setId(orderViolation.getDetailId());
            orderRentVehicleDetail.setHandelViolation(1);
            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)) {
                orderViolation.setIsDel(0);
                orderViolation.setCrtHost(getRequest().getRemoteHost());
                orderViolation.setCrtName(userDTO.getName());
                orderViolation.setCrtUserId(userDTO.getId());
                orderViolation.setCrtTime(new BigInteger(String.valueOf(System.currentTimeMillis())));
                insertSelective(orderViolation);
                detailMapper.updateByPrimaryKeySelective(orderRentVehicleDetail);
                BaseOrder baseOrder = baseOrderBiz.selectOne(new BaseOrder(){{setDetailId(orderViolation.getDetailId());}});
                if (baseOrder != null) {
                    baseOrder.setRefundStatus(3);
                    baseOrderBiz.updateSelectiveByIdRe(baseOrder);
                    //触发违章金退款
                    //orderAccountBiz.handleRentDepositMarginV2(baseOrder, orderRentVehicleDetail);
                }
            } else {
                throw new BaseException("The operation cannot be changed at this time");
            }
        }

    }

    /**
     * 修改违章记录
     *
     * @param orderViolation
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateOrderViolation(OrderViolation orderViolation) {
        UserDTO userDTO = getBusinessUserByAppUser();
        if (userDTO == null ) {
            throw new BaseException(ResultCode.RSTOKEN_EXPIRED_CODE);
        }
        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)) {
            orderViolation.setUpdHost(getRequest().getRemoteHost());
            orderViolation.setUpdName(userDTO.getName());
            orderViolation.setUpdUserId(userDTO.getId());
            orderViolation.setUpdTime(new BigInteger(String.valueOf(System.currentTimeMillis())));
            updateSelectiveByIdRe(orderViolation);

            BaseOrder baseOrder = baseOrderBiz.selectOne(new BaseOrder(){{setDetailId(orderViolation.getDetailId());}});
            if (baseOrder != null) {
                baseOrder.setRefundStatus(3);
                baseOrderBiz.updateSelectiveByIdRe(baseOrder);
            }
        } 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);
    }


    public void batchSave(List<OrderViolation> list) {
        mapper.batchSave(list);
    }
}
