package com.ruoyi.web.controller.fleet.orderPlan;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.orderPlan.domain.Ftmsorderbills;
import com.ruoyi.orderPlan.domain.Ftmsorderbillscars;
import com.ruoyi.orderPlan.domain.FtmsorderbillscarsExcel;
import com.ruoyi.orderPlan.domain.VehicleLedgerExcel;
import com.ruoyi.orderPlan.service.IftmsorderbillscarsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
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.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 车队派车Controller
 *
 * @author ruoyi
 * @date 2021-02-22
 */
@RestController
@RequestMapping("/fleet/ftmsorderbillscars")
public class ftmsorderbillscarsController extends BaseController {
    @Autowired
    private IftmsorderbillscarsService ftmsorderbillscarsService;

    /**
     * 查询车队派车列表
     */
    @GetMapping("/list")
    public TableDataInfo list(Ftmsorderbillscars ftmsorderbillscars) {
        startPage();
        List<Ftmsorderbillscars> list = ftmsorderbillscarsService.selectftmsorderbillscarsList(ftmsorderbillscars);
        return getDataTable(list);
    }

    /**
     * 查询司机状态跟踪列表
     */
    @PreAuthorize("@ss.hasPermi('fleet:vehicleStatus:query')")
    @GetMapping("/query")
    public Map<String, Object> query(Ftmsorderbills ftmsorderbills) {
        Map<String, Object> map = new HashMap<String,Object>();
        Ftmsorderbills tmsorder = ftmsorderbillscarsService.judgmentFleet(ftmsorderbills);
        startPage();
        List<FtmsorderbillscarsExcel> list = ftmsorderbillscarsService.selectftmsorderbillscarsMapList(tmsorder);
        map.put("dataTable", getDataTable(list));
        map.put("buttonValue", ftmsorderbillscarsService.getButtonValue());
        return map;
    }

    /**
     * 查询司机状态跟踪列表
     */
    @PreAuthorize("@ss.hasPermi('fleet:vehicleStatus:query')")
    @GetMapping("/queryModify")
    public Map<String, Object> queryModify(Ftmsorderbills ftmsorderbills) {
        Map<String, Object> map = new HashMap<String,Object>();
        Ftmsorderbills tmsorder = ftmsorderbillscarsService.judgmentFleet(ftmsorderbills);
        startPage();
        List<FtmsorderbillscarsExcel> list = ftmsorderbillscarsService.selectftmsorderbillscarsMapListModify(tmsorder);
        map.put("dataTable", getDataTable(list));
        //增加是否具有审核资格字段返回
        map.put("isApprove",false);
        List<SysRole> roles = SecurityUtils.getLoginUser().getUser().getRoles();
        for (int i = 0; i < roles.size(); i++) {
            if("FeeRevisionAuditor".equals(roles.get(i).getRoleKey())){
                map.put("isApprove",true);
            }
        }
        return map;
    }

    /**
     * 查询司机状态跟踪列表
     */
    @GetMapping("/wechatQuery")
    public Map<String, Object> wechatQuery(Ftmsorderbills ftmsorderbills) {
        Map<String, Object> map = new HashMap<>();
        Ftmsorderbills tmsorder = ftmsorderbillscarsService.judgmentFleet(ftmsorderbills);
        startPage();
        List<FtmsorderbillscarsExcel> list = ftmsorderbillscarsService.selectftmsorderbillscarsMapList(tmsorder);
        map.put("dataTable", getDataTable(list));
        map.put("buttonValue", ftmsorderbillscarsService.getButtonValue());
        return map;
    }

    /**
     * 查询陆运台账列表信息
     */
    @GetMapping("/queryLedgerList")
    public TableDataInfo queryLedgerList(VehicleLedgerExcel vehicleLedgerExcel) {
        startPage();
        List<VehicleLedgerExcel> list = ftmsorderbillscarsService.queryLedgerList(vehicleLedgerExcel);
        return getDataTable(list);
    }

    /**
     * 导出陆运台账列表信息
     */
    @GetMapping("/ledgerListExport")
    public AjaxResult ledgerListExport(VehicleLedgerExcel vehicleLedgerExcel) {
        List<VehicleLedgerExcel> list = ftmsorderbillscarsService.queryLedgerList(vehicleLedgerExcel);
        ExcelUtil<VehicleLedgerExcel> util = new ExcelUtil<VehicleLedgerExcel>(VehicleLedgerExcel.class);
        return util.exportExcel(list, "陆运台账");
    }

