package com.ozs.web.controller.accountmanagment;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ozs.common.annotation.Log;
import com.ozs.common.core.controller.BaseController;
import com.ozs.common.core.domain.AjaxResult;
import com.ozs.common.enums.BusinessType;
import com.ozs.common.utils.ChineseToPingyin;
import com.ozs.common.utils.StringUtils;
import com.ozs.common.utils.file.FileUtils;
import com.ozs.common.utils.poi.ExcelUtil;
import com.ozs.entity.BaseTerminal;
import com.ozs.entity.BaseVehicle;
import com.ozs.entity.CameraTree;
import com.ozs.entity.VehiclePosition;
import com.ozs.entity.VehicleTree;
import com.ozs.entity.vo.BaseVehicleTerminalVo;
import com.ozs.entity.vo.BaseVehicleVo;
import com.ozs.entity.vo.VehicleTreeVo;
import com.ozs.service.BaseDeviceDynamicManagementService;
import com.ozs.service.BaseVehicleService;
import com.ozs.service.VehiclePositionService;
import com.ozs.system.service.DataScoreUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 机车信息表 前端控制器
 * </p>
 *
 * @author ozs
 * @since 2023-04-11
 */
@RestController
@RequestMapping("/baseVehicle")
@Slf4j
public class BaseVehicleController extends BaseController {

    @Autowired
    private BaseVehicleService baseVehicleService;
    @Resource
    BaseDeviceDynamicManagementService baseDeviceDynamicManagementService;
    @Autowired
    private VehiclePositionService vehiclePositionService;
    @Autowired
    private DataScoreUtil dataScoreUtil;

    public static void main(String[] args) {
        System.out.println(new Date().getTime());
    }

    /**
     * 车载终端挂载列表
     *
     * @param baseVehicleVo
     * @return
     */
    @ApiOperation(value = "车载终端挂载列表")
    @PostMapping("/vehicleTerminal")
    @Log(title = "机车信息管理", businessType = BusinessType.SELECT)
    public AjaxResult vehicleTerminal(@RequestBody BaseVehicleVo baseVehicleVo) {
        if (StringUtils.isEmptySunhh(baseVehicleVo) || StringUtils.isEmptySunhh(baseVehicleVo.getVehicleCode())) {
            return AjaxResult.error("机车编码不能为空！");
        }
        IPage<BaseVehicleTerminalVo> baseVehicleTerminalVoIPage = baseVehicleService.vehicleTerminal(baseVehicleVo);
        return AjaxResult.success(baseVehicleTerminalVoIPage);
    }

    /**
     * 机车是否挂载终端
     *
     * @param baseVehicleVo
     * @return
     */
    @ApiOperation(value = "机车是否挂载终端")
    @PostMapping("/isMount")
    @Log(title = "机车信息管理", businessType = BusinessType.SELECT)
    public AjaxResult isMount(@RequestBody BaseVehicleVo baseVehicleVo) {
        if (StringUtils.isEmptySunhh(baseVehicleVo) || StringUtils.isEmptySunhh(baseVehicleVo.getVehicleCode())) {
            return AjaxResult.error("机车编码不能为空！");
        }
        Boolean isMount = baseVehicleService.isMount(baseVehicleVo);
        return AjaxResult.success(isMount);
    }

    /**
     * 车载终端挂载 保存
     *
     * @param baseTerminal
     * @return
     */
    @ApiOperation(value = "车载终端挂载 保存")
    @PostMapping("/vehicleTerminalAdd")
    @Log(title = "机车信息管理", businessType = BusinessType.INSERT)
    public AjaxResult vehicleTerminalAdd(@RequestBody BaseTerminal baseTerminal) {
        if (StringUtils.isEmptySunhh(baseTerminal) || StringUtils.isEmptySunhh(baseTerminal.getVehicleCode())
                || StringUtils.isEmptySunhh(baseTerminal.getTerminalCode())) {
            return AjaxResult.error("机车编码、终端编码不能为空！");
        }
        return baseVehicleService.vehicleTerminalAdd(baseTerminal, getUserId());
    }

