package com.xxfc.platform.order.rest;


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.exception.BaseException;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.xxfc.platform.order.biz.OrderDepositRefundRecordBiz;
import com.xxfc.platform.order.biz.OrderViolationBiz;
import com.xxfc.platform.order.entity.OrderViolation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.weekend.WeekendSqls;

import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.util.List;

/**
 * 订单违章表
 *
 * @author Administrator
 */
@RestController
@RequestMapping("orderViolation")
@Slf4j
public class OrderViolationController extends BaseController<OrderViolationBiz, OrderViolation> implements UserRestInterface {

    @Autowired
    private UserFeign userFeign;
    @Autowired
    OrderDepositRefundRecordBiz orderDepositRefundRecordBiz;
    @Override
    public UserFeign getUserFeign() {
        return userFeign;
    }

    private Long MAX_DRIVING_LICENSE_SIZE = 1024 * 1024 * 50L;

    private final String  FILE_TYPE="JPG";

    /**
     * 保存违章记录
     *
     * @param orderViolation
     * @param request
     * @return
     */
    @PostMapping("/saveOrderViolation")
    public ObjectRestResponse saveOrderViolation(@RequestBody OrderViolation orderViolation, HttpServletRequest request) {
        log.info("保存违章记录：orderViolation = {}", orderViolation.toString());
        UserDTO userDTOD = getAdminUserInfo();
        if (orderViolation.getId()==null) {
            orderViolation.setIsDel(0);
            orderViolation.setCrtHost(request.getRemoteHost());
            orderViolation.setCrtName(userDTOD.getName());
            orderViolation.setCrtUserId(userDTOD.getId());
            orderViolation.setCrtTime(new BigInteger(String.valueOf(System.currentTimeMillis())));
            getBaseBiz().insertOrderViolation(orderViolation);
        }else {
            orderViolation.setUpdHost(request.getRemoteHost());
            orderViolation.setUpdName(userDTOD.getName());
            orderViolation.setUpdUserId(userDTOD.getId());
            orderViolation.setUpdTime(new BigInteger(String.valueOf(System.currentTimeMillis())));
            getBaseBiz().updateOrderViolation(orderViolation);
        }
        orderDepositRefundRecordBiz.saveViolationDeposit(orderViolation);
        return ObjectRestResponse.succ();
    }

    /**
     * 通过订单id查询违章记录
     *
     * @param detailId
     * @return
     */
    @GetMapping("/getOne/{detailId}")
    public ObjectRestResponse<OrderViolation> getOne(@PathVariable Integer detailId) {
        Example exa = Example.builder(OrderViolation.class)
                .where(WeekendSqls.<OrderViolation>custom().andEqualTo(OrderViolation::getDetailId, detailId)
                        .andEqualTo(OrderViolation::getIsDel, 0)).build();
        List<OrderViolation> orderViolations = getBaseBiz().selectByExample(exa);
        if (orderViolations.size() > 1) {
            throw new BaseException("The database has multiple records");
        }
        OrderViolation orderViolation= new OrderViolation();
        orderViolation=(orderViolations.size()==0)? null:orderViolations.get(0);
        return ObjectRestResponse.succ(orderViolation);
    }



    @PostMapping(value = "/upload/violation")
    public ObjectRestResponse uploadViolation(@RequestParam("file") MultipartFile file)
            throws Exception {
        Assert.notNull(file);
        //文件类型
        String contentType = file.getContentType();
        if (!FILE_TYPE.equalsIgnoreCase(contentType)||"png".equalsIgnoreCase(contentType)) {
            return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE,"Picture format error");
        }
        if (file.getSize() > MAX_DRIVING_LICENSE_SIZE) {
            return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE,"Picture is too large");
        }
        return baseBiz.uploadViolation(file);
    }


    @GetMapping(value = "/download/Violation/{realFileRelPath}") //匹配的是href中的download请求
    public ResponseEntity<byte[]> downloadViolation(@RequestParam("realFileRelPath") String realFileRelPath) throws Exception {
        return baseBiz.downloadViolation(realFileRelPath);
    }
}