    /**
     * 查询车辆可配载运单
     */
    @GetMapping(value = "/selectStowage")
    public TableDataInfo selectStowage(Ftmsorderbillscars ftmsorderbillscars) {
        startPage();
        List<Map<String, Object>> list = ftmsorderbillscarsService.selectStowageList(ftmsorderbillscars);
        return getDataTable(list);
    }


    /**
     *自动配载
     * @param sourceId 来源ID,待插入数据ID,执行逻辑:插入数据,单据类型为分单,主单号为原来车辆的运单号
     * @param targetId 目标ID,待处理数据ID,执行逻辑:单据类型 变为主单
     * @return
     * dongyongwei 20210713
     */
    @GetMapping("/autoStowage")
    public AjaxResult autoStowage(Long sourceId, Long targetId){
        if(sourceId==null){
            return AjaxResult.error("sourceId不能为空");
        }
        if(targetId==null){
            return AjaxResult.error("targetId不能为空");
        }
        return ftmsorderbillscarsService.autoStowage(sourceId,targetId);
    }

    /**
     * 提交车辆配载
     */
    @PostMapping(value = "/addStowage")
    public AjaxResult addStowage(@RequestBody Ftmsorderbillscars ftmsorderbillscars) {
        if (StringUtils.isNull(ftmsorderbillscars) || StringUtils.isNull(ftmsorderbillscars.getmBillNo())) {
            return AjaxResult.error("未找到查询条件或未找到配载运单号，请确认");
        }
        return ftmsorderbillscarsService.addStowage(ftmsorderbillscars);
    }

    /**
     * 撤销车辆配载
     */
    @GetMapping(value = "/revokeStowage/{id}")
    public AjaxResult revokeStowage(@PathVariable("id") Long id) {
        if (StringUtils.isNull(id)) {
            return AjaxResult.error("未找到查询条件，请确认");
        }
        return ftmsorderbillscarsService.revokeStowage(id);
    }


    /**
     * 根据手机号查询司机的
     * 新订单、本月订单、本月历程、本月运费
     */
//    @PreAuthorize("@ss.hasPermi('fleet:ftmsorderbillscars:query')")
    @GetMapping(value = "/selectDriverPerformance")
    public AjaxResult selectDriverPerformance(SysUser user) {
        if (StringUtils.isNull(user.getPhonenumber()) || "".equals(user.getPhonenumber())) {
            return AjaxResult.error("未找到查询条件，请确认");
        }
        return ftmsorderbillscarsService.selectDriverPerformance(user.getPhonenumber());
    }

    /**
     * 导出车队派车列表
     */
    @PreAuthorize("@ss.hasPermi('fleet:ftmsorderbillscars:export')")
    @Log(title = "车队派车", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    @RepeatSubmit
    public AjaxResult export(Ftmsorderbills ftmsorderbills) {
        Ftmsorderbills tmsorder = ftmsorderbillscarsService.judgmentFleet(ftmsorderbills);
        List<FtmsorderbillscarsExcel> list = ftmsorderbillscarsService.selectftmsorderbillscarsMapList(tmsorder);
        ExcelUtil<FtmsorderbillscarsExcel> util = new ExcelUtil<FtmsorderbillscarsExcel>(FtmsorderbillscarsExcel.class);
        return util.exportExcel(list, "状态跟踪");
    }

    /**
     * 根据派车id查询详细信息
     */
    @PreAuthorize("@ss.hasPermi('fleet:ftmsorderbillscars:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        if (StringUtils.isNull(id)) {
            return AjaxResult.error("未找到查询条件，请确认");
        }
        return AjaxResult.success(ftmsorderbillscarsService.selectftmsorderbillscarsById(id));
    }

    /**
     * 根据司机id查询详细信息
     */
//    @PreAuthorize("@ss.hasPermi('fleet:ftmsorderbillscars:query')")
    @PostMapping(value = "/selectDriver")
    public AjaxResult selectDriver(@RequestBody Ftmsorderbillscars ftmsorderbillscars) {
        if (StringUtils.isNull(ftmsorderbillscars) || StringUtils.isNull(ftmsorderbillscars.getId())) {
            return AjaxResult.error("未找到运单数据，请确认");
        }
        return AjaxResult.success(ftmsorderbillscarsService.selectDriver(ftmsorderbillscars));
    }

