package com.jpsoft.shinestar.modules.mobile.controller;

import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.base.dto.*;
import com.jpsoft.shinestar.modules.base.entity.*;
import com.jpsoft.shinestar.modules.base.service.*;
import com.jpsoft.shinestar.modules.business.service.WorkAttendanceService;
import com.jpsoft.shinestar.modules.business.service.WorkScheduleAttendanceService;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.dto.ParkResult;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.utils.JwtUtil;
import com.jpsoft.shinestar.modules.common.utils.StringUtils;
import com.jpsoft.shinestar.modules.common.utils.WeixinUtil;
import com.jpsoft.shinestar.modules.pay.properties.WxPayProperties;
import com.jpsoft.shinestar.modules.wechat.entity.AccessToken;
import com.jpsoft.shinestar.modules.wechat.vo.UserInfo;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author 墨鱼_mo
 * @date 2020-10-21 14:00
 */
@RestController
@RequestMapping("/mobile/parkingInfoApi")
@Slf4j
public class ParkingInfoApiController {

    @Value("${jwt.secret}")
    private String jwtSecret;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private WorkScheduleAttendanceService workScheduleAttendanceService;


    @Autowired
    private ParkingMerchantBinderService parkingMerchantBinderService;

    @Autowired
    private PersonDeviceLogService personDeviceLogService;

    @Autowired
    private ParkingCouponService parkingCouponService;

    @Autowired
    private ParkingRecordService parkingRecordService;

    @Autowired
    private ParkingMerchantService parkingMerchantService;

    @Autowired
    private WxPayProperties wxPayProperties;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private ParkingInfoService parkingInfoService;

    @Autowired
    private ParkingApplyService parkingApplyService;

    @Autowired
    private ParkingAuthorizeService parkingAuthorizeService;

    @Autowired
    private ParkingWayService parkingWayService;