    /**
     * 机车信息表 分页查询
     *
     * @param baseVehicle
     * @return
     */
    @ApiOperation(value = "机车信息表 分页查询")
    @PostMapping("/vehicleList")
    @Log(title = "机车信息管理", businessType = BusinessType.SELECT)
    public AjaxResult vehicleList(@RequestBody BaseVehicleVo baseVehicle) {
        IPage<BaseVehicle> baseVehicleList = baseVehicleService.vehicleList(baseVehicle);
        return AjaxResult.success(baseVehicleList);
    }

    /**
     * 机车信息表 详情
     *
     * @param baseVehicle
     * @return
     */
    @ApiOperation(value = "机车信息表 详情")
    @PostMapping("/vehicleDetails")
    @Log(title = "机车信息管理", businessType = BusinessType.SELECT)
    public AjaxResult vehicleDetails(@RequestBody BaseVehicle baseVehicle) {
        if (StringUtils.isEmptySunhh(baseVehicle) || StringUtils.isEmptySunhh(baseVehicle.getId())) {
            return AjaxResult.error("机车id不能为空！");
        }
        return baseVehicleService.vehicleDetails(baseVehicle);
    }

    /**
     * 机车信息表 新增
     *
     * @param baseVehicle
     * @return
     */
    @ApiOperation(value = "机车信息表 新增")
    @PostMapping("/vehicleAdd")
    @Log(title = "机车信息管理", businessType = BusinessType.INSERT)
    public AjaxResult vehicleAdd(@RequestBody BaseVehicle baseVehicle) {
        if (StringUtils.isEmptySunhh(baseVehicle) || StringUtils.isEmptySunhh(baseVehicle.getVehicleName())
                || StringUtils.isEmptySunhh(baseVehicle.getVehicleCode())) {
            return AjaxResult.error("机车名称、机车编码不能为空！");
        }
        return baseVehicleService.vehicleAdd(baseVehicle, getUserId());
    }

    /**
     * 机车信息表 修改
     *
     * @param baseVehicle
     * @return
     */
    @ApiOperation(value = "机车信息表 修改")
    @PostMapping("/vehicleUpdate")
    @Log(title = "机车信息管理", businessType = BusinessType.UPDATE)
    public AjaxResult vehicleUpdate(@RequestBody BaseVehicle baseVehicle) {
        if (StringUtils.isEmptySunhh(baseVehicle) || StringUtils.isEmptySunhh(baseVehicle.getId())) {
            return AjaxResult.error("修改ID不能为空！");
        }
        return baseVehicleService.vehicleUpdate(baseVehicle, getUserId());
    }

    /**
     * 机车信息表 删除
     *
     * @param ids
     * @return
     */
    @ApiOperation(value = "机车信息表 删除")
    @DeleteMapping("/vehicleDelete/{ids}")
    @Log(title = "机车信息管理", businessType = BusinessType.DELETE)
    public AjaxResult vehicleDelete(@PathVariable List<Long> ids) {
        if (StringUtils.isEmptySunhh(ids)) {
            return AjaxResult.error("删除ID不能为空！");
        }
        boolean delete = baseVehicleService.removeByIds(ids);
        if (delete) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }

    /**
     * 机车信息导入
     *
     * @param file
     * @param updateSupport
     * @return
     * @throws Exception
     */
    @ApiOperation("机车信息导入")
    @PostMapping("/importBaseVehicle")
    @Log(title = "机车信息管理", businessType = BusinessType.IMPORT)
    public AjaxResult importBaseVehicle(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<BaseVehicle> util = new ExcelUtil<BaseVehicle>(BaseVehicle.class);
        List<BaseVehicle> accountManageList = util.importExcel(file.getInputStream());
        String message = baseVehicleService.importBaseVehicle(accountManageList, updateSupport, getUserId());
        return AjaxResult.success(message);
    }