    /**
     * 根据司机id查询详细信息(暂存)
     */
//    @PreAuthorize("@ss.hasPermi('fleet:ftmsorderbillscars:query')")
    @PostMapping(value = "/selectDriverModify")
    public AjaxResult selectDriverModify(@RequestBody Ftmsorderbillscars ftmsorderbillscars) {
        if (StringUtils.isNull(ftmsorderbillscars) || StringUtils.isNull(ftmsorderbillscars.getId())) {
            return AjaxResult.error("未找到运单数据，请确认");
        }
        return AjaxResult.success(ftmsorderbillscarsService.selectDriverModify(ftmsorderbillscars));
    }

    /**
     * 司机操作接单/提箱/装卸货/还卸柜/回单操作  保存
     */
//    @PreAuthorize("@ss.hasPermi('fleet:ftmsorderbillscars:edit')")
    @Log(title = "车队派车", businessType = BusinessType.INSERT)
    @PostMapping(value = "/driverSave")
    @RepeatSubmit
    public AjaxResult driverSave(@RequestParam("cars") String cars,
                                 @RequestParam("fees") String fees,
                                 @RequestParam("attachs") String attachs,
                                 @RequestParam("operationType") String operationType) {
        if (StringUtils.isEmpty(cars) || "{}".equals(cars)) {
            return AjaxResult.error("未找到运单数据，请确认");
        }
        if (StringUtils.isEmpty(operationType) || "{}".equals(operationType)) {
            return AjaxResult.error("未找到状态条件，请确认");
        }
        return ftmsorderbillscarsService.driverSave(cars, fees, attachs, operationType);
    }

    /**
     * 司机操作接单/提箱/装卸货/还卸柜/回单操作  提交
     */
//    @PreAuthorize("@ss.hasPermi('fleet:ftmsorderbillscars:edit')")
    @Log(title = "车队派车", businessType = BusinessType.INSERT)
    @PostMapping(value = "/insertDriver")
    @RepeatSubmit
    public AjaxResult insertDriver(@RequestParam("cars") String cars,
                                   @RequestParam("attachs") String attachs,
                                   @RequestParam("operationType") String operationType) {
        if (StringUtils.isEmpty(cars) || "{}".equals(cars)) {
            return AjaxResult.error("未找到运单数据，请确认");
        }
        if (StringUtils.isEmpty(operationType) || "{}".equals(operationType)) {
            return AjaxResult.error("未找到状态条件，请确认");
        }
        return ftmsorderbillscarsService.insertDriver(cars, attachs, operationType);
    }

    /**
     * 状态跟踪提交  提交
     */
//    @PreAuthorize("@ss.hasPermi('fleet:ftmsorderbillscars:edit')")
    @Log(title = "车队派车", businessType = BusinessType.INSERT)
    @PostMapping(value = "/driverSubmit")
    @RepeatSubmit
    public AjaxResult driverSubmit(@RequestParam("cars") String cars,
                                   @RequestParam("fees") String fees,
                                   @RequestParam("attachs") String attachs) {
        if (StringUtils.isEmpty(cars) || "{}".equals(cars)) {
            return AjaxResult.error("未找到运单数据，请确认");
        }
        if (StringUtils.isEmpty(fees) || "[]".equals(fees)) {
            return AjaxResult.error("未找到费用数据，请确认");
        }
        return ftmsorderbillscarsService.driverSubmit(cars, fees, attachs);
    }

    /**
     * 司机操作接单/提箱/装卸货/还卸柜/回单操作  微信提交
     */
    @Log(title = "车队派车", businessType = BusinessType.INSERT)
    @PostMapping(value = "/wechatInsertDriver")
    @RepeatSubmit
    public AjaxResult wechatInsertDriver(@RequestBody String information) {
        if (StringUtils.isEmpty(information)) {
            return AjaxResult.error("未找到查询条件，请确认");
        }
        JSONObject jsonObject = JSONArray.parseObject(information);
        String cars = jsonObject.get("cars").toString();
        String attachs = jsonObject.get("attachs").toString();
        String operationType = jsonObject.get("operationType").toString();
        if (StringUtils.isEmpty(cars) || "{}".equals(cars)) {
            return AjaxResult.error("未找到司机信息，请确认");
        }
        if (StringUtils.isEmpty(operationType)) {
            return AjaxResult.error("未找到状态信息，请确认");
        }
        return ftmsorderbillscarsService.insertDriver(cars, attachs, operationType);
    }