    @PostMapping("parkingList")
    @ResponseBody
    @ApiOperation(value = "可租赁车位列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", required = true, paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form")
    })
    public MessageResult<Map> parkingList(String token, @RequestAttribute String subject, String id) {
        MessageResult<Map> messageResult = new MessageResult<>();

        try {

            Map<String, Object> map = new HashMap<>();
            List<ParkingInfoDTO> list = new ArrayList<>();
            PersonInfo personInfo = personInfoService.get(new Long(subject));
            ParkingAuthorize parkingAuthorize = parkingAuthorizeService.findByAuthorizedCompanyId(personInfo.getCompanyId());
            if (parkingAuthorize != null) {

                if (StringUtils.isBlank(id)) {
                    List<ParkingInfo> parkingInfoList = parkingInfoService.findByCompanyIdNotParentId(parkingAuthorize.getCompanyId());
                    if (parkingInfoList.size() > 0) {
                        for (ParkingInfo parkingInfo : parkingInfoList) {
                            boolean enableLease = true;
                            ParkingInfoDTO parkingInfoDTO = new ParkingInfoDTO();
                            parkingInfoDTO.setId(parkingInfo.getId());
                            parkingInfoDTO.setParkingName(parkingInfo.getParkingName());
                            List<ParkingInfo> parkingList = parkingInfoService.findByParentId(parkingInfo.getId());
                            if (parkingList.size() > 0) {
                                parkingInfoDTO.setHasNext(true);
                            } else {
                                parkingInfoDTO.setHasNext(false);
                            }
                            Map<String, Object> searchParams = new HashMap<>();
                            searchParams.put("parkingFlag", true);
                            searchParams.put("code", "%" + parkingInfo.getId() + "%");
                            searchParams.put("applyEndTime", new Date());
                            List<Sort> sortList = new ArrayList<>();
                            sortList.add(new Sort("create_time", "desc"));
                            Page<ParkingInfo> parkingInfoPage = parkingInfoService.pageSearch(searchParams, 1, 1000, sortList);
                            //    Page<ParkingApply> parkingApplyPage = parkingApplyService.pageSearch(searchParams,1,1,sortList);
                            if (parkingInfoPage.getResult().size() == 0) {
                                enableLease = false;
                            }

                            parkingInfoDTO.setEnableLease(enableLease);
                            parkingInfoDTO.setNumber(parkingInfoPage.size());
                            list.add(parkingInfoDTO);
                        }
                    }


                } else {
                    List<ParkingInfo> parkingInfoList = parkingInfoService.findByParentId(id);
                    if (parkingInfoList.size() > 0) {
                        for (ParkingInfo parkingInfo : parkingInfoList) {
                            boolean enableLease = true;
                            ParkingInfoDTO parkingInfoDTO = new ParkingInfoDTO();
                            parkingInfoDTO.setId(parkingInfo.getId());
                            parkingInfoDTO.setParkingName(parkingInfo.getParkingName());
                            List<ParkingInfo> parkingList = parkingInfoService.findByParentId(parkingInfo.getId());
                            if (parkingList.size() > 0) {
                                parkingInfoDTO.setHasNext(true);
                            }

                            if (parkingList.size() == 0) {
                                parkingInfoDTO.setHasNext(false);
                            }


                            Map<String, Object> searchParams = new HashMap<>();
                            if (parkingInfo.getParkingFlag()) {
                                searchParams.put("id", parkingInfo.getId());
                            }
                            searchParams.put("parkingFlag", true);
                            searchParams.put("code", "%" + parkingInfo.getId() + "%");
                            searchParams.put("applyEndTime", new Date());
                            List<Sort> sortList = new ArrayList<>();
                            sortList.add(new Sort("create_time", "desc"));
                            Page<ParkingInfo> parkingInfoPage = parkingInfoService.pageSearch(searchParams, 1, 1000, sortList);
                            if (parkingInfoPage.getResult().size() == 0) {
                                enableLease = false;
                            }

                            parkingInfoDTO.setEnableLease(enableLease);
                            list.add(parkingInfoDTO);
                        }
                    }
                }

            }
            map.put("list", list);
            messageResult.setData(map);
            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @PostMapping("parkingPicList")
    @ResponseBody
    @ApiOperation(value = "停车场图片列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", required = true, paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form")
    })
    public MessageResult<Map> parkingPicList(String token, @RequestAttribute String subject) {
        MessageResult<Map> messageResult = new MessageResult<>();

        try {

            Map<String, Object> map = new HashMap<>();
            List<String> list = new ArrayList<>();
            PersonInfo personInfo = personInfoService.get(new Long(subject));
            ParkingAuthorize parkingAuthorize = parkingAuthorizeService.findByAuthorizedCompanyId(personInfo.getCompanyId());
            if (parkingAuthorize != null) {

                List<ParkingInfo> parkingInfoList = parkingInfoService.findHasPicUrl(parkingAuthorize.getCompanyId());
                if (parkingInfoList.size() > 0) {
                    for (ParkingInfo parkingInfo : parkingInfoList) {
                        list.add(parkingInfo.getPicUrl());
                    }
                }

            }
            map.put("list", list);
            messageResult.setData(map);
            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @PostMapping("parkingUnit")
    @ResponseBody
    @ApiOperation(value = "可租赁车位时间单位")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", required = true, paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form")
    })
    public MessageResult<Map> parkingUnit(String token, @RequestAttribute String subject) {
        MessageResult<Map> messageResult = new MessageResult<>();

        try {

            Map<String, Object> map = new HashMap<>();
            PersonInfo personInfo = personInfoService.get(new Long(subject));
            ParkingAuthorize parkingAuthorize = parkingAuthorizeService.findByAuthorizedCompanyId(personInfo.getCompanyId());
            if (parkingAuthorize != null) {
                ParkingWay parkingWay = parkingWayService.findByCompanyId(parkingAuthorize.getCompanyId());
                map.put("unit", parkingWay);

            }

            //查询是否有已处理但未支付的审计记录
            ParkingApply parkingApply1 = parkingApplyService.findByPopedomIdAndPayStatus(personInfo.getPopedom(), 10);
            if (parkingApply1 != null) {
                map.put("id", parkingApply1.getId());
            } else {
                //查询是否已经有一条未处理的申请记录
                ParkingApply parkingApply0 = parkingApplyService.findByPopedomIdAndStatus(personInfo.getPopedom(), "0");
                if (parkingApply0 != null) {
                    map.put("id", parkingApply0.getId());
                }
            }

            Map<String, Object> searchParams = new HashMap<>();
            searchParams.put("parkingFlag", true);
            searchParams.put("applyEndTime", new Date());
            List<Sort> sortList = new ArrayList<>();
            sortList.add(new Sort("create_time", "desc"));
            Page<ParkingInfo> parkingInfoPage = parkingInfoService.pageSearch(searchParams, 1, 1000, sortList);

            map.put("number", parkingInfoPage.getResult().size());


            messageResult.setData(map);
            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @PostMapping("inParkDate")
    @ResponseBody
    @ApiOperation(value = "进停车场数据")
    public ParkResult inParkDate(@RequestBody InParkDateDTO inParkDateDTO) {
        ParkResult parkResult = new ParkResult();

        try {
            ParkingRecord parkingRecord = new ParkingRecord();
            parkingRecord.setId(UUID.randomUUID().toString());
            parkingRecord.setParkId(Long.valueOf(inParkDateDTO.getPark_id()));
            parkingRecord.setCarNum(inParkDateDTO.getCar_number());
            parkingRecord.setInParkingTime(DateUtil.date(Long.parseLong(inParkDateDTO.getIn_time().toString()+"000")));
            parkingRecord.setPayStatus(10);
            parkingRecord.setProductTheme("停车费");
            parkingRecord.setCreateTime(new Date());
            parkingRecord.setCarType(inParkDateDTO.getCar_type());
            parkingRecord.setCType(inParkDateDTO.getC_type());
            parkingRecord.setOrderNumber(inParkDateDTO.getOrder_id());

            /**
             * 文档中通道名称和id相反
             */
            parkingRecord.setInChannelId(inParkDateDTO.getIn_channel());
            parkingRecord.setInChannel(inParkDateDTO.getIn_channel_id());
            parkingRecord.setInImage(inParkDateDTO.getIn_image());
            parkingRecordService.insert(parkingRecord);


            //新生源车辆进场打考勤卡
            new Thread(()->{
                String carNum = inParkDateDTO.getCar_number();
                PersonInfo personInfo = personInfoService.findByCarNum(carNum);
                if (personInfo != null){

                    workScheduleAttendanceService.punchIn(inParkDateDTO.getIn_channel(),personInfo.getId(),BigDecimal.ZERO,DateUtil.date(Long.parseLong(inParkDateDTO.getIn_time().toString()+"000")));

                    try{
                        personDeviceLogService.insertLog(inParkDateDTO.getIn_channel(),personInfo,BigDecimal.ZERO,personInfo.getFaceImageUrl(),DateUtil.date(Long.parseLong(inParkDateDTO.getIn_time().toString()+"000")),1,"核验成功",personInfo.getId().intValue());
                    }catch (Exception ex){
                        ex.printStackTrace();
                    }



                }

            }).start();


            parkResult.setState(1);
            parkResult.setErrmsg("send success!");
        } catch (Exception ex) {
            log.error(ex.getMessage(),ex);
            parkResult.setState(0);
            parkResult.setErrmsg("send fail!");
        }

        return parkResult;
    }

    @PostMapping("outParkDate")
    @ResponseBody
    @ApiOperation(value = "出停车场数据")
    public ParkResult outParkDate(@RequestBody OutParkDateDTO outParkDateDTO ) {
        ParkResult parkResult = new ParkResult();

        try {


            String orderNumber = outParkDateDTO.getOrder_id();

            if (orderNumber != null){
                ParkingRecord parkingRecord = parkingRecordService.findByOrderNumber(orderNumber);
                if (parkingRecord != null){
                    parkingRecord.setParkingTime(new BigDecimal(outParkDateDTO.getDuration()));
                    //现金支付直接修改
                    if (outParkDateDTO.getPay_channel() == 0 && parkingRecord.getPayStatus()==10){
                        parkingRecord.setTotalAmount(new BigDecimal(outParkDateDTO.getAmount_receivable()));
                        parkingRecord.setReduceAmount(new BigDecimal(outParkDateDTO.getReduce_amount()));
                        parkingRecord.setPayAmount(new BigDecimal(outParkDateDTO.getTotal()));
                        parkingRecord.setPayType(OutParkDateDTO.getPayType(outParkDateDTO.getPay_channel()));
                        parkingRecord.setPayStatus(20);
                        parkingRecord.setPaymentTime(new Date());
                        parkingRecord.setTransactionNumber(outParkDateDTO.getOut_order_id());
                    }
                    if (outParkDateDTO.getPay_channel() ==0 && parkingRecord.getPayStatus() == 20){
                        parkingRecord.setTotalAmount(parkingRecord.getTotalAmount().add(new BigDecimal(outParkDateDTO.getAmount_receivable())));
                        parkingRecord.setReduceAmount(parkingRecord.getReduceAmount().add(new BigDecimal(outParkDateDTO.getReduce_amount())));
                        parkingRecord.setPayAmount( parkingRecord.getPayAmount().add(new BigDecimal(outParkDateDTO.getTotal())));
                        parkingRecord.setPayType(parkingRecord.getPayType()+","+OutParkDateDTO.getPayType(outParkDateDTO.getPay_channel()));
                        parkingRecord.setPaymentTime(new Date());
                    }


                    /**
                     * 文档中通道名称和id相反
                     */
                    parkingRecord.setOutChannel(outParkDateDTO.getOut_channel_id());
                    parkingRecord.setOutChannelId(outParkDateDTO.getOut_channel());
                    parkingRecord.setOutImage(outParkDateDTO.getOut_image());
                    parkingRecord.setOutParkingTime(DateUtil.date(Long.parseLong(outParkDateDTO.getOut_time().toString()+"000")));
                    parkingRecordService.update(parkingRecord);


                }
            }

            parkResult.setState(1);
            parkResult.setErrmsg("send success!");
        } catch (Exception ex) {
            log.error(ex.getMessage(),ex);
            parkResult.setState(0);
            parkResult.setErrmsg("send fail!");
        }

        return parkResult;
    }


    @PostMapping("findByOpenIdAndMerchant")
    @ResponseBody
    @ApiOperation(value = "通过openId和商户id查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "openId", value = "openId", required = true, paramType = "form"),
            @ApiImplicitParam(name = "merchantId", value = "商户id", required = true, paramType = "form")
    })
    public MessageResult<Map> findByOpenIdAndMerchant(String openId,String merchantId) {
        MessageResult<Map> messageResult = new MessageResult<>();

        try{

            ParkingMerchant parkingMerchant = parkingMerchantService.get(merchantId);
            if (parkingMerchant == null){
                throw new Exception("商户不存在");
            }

            ParkingMerchantBinder parkingMerchantBinder = parkingMerchantBinderService.findByOpenIdAndMerchantId(openId,merchantId);

            if (parkingMerchantBinder == null){
                throw new Exception("未授权");
            }



            Map<String,Object> map = new HashMap<>();
            map.put("id",parkingMerchant.getId());
            map.put("name",parkingMerchant.getMerchantName());
            map.put("token",JwtUtil.createToken(jwtSecret, parkingMerchant.getId() + "", DateTime.now().plusHours(6).toDate()));
            messageResult.setData(map);
            messageResult.setResult(true);
            messageResult.setMessage("成功");
        }catch (Exception ex){
            log.error(ex.getMessage(),ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }


        return messageResult;
        }


    @PostMapping("queryParkDetail")
    @ResponseBody
    @ApiOperation(value = "查询停车详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form"),
            @ApiImplicitParam(name = "carNumber", value = "carNumber", required = true, paramType = "form")

    })
    public MessageResult<ParkingDetailDTO> queryParkDetail(String carNumber,String token, @RequestAttribute String subject) {
        MessageResult<ParkingDetailDTO> messageResult = new MessageResult<>();
        try{
           ParkingMerchant parkingMerchant = parkingMerchantService.get(subject);

           if (parkingMerchant == null){
               throw new Exception("商户不存在");
           }

            ParkingDetailDTO parkingDetailDTO = parkingRecordService.findByCarNumber(carNumber,parkingMerchant,null);
           messageResult.setData(parkingDetailDTO);
           messageResult.setResult(true);
        }catch (Exception ex){
            log.error(ex.getMessage(),ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }
        return messageResult;
    }

    @PostMapping("giveDiscountTicket")
    @ResponseBody
    @ApiOperation(value = "赠送优惠券")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form"),
            @ApiImplicitParam(name = "carNumber", value = "车牌号", required = true, paramType = "form"),
            @ApiImplicitParam(name = "id",value = "id",required = true,paramType = "form")
    })
    public MessageResult<Map> giveDiscountTicket(String carNumber,String id,String token, @RequestAttribute String subject) {
        MessageResult<Map> messageResult = new MessageResult<>();

        try{
            ParkingMerchant parkingMerchant = parkingMerchantService.get(subject);

            if (parkingMerchant == null){
                throw new Exception("商户不存在");
            }

            ParkingCoupon parkingCoupon0 = parkingCouponService.findByParkingRecordIdAndStatus(id,false);
            if (parkingCoupon0 != null){
                throw new Exception("此车已赠送优惠券");
            }

            String code =  parkingMerchantService.createReductionTicket(carNumber,parkingMerchant);

            parkingMerchantService.useReductionTicket(carNumber,code,parkingMerchant);

            ParkingCoupon parkingCoupon = new ParkingCoupon();
            parkingCoupon.setId(UUID.randomUUID().toString());
            parkingCoupon.setMerchantId(parkingMerchant.getId());
            parkingCoupon.setType(parkingMerchant.getType());
            parkingCoupon.setReduce(parkingMerchant.getReduce());
            parkingCoupon.setParkingRecordId(id);
            parkingCoupon.setUseStatus(false);
            parkingCoupon.setUseQuote(0);
            parkingCoupon.setInvalidTime(DateUtil.offsetHour(new Date(),24));
            parkingCoupon.setCreateTime(new Date());
            parkingCouponService.insert(parkingCoupon);
            messageResult.setResult(true);
        }catch (Exception ex){
            log.error(ex.getMessage(),ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;

    }

    @PostMapping("discountTicketList")
    @ResponseBody
    @ApiOperation(value = "赠送优惠券历史记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", required = false, paramType = "form"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", required = false, paramType = "form"),
            @ApiImplicitParam(name = "carNumber",value = "车牌号",required = false,paramType = "form")
    })
    public MessageResult<Map> discountTicketList(String carNumber,String startTime,String endTime,String token, @RequestAttribute String subject,@RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex, @RequestParam(value = "pageSize", defaultValue = "20") int pageSize) {
        MessageResult<Map> messageResult = new MessageResult<>();

        try{
            ParkingMerchant parkingMerchant = parkingMerchantService.get(subject);


            Map<String, Object> searchParams = new HashMap<>();

            searchParams.put("merchantId",parkingMerchant.getId());

            if (org.apache.commons.lang3.StringUtils.isNotBlank(carNumber)){
                searchParams.put("carNum", carNumber);
            }
            if (org.apache.commons.lang3.StringUtils.isNotBlank(startTime)){
                searchParams.put("startTime",startTime);
            }
            if (org.apache.commons.lang3.StringUtils.isNotBlank(endTime)){
                searchParams.put("endTime",endTime);
            }

            List<Sort> sortList = new ArrayList<>();
            sortList.add(new Sort("a.create_time", "desc"));
            Page<ParkingCoupon> page =  parkingCouponService.pageSearch(searchParams, pageIndex, pageSize, false, sortList);

            Map<String, Object> map = new HashMap<>();
            map.put("totalPage", page.getPages());
            map.put("pageNumber", page.getPageNum());
            map.put("pageSize", page.getPageSize());
            map.put("data", page.getResult());
            map.put("recordsTotal", page.getTotal());
            map.put("recordsFiltered", page.getTotal());

            messageResult.setData(map);
            messageResult.setResult(true);
        }catch (Exception ex){
            log.error(ex.getMessage(),ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }
        return messageResult;
    }


    @PostMapping("discountTicketDetail")
    @ResponseBody
    @ApiOperation(value = "赠送优惠券详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form"),
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "form")
    })
    public MessageResult<ParkingCouponApiDTO> discountTicketDetail(String id, String token, @RequestAttribute String subject) {
        MessageResult<ParkingCouponApiDTO> messageResult = new MessageResult<>();

        try{

            ParkingCouponApiDTO parkingCouponApiDTO = new ParkingCouponApiDTO();
            ParkingCoupon parkingCoupon = parkingCouponService.get(id);
            if (parkingCoupon == null){
                throw new Exception("优惠券不存在");
            }

            ParkingRecord parkingRecord = parkingRecordService.get(parkingCoupon.getParkingRecordId());
            if (parkingRecord ==null){
                throw new Exception("停车记录不存在");
            }
            ParkingMerchant parkingMerchant = parkingMerchantService.get(parkingCoupon.getMerchantId());
            List<ParkingInfo> parkingInfoList = parkingInfoService.findByCompanyIdNotParentId(parkingMerchant.getCompanyId());
            ParkingInfo parkingInfo = parkingInfoList.get(0);
            parkingCouponApiDTO.setCarNumber(parkingRecord.getCarNum());

            if (parkingRecord.getOutParkingTime()!=null){
                parkingCouponApiDTO.setParkingStatus("2");
                parkingCouponApiDTO.setParkingStatusStr("已离场");
                parkingCouponApiDTO.setInTimeStr(parkingRecord.getParkingTime().toString()+"分钟");
               parkingCouponApiDTO.setOutParkTime(DateUtil.format(parkingRecord.getOutParkingTime(),"yyyy-MM-dd HH:mm:ss"));
            }else {
                parkingCouponApiDTO.setParkingStatus("1");
                parkingCouponApiDTO.setParkingStatusStr("停车中");
                ParkingDetailDTO parkingDetailDTO = parkingRecordService.findByCarNumber(parkingRecord.getCarNum(),parkingMerchant,null);
                parkingCouponApiDTO.setInTimeStr(parkingDetailDTO.getParkingTime()+"分钟");
            }

            parkingCouponApiDTO.setCouponCreateTime(DateUtil.format(parkingCoupon.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
            parkingCouponApiDTO.setMerchantName(parkingMerchant.getMerchantName());
            parkingCouponApiDTO.setParkingName(parkingInfo.getParkingName());
            parkingCouponApiDTO.setCouponMoney(String.valueOf(parkingCoupon.getReduce()));
            parkingCouponApiDTO.setInParkTime(DateUtil.format(parkingRecord.getInParkingTime(),"yyyy-MM-dd HH:mm:ss"));

            messageResult.setData(parkingCouponApiDTO);
            messageResult.setResult(true);
        }catch (Exception ex){
            log.error(ex.getMessage(),ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }
        return messageResult;
    }



    @PostMapping("carPayDetail")
    @ResponseBody
    @ApiOperation(value = "车牌号查询缴费详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "carNumber", value = "车牌号", required = true, paramType = "form"),
            @ApiImplicitParam(name = "companyId", value = "停车场对应物业公司", required = true, paramType = "form")
    })
    public MessageResult<ParkingDetailDTO> carPayDetail(String carNumber, String companyId) {
        MessageResult<ParkingDetailDTO> messageResult = new MessageResult<>();

        try{

            List<ParkingInfo> parkingInfoList = parkingInfoService.findByCompanyIdNotParentId(companyId);
            if (parkingInfoList.size() == 0){
                throw new Exception("物业公司设置停车场有误");
            }
            ParkingInfo parkingInfo = parkingInfoList.get(0);
            ParkingDetailDTO parkingDetailDTO = parkingRecordService.findByCarNumber(carNumber,null,parkingInfo.getParkId());

            if (parkingDetailDTO.getPrice() == 0){
                throw new Exception("请直接离场");
            }

            ParkingRecord parkingRecord = parkingRecordService.get(parkingDetailDTO.getId());
            if (parkingRecord.getPayStatus() == 10){
                parkingRecord.setTotalAmount(new BigDecimal(parkingDetailDTO.getTotal()));
                parkingRecord.setReduceAmount(new BigDecimal(parkingDetailDTO.getDiscountMoney()));
                parkingRecord.setPayAmount(new BigDecimal(parkingDetailDTO.getPrice()));

                parkingRecordService.update(parkingRecord);
            }



            messageResult.setData(parkingDetailDTO);
            messageResult.setResult(true);
        }catch (Exception ex){
            log.error(ex.getMessage(),ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;


    }

    @PostMapping("channelPayDetail")
    @ResponseBody
    @ApiOperation(value = "通道查询缴费详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "channelId", value = "通道id", required = true, paramType = "form"),
            @ApiImplicitParam(name = "companyId", value = "停车场对应物业公司", required = true, paramType = "form")
    })
    public MessageResult<ParkingDetailDTO> channelPayDetail(String channelId, String companyId) {
        MessageResult<ParkingDetailDTO> messageResult = new MessageResult<>();

        try{

            List<ParkingInfo> parkingInfoList = parkingInfoService.findByCompanyIdNotParentId(companyId);
            if (parkingInfoList.size() == 0){
                throw new Exception("物业公司设置停车场有误");
            }
            if (org.apache.commons.lang3.StringUtils.isBlank(channelId)){
                throw new Exception("车道不能为空");
            }

            ParkingInfo parkingInfo = parkingInfoList.get(0);
            ParkingDetailDTO parkingDetailDTO = parkingRecordService.findByChannel(channelId,null,parkingInfo.getParkId());

            if (parkingDetailDTO.getPrice() == 0){
                throw new Exception("请直接离场");
            }


            ParkingRecord parkingRecord = parkingRecordService.get(parkingDetailDTO.getId());
            if (parkingRecord.getPayStatus() ==10){
                parkingRecord.setTotalAmount(new BigDecimal(parkingDetailDTO.getTotal()));
                parkingRecord.setReduceAmount(new BigDecimal(parkingDetailDTO.getDiscountMoney()));
                parkingRecord.setPayAmount(new BigDecimal(parkingDetailDTO.getPrice()));

                parkingRecordService.update(parkingRecord);
            }



            messageResult.setData(parkingDetailDTO);
            messageResult.setResult(true);
        }catch (Exception ex){
            log.error(ex.getMessage(),ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;


    }

    @PostMapping("findByCompanyId")
    @ResponseBody
    @ApiOperation(value = "获取停车场信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyId", value = "停车场对应物业公司", required = true, paramType = "form")
    })
    public MessageResult<ParkingInfoDTO> findByCompanyId(String companyId) {
        MessageResult<ParkingInfoDTO> messageResult = new MessageResult<>();

        try{

            List<ParkingInfo> parkingInfoList = parkingInfoService.findByCompanyIdNotParentId(companyId);
            ParkingInfo parkingInfo = parkingInfoList.get(0);

            ParkingInfoDTO parkingInfoDTO = new ParkingInfoDTO();
            BeanUtils.copyProperties(parkingInfo,parkingInfoDTO);
            messageResult.setData(parkingInfoDTO);
            messageResult.setResult(true);
        }catch (Exception ex){
            log.error(ex.getMessage(),ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @PostMapping("bindParkMerchant")
    @ResponseBody
    @ApiOperation(value = "绑定停车场商户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "停车场商户公司", required = true, paramType = "form")
    })
    public MessageResult<Map> bindParkMerchant(String id,String name,String phone,String openid,String nickname,String headimgurl) {
        MessageResult<Map> messageResult = new MessageResult<>();

        try{

            if (org.apache.commons.lang3.StringUtils.isBlank(id)){
                throw new Exception("商户id为空");
            }

            if (org.apache.commons.lang3.StringUtils.isBlank(name) || org.apache.commons.lang3.StringUtils.isBlank(phone)){
                throw new Exception("姓名和手机号不可为空");
            }

            ParkingMerchantBinder parkingMerchantBinder0 = parkingMerchantBinderService.findByOpenIdAndMerchantId(openid,id);
            if (parkingMerchantBinder0 != null){
                throw new Exception("您已绑定此商户");
            }


            ParkingMerchantBinder parkingMerchantBinder = new ParkingMerchantBinder();
            parkingMerchantBinder.setId(UUID.randomUUID().toString());
            parkingMerchantBinder.setName(name);
            parkingMerchantBinder.setPhone(phone);
            parkingMerchantBinder.setParkMerchantId(id);
            parkingMerchantBinder.setOpenId(openid);
            parkingMerchantBinder.setNickName(nickname);
            parkingMerchantBinder.setPicUrl(headimgurl);
            parkingMerchantBinder.setParkMerchantId(id);
            parkingMerchantBinderService.insert(parkingMerchantBinder);




            messageResult.setResult(true);
        }catch (Exception ex){
            log.error(ex.getMessage(),ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }




}