    /**
     * 机车信息导出
     *
     * @param response
     */
    @ApiOperation("机车信息导出")
    @PostMapping("/exportBaseVehicle")
    @Log(title = "机车信息管理", businessType = BusinessType.EXPORT)
    public void exportBaseVehicle(HttpServletResponse response, @RequestBody BaseVehicle baseVehicle) {
        List<BaseVehicle> baseVehicleList = baseVehicleService.exportBaseVehicle(baseVehicle);
        ExcelUtil<BaseVehicle> util = new ExcelUtil<>(BaseVehicle.class);
        util.exportExcel(response, baseVehicleList, "机车信息台账数据");
    }

    /**
     * 机车信息模板下载
     *
     * @param response
     */
    @ApiOperation("机车信息模板下载")
    @GetMapping("/downloaExcel")
    @Log(title = "机车信息管理", businessType = BusinessType.OTHER)
    public void downloadZip(HttpServletResponse response) {
        try {
            InputStream resourceAsStream = this.getClass().getResourceAsStream("/template/BaseVehicle.xlsx");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, "机车信息模板.xlsx");
            FileUtils.writeBytesByInput(resourceAsStream, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 首页--机车树结构
     * 机车行驶日志中有线路编码
     * 根据机车在行驶日志中记录的最后时间
     * <p>
     * 获取机车列表和线路编码,组成树结构
     */
    @ApiOperation("视频服务树形结构")
    @PostMapping("/vehicleTree")
    @Log(title = "相机台账管理", businessType = BusinessType.OTHER)
    public AjaxResult vehicleTree(@RequestBody VehicleTreeVo vehicleTreeVo) {

        vehicleTreeVo = (VehicleTreeVo) dataScoreUtil.setDataScore(getUserId(), vehicleTreeVo);
        int count = 0;
        if (!ObjectUtils.isEmpty(vehicleTreeVo.getMils())) {
            vehicleTreeVo.setMils(vehicleTreeVo.getMils() * 1000);
        }
        VehicleTree vehicleTree = baseDeviceDynamicManagementService.vehicleTree(vehicleTreeVo);
        List<VehicleTree> children = vehicleTree.getChildren();
        children.sort(new Comparator<VehicleTree>() {
            @Override
            public int compare(VehicleTree o1, VehicleTree o2) {
                String name1 = ChineseToPingyin.convertHanziToPinyin(o1.getName());
                String substring1 = name1.substring(0, 1);
                String name2 = ChineseToPingyin.convertHanziToPinyin(o2.getName());
                String substring2 = name2.substring(0, 1);
                return substring1.compareTo(substring2);
            }
        });


        for (VehicleTree child : children) {
            List<VehicleTree> children1 = child.getChildren();
            children1.sort(new Comparator<VehicleTree>() {
                @Override
                public int compare(VehicleTree o1, VehicleTree o2) {
                    int i = o1.getMileage() - o2.getMileage();
                    if (i == 0) {
                        String[] split = o1.getName().split("-");
                        return "上行".equals(split[1]) ? -1 : 1;
                    } else {
                        return i;
                    }
                }
            });
            for (VehicleTree tree : children1) {
                List<VehicleTree> children2 = tree.getChildren();
                if (children2.size() < 2) {
                    String code = children2.get(0).getCode();
                    tree.setCode(code);
                    children2.remove(0);
                } else {
                    for (VehicleTree vehicleTree1 : children2) {
                        count = count + 1;
                        vehicleTree1.setName("相机" + count);
                    }
                    count = 0;
                }
            }
        }
        return success(vehicleTree);
    }

    /**
     * 机车信息表 （首页地图中的机车信息）
     *
     * @return
     */
    @ApiOperation(value = "机车信息表 列表查询")
    @GetMapping("/vehicleList")
    @Log(title = "机车信息管理", businessType = BusinessType.SELECT)
    public AjaxResult vehicleList() {
        return AjaxResult.success(baseVehicleService.vehicleList());
    }
}