    /**
     * 司机操作接单/提箱/装卸货/还卸柜/回单操作  变更
     */
//    @PreAuthorize("@ss.hasPermi('fleet:ftmsorderbillscars:edit')")
    @Log(title = "车队派车", businessType = BusinessType.INSERT)
    @PostMapping(value = "/operationalChanges")
    @RepeatSubmit
    public AjaxResult operationalChanges(@RequestParam("cars") String cars,
                                         @RequestParam("operationType") String operationType) {
        if (StringUtils.isEmpty(cars) || "{}".equals(cars)) {
            return AjaxResult.error("未找到查询条件，请确认");
        }
        if (StringUtils.isEmpty(operationType)) {
            return AjaxResult.error("未找到状态条件，请确认");
        }
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return ftmsorderbillscarsService.operationalChanges(cars, operationType, loginUser);
    }

    /**
     * 单条车辆安排 变更
     */
//    @PreAuthorize("@ss.hasPermi('fleet:ftmsorderbillscars:edit')")
    @Log(title = "车队派车", businessType = BusinessType.INSERT)
    @PostMapping(value = "/vehicleOperationChanges/{id}")
    @RepeatSubmit
    public AjaxResult vehicleOperationChanges(@PathVariable("id") Long id) {
        if (StringUtils.isNull(id)) {
            return AjaxResult.error("未找到查询条件，请确认");
        }
        return ftmsorderbillscarsService.vehicleOperationChanges(id);
    }

    /**
     * 单条车辆安排变更提交接口
     */
//    @PreAuthorize("@ss.hasPermi('fleet:ftmsorderbillscars:add')")
    @Log(title = "车队派车", businessType = BusinessType.INSERT)
    @PostMapping(value = "/vehicleArrangementChange")
    @RepeatSubmit
    public AjaxResult vehicleArrangementChange(@RequestBody Ftmsorderbillscars ftmsorderbillscars) {
        if (StringUtils.isNull(ftmsorderbillscars.getpId())) {
            return AjaxResult.error("未找到调度安排信息");
        }
        String status = "change";
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return ftmsorderbillscarsService.vehicleArrangement(status, ftmsorderbillscars, loginUser);
    }

    /**
     * 单条车辆安排提交接口
     */
//    @PreAuthorize("@ss.hasPermi('fleet:ftmsorderbillscars:add')")
    @Log(title = "车队派车", businessType = BusinessType.INSERT)
    @PostMapping(value = "/vehicleArrangementAddStowage")
    @RepeatSubmit
    public AjaxResult vehicleArrangementAddStowage(@RequestBody Ftmsorderbillscars ftmsorderbillscars) {
        if (StringUtils.isNull(ftmsorderbillscars.getpId())) {
            return AjaxResult.error("未找到调度安排信息");
        }
        String status = "addStowage";
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return ftmsorderbillscarsService.vehicleArrangement(status, ftmsorderbillscars, loginUser);
    }

    /**
     * 单条车辆安排提交接口
     */
//    @PreAuthorize("@ss.hasPermi('fleet:ftmsorderbillscars:add')")
    @Log(title = "车队派车", businessType = BusinessType.INSERT)
    @PostMapping(value = "/vehicleArrangementAdd")
    @RepeatSubmit
    public AjaxResult vehicleArrangementAdd(@RequestBody Ftmsorderbillscars ftmsorderbillscars) {
        if (StringUtils.isNull(ftmsorderbillscars.getpId())) {
            return AjaxResult.error("未找到调度安排信息");
        }
        String status = "add";
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return ftmsorderbillscarsService.vehicleArrangement(status, ftmsorderbillscars, loginUser);
    }

    /**
     * 单条车辆安排撤销接口
     */
//    @PreAuthorize("@ss.hasPermi('fleet:ftmsorderbillscars:edit')")
    @PostMapping(value = "/vehicleArrangementRevokeStowage")
    @RepeatSubmit
    public AjaxResult vehicleArrangementRevokeStowage(@RequestBody Ftmsorderbillscars ftmsorderbillscars) {
        if (StringUtils.isNull(ftmsorderbillscars.getpId())) {
            return AjaxResult.error("未找到调度安排信息");
        }
        String status = "revokeStowage";
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return ftmsorderbillscarsService.vehicleArrangement(status, ftmsorderbillscars, loginUser);
    }

