package com.ruoyi.app.order;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.List;
import jakarta.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.app.utils.DateUtil;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.system.domain.PosOrder;
import com.ruoyi.system.domain.RiderPosition;
import com.ruoyi.system.mapper.TaxiOrderMapper;
import com.ruoyi.system.service.IInfoUserService;
import com.ruoyi.system.service.IRiderPositionService;
import com.ruoyi.system.utils.Auth;
import com.ruoyi.system.utils.JwtUtil;
import io.swagger.models.auth.In;
import lombok.SneakyThrows;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.TaxiOrder;
import com.ruoyi.system.service.ITaxiOrderService;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * TaxiOrderController
 *
 * @author ruoyi
 * @date 2024-01-26
 */
@RestController
@RequestMapping("/system/txorder")
public class TaxiOrderController extends BaseController
{
    @Autowired
    private ITaxiOrderService taxiOrderService;
    @Autowired
    private TaxiOrderMapper taxiOrderMapper;
    @Autowired
    private IInfoUserService infoUserService;
    @Autowired
    private IRiderPositionService riderPositionService;

    //获取订单详情
    @Anonymous
    @GetMapping("/getTxorder")
    public AjaxResult getTxorder(@RequestParam Long  id)
    {
        TaxiOrder order =  taxiOrderService.getById(id);
        JSONObject org = new JSONObject();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        org.put("id",order.getId());
        org.put("ddId",order.getDdId());
        org.put("user",infoUserService.getById(order.getUserId()));
        org.put("driver",infoUserService.getById(order.getDriverId()));
        org.put("boardingAddress",order.getBoardingAddress());
        org.put("intoLongitude",order.getIntoLongitude());
        org.put("intoLatitude",order.getIntoLatitude());
        org.put("downAddress",order.getDownAddress());
        org.put("downLongitude",order.getDownLongitude());
        org.put("downLatitude",order.getIntoLatitude());
        org.put("distance",order.getDistance());
        org.put("state",order.getState());
        org.put("taxiType",order.getTaxiType());
        org.put("releaseId",order.getReleaseId());
        org.put("orderTime",sdf.format(order.getOrderTime()));
        org.put("boardingTime",order.getBoardingTime());
        org.put("alightingTime",order.getAlightingTime());
        org.put("appointmentTime",order.getAppointmentTime());
        org.put("fare",order.getFare());
        org.put("highwayCosts",order.getHighwayCosts());
        org.put("amount",order.getAmount());
        org.put("estimatedDuration",order.getEstimatedDuration());
        org.put("notes",order.getNotes());
        org.put("coupon",order.getCoupon());
        QueryWrapper<RiderPosition> query= new QueryWrapper<>();
        query.eq("rider_id",order.getDriverId());
        org.put("RiderPosition",order.getDriverId()==null||order.getDriverId().equals("")?null:riderPositionService.getOne(query));

        return success(org);
    }
    //获取用户订单
    @Anonymous
    @Auth
    @GetMapping("/getUsTxorder")
    public AjaxResult getUsTxorder(@RequestHeader String token,
                                   @RequestParam Integer page,
                                   @RequestParam Integer size,
                                   @RequestParam String type,
                                   @RequestParam(defaultValue = "") String state)
    {
        JwtUtil jwtUtil = new JwtUtil();
        String id = jwtUtil.getusid(token);
        IPage<TaxiOrder> palist = new Page<>(page, size);
        QueryWrapper<TaxiOrder> queryWrapper= new QueryWrapper<>();
        queryWrapper.select().orderByDesc("order_time");
        if(type.equals("0")){
            queryWrapper.eq("user_id",id);
        }else {
            queryWrapper.eq("driver_id",id);
        }
        if(!"".equals(state)){
            queryWrapper.eq("state",state);
        }
        IPage<TaxiOrder> list =  taxiOrderService.page(palist,queryWrapper);
        List<TaxiOrder> orlist = list.getRecords();
        JSONArray arr = new JSONArray();
        for(int i=0;i<orlist.size();i++){
            JSONObject org = new JSONObject();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            org.put("id",orlist.get(i).getId());
            org.put("ddId",orlist.get(i).getDdId());
            org.put("user",infoUserService.getById(orlist.get(i).getUserId()));
            org.put("driver",infoUserService.getById(orlist.get(i).getDriverId()));
            org.put("boardingAddress",orlist.get(i).getBoardingAddress());
            org.put("intoLongitude",orlist.get(i).getIntoLongitude());
            org.put("intoLatitude",orlist.get(i).getIntoLatitude());
            org.put("downAddress",orlist.get(i).getDownAddress());
            org.put("downLongitude",orlist.get(i).getDownLongitude());
            org.put("downLatitude",orlist.get(i).getIntoLatitude());
            org.put("distance",orlist.get(i).getDistance());
            org.put("state",orlist.get(i).getState());
            org.put("taxiType",orlist.get(i).getTaxiType());
            org.put("releaseId",orlist.get(i).getReleaseId());
            org.put("orderTime",sdf.format(orlist.get(i).getOrderTime()));
            org.put("boardingTime",orlist.get(i).getBoardingTime());
            org.put("alightingTime",orlist.get(i).getAlightingTime());
            org.put("appointmentTime",orlist.get(i).getAppointmentTime());
            org.put("fare",orlist.get(i).getFare());
            org.put("highwayCosts",orlist.get(i).getHighwayCosts());
            org.put("amount",orlist.get(i).getAmount());
            org.put("estimatedDuration",orlist.get(i).getEstimatedDuration());
            org.put("notes",orlist.get(i).getNotes());
            org.put("coupon",orlist.get(i).getCoupon());
            arr.add(org);
        }
        return success(arr);
    }

    //获取附近可接订单
    @Anonymous
    @GetMapping("/getFjorder")
    public AjaxResult getFjorder(@RequestParam BigDecimal longitude,
                                 @RequestParam BigDecimal latitude,
                                 @RequestParam Integer page,
                                 @RequestParam Integer juli)
    {
        List<TaxiOrder> list = taxiOrderMapper.getfjorder(longitude,latitude,(page-1)*20,juli);
        JSONArray arr = new JSONArray();
        for(int i=0;i<list.size();i++){
            JSONObject org = new JSONObject();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            org.put("id",list.get(i).getId());
            org.put("ddId",list.get(i).getDdId());
            org.put("user",infoUserService.getById(list.get(i).getUserId()));
            org.put("driver",infoUserService.getById(list.get(i).getDriverId()));
            org.put("boardingAddress",list.get(i).getBoardingAddress());
            org.put("intoLongitude",list.get(i).getIntoLongitude());
            org.put("intoLatitude",list.get(i).getIntoLatitude());
            org.put("downAddress",list.get(i).getDownAddress());
            org.put("downLongitude",list.get(i).getDownLongitude());
            org.put("downLatitude",list.get(i).getIntoLatitude());
            org.put("distance",list.get(i).getDistance());
            org.put("state",list.get(i).getState());
            org.put("taxiType",list.get(i).getTaxiType());
            org.put("releaseId",list.get(i).getReleaseId());
            org.put("orderTime",sdf.format(list.get(i).getOrderTime()));
            org.put("boardingTime",list.get(i).getBoardingTime());
            org.put("alightingTime",list.get(i).getAlightingTime());
            org.put("appointmentTime",list.get(i).getAppointmentTime());
            org.put("fare",list.get(i).getFare());
            org.put("highwayCosts",list.get(i).getHighwayCosts());
            org.put("amount",list.get(i).getAmount());
            org.put("estimatedDuration",list.get(i).getEstimatedDuration());
            org.put("notes",list.get(i).getNotes());
            org.put("coupon",list.get(i).getCoupon());
            arr.add(org);
        }
        return success(MessageUtils.message("no.obtained.success"), arr);

    }

    //修改订单
    @Anonymous
    @RepeatSubmit(interval = 1000, message = "请求过于频繁")
    @PostMapping("/SetTxorder")
    public AjaxResult SetTxorder(@RequestBody TaxiOrder taxiOrder)
    {
        TaxiOrder order = taxiOrderService.getById(taxiOrder.getId());
        if(order==null){
            return error(MessageUtils.message("no.order.not.exist"));
        }else {
            boolean org = taxiOrderService.saveOrUpdate(taxiOrder);
            if(org){
                return success(MessageUtils.message("no.modify.success"));
            }else {
                return error();
            }
        }

    }

    //新增订单
    @SneakyThrows
    @Anonymous
    @Auth
    @RepeatSubmit(interval = 1000, message = "请求过于频繁")
    @PostMapping("/addTxorder")
    public AjaxResult addTxorder(@RequestHeader String token ,@RequestBody TaxiOrder taxiOrder)
    {
        JwtUtil jwtUtil = new JwtUtil();
        String id = jwtUtil.getusid(token);
        DateUtil date = new DateUtil();
        taxiOrder.setUserId(Long.valueOf(id));
        taxiOrder.setReleaseId(Long.valueOf(id));
        taxiOrder.setDdId(date.getTimeMillis().toString());
        int org = taxiOrderService.insertTaxiOrder(taxiOrder);
        if(org==1){
            return success(MessageUtils.message("no.order.place.success"), taxiOrder);
        }else {
            return error();
        }
    }
    /**
     * 查询TaxiOrder列表
     */
    @PreAuthorize("@ss.hasPermi('system:txorder:list')")
    @GetMapping("/list")
    public TableDataInfo list(TaxiOrder taxiOrder)
    {
        startPage();
        List<TaxiOrder> list = taxiOrderService.selectTaxiOrderList(taxiOrder);
        return getDataTable(list);
    }

    /**
     * 导出TaxiOrder列表
     */
    @PreAuthorize("@ss.hasPermi('system:txorder:export')")
    @Log(title = "TaxiOrder", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TaxiOrder taxiOrder)
    {
        List<TaxiOrder> list = taxiOrderService.selectTaxiOrderList(taxiOrder);
        ExcelUtil<TaxiOrder> util = new ExcelUtil<TaxiOrder>(TaxiOrder.class);
        util.exportExcel(response, list, MessageUtils.message("no.export.excel.taxiorder"));
    }

    /**
     * 获取TaxiOrder详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:txorder:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(taxiOrderService.selectTaxiOrderById(id));
    }

    /**
     * 新增TaxiOrder
     */
    @PreAuthorize("@ss.hasPermi('system:txorder:add')")
    @Log(title = "TaxiOrder", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TaxiOrder taxiOrder)
    {
        return toAjax(taxiOrderService.insertTaxiOrder(taxiOrder));
    }

    /**
     * 修改TaxiOrder
     */
    @PreAuthorize("@ss.hasPermi('system:txorder:edit')")
    @Log(title = "TaxiOrder", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TaxiOrder taxiOrder)
    {
        return toAjax(taxiOrderService.updateTaxiOrder(taxiOrder));
    }

    /**
     * 删除TaxiOrder
     */
    @PreAuthorize("@ss.hasPermi('system:txorder:remove')")
    @Log(title = "TaxiOrder", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(taxiOrderService.deleteTaxiOrderByIds(ids));
    }
}