    /**
     * 单条车辆安排撤销接口
     */
//    @PreAuthorize("@ss.hasPermi('fleet:ftmsorderbillscars:edit')")
    @PostMapping(value = "/vehicleArrangementRevoke")
    @RepeatSubmit
    public AjaxResult vehicleArrangementRevoke(@RequestBody Ftmsorderbillscars ftmsorderbillscars) {
        if (StringUtils.isNull(ftmsorderbillscars.getpId())) {
            return AjaxResult.error("未找到调度安排信息");
        }
        String status = "revoke";
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return ftmsorderbillscarsService.vehicleArrangement(status, ftmsorderbillscars, loginUser);
    }

    /**
     * 单条车辆安排删除接口
     */
//    @PreAuthorize("@ss.hasPermi('fleet:ftmsorderbillscars:remove')")
    @PostMapping(value = "/vehicleArrangementRemove")
    @RepeatSubmit
    public AjaxResult vehicleArrangementRemove(@RequestBody Ftmsorderbillscars ftmsorderbillscars) {
        if (StringUtils.isNull(ftmsorderbillscars.getpId())) {
            return AjaxResult.error("未找到调度安排信息");
        }
        String status = "remove";
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return ftmsorderbillscarsService.vehicleArrangement(status, ftmsorderbillscars, loginUser);
    }

    /**
     * 暂存车队派车
     */
//    @PreAuthorize("@ss.hasPermi('fleet:ftmsorderbillscars:add')")
    @Log(title = "车队派车", businessType = BusinessType.INSERT)
    @PostMapping(value = "/save")
    @RepeatSubmit
    public AjaxResult save(@RequestParam("plans") String plans,
                           @RequestParam("attachs") String attachs,
                           @RequestParam("fees") String fees,
                           @RequestParam("cars") String cars) {
        if (StringUtils.isNull(plans) || "{}".equals(plans)) {
            return AjaxResult.error("未找到调度数据，请确认");
        }
        String billType = "save";
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return ftmsorderbillscarsService.insertftmsorderbillscars(plans, attachs, fees, cars, billType, loginUser);
    }

    /**
     * 车队派车提交
     */
//    @PreAuthorize("@ss.hasPermi('fleet:ftmsorderbillscars:add')")
    @Log(title = "车队派车", businessType = BusinessType.INSERT)
    @PostMapping(value = "/add")
    @RepeatSubmit
    public AjaxResult add(@RequestParam("plans") String plans,
                          @RequestParam("attachs") String attachs,
                          @RequestParam("fees") String fees,
                          @RequestParam("cars") String cars) {
        if (StringUtils.isNull(plans) || "{}".equals(plans)) {
            return AjaxResult.error("未找到调度数据，请确认");
        }
        if (StringUtils.isNull(cars) || "[]".equals(cars)) {
            return AjaxResult.error("未找到车辆安排数据，请确认");
        }
        String billType = "add";
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return ftmsorderbillscarsService.insertftmsorderbillscars(plans, attachs, fees, cars, billType, loginUser);
    }

    /**
     * 车队派车（大）变更
     */
//    @PreAuthorize("@ss.hasPermi('fleet:ftmsorderbillscars:add')")
    @Log(title = "车队派车", businessType = BusinessType.INSERT)
    @PostMapping(value = "/change/{id}")
    @RepeatSubmit
    public AjaxResult change(@PathVariable("id") Long id) {
        if (StringUtils.isNull(id) || id == 0) {
            return AjaxResult.error("未找到车辆调度数据，请确认");
        }
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return ftmsorderbillscarsService.dispatchChange(id, loginUser);
    }

    /**
     * 修改车队派车
     */
//    @PreAuthorize("@ss.hasPermi('fleet:ftmsorderbillscars:edit')")
    @Log(title = "车队派车", businessType = BusinessType.UPDATE)
    @PutMapping
    @RepeatSubmit
    public AjaxResult edit(@RequestBody Ftmsorderbillscars ftmsorderbillscars) {
        return toAjax(ftmsorderbillscarsService.updateftmsorderbillscars(ftmsorderbillscars));
    }

    /**
     * 删除车队派车
     */
//    @PreAuthorize("@ss.hasPermi('fleet:ftmsorderbillscars:remove')")
    @Log(title = "车队派车", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @RepeatSubmit
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(ftmsorderbillscarsService.deleteftmsorderbillscarsByIds(ids));
    }


}
