package com.sckw.fleet.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sckw.core.exception.BusinessException;
import com.sckw.core.exception.CustomPromptException;
import com.sckw.core.exception.SystemException;
import com.sckw.core.model.constant.Global;
import com.sckw.core.model.page.PageHelperUtil;
import com.sckw.core.model.page.PageResult;
import com.sckw.core.utils.CollectionUtils;
import com.sckw.core.utils.StringUtils;
import com.sckw.core.web.constant.HttpStatus;
import com.sckw.core.web.context.LoginUserHolder;
import com.sckw.core.web.response.HttpResult;
import com.sckw.excel.utils.ExcelUtil;
import com.sckw.fleet.model.dto.GpsByTruckNoDto;
import com.sckw.fleet.model.dto.KwfTransportLicenseDto;
import com.sckw.fleet.model.dto.KwfTruckDto;
import com.sckw.fleet.model.dto.KwfTruckLicenseDto;
import com.sckw.fleet.model.vo.KwfTruckDetailVo;
import com.sckw.fleet.model.vo.KwfTruckVo;
import com.sckw.fleet.service.KwfTruckService;
import com.sckw.system.api.RemoteSystemService;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;

/**
 * @author zk
 * @desc 车辆
 * @date 2023/7/6 0006
 */
@RestController
@RequestMapping("/kwfTruck")
public class KwfTruckController {

    @Autowired
    KwfTruckService truckService;
    @DubboReference(version = "1.0.0", group = "design", check = false)
    private RemoteSystemService remoteSystemService;

    /**
     * @param id 主键ID
     * @desc 根据主键查询
     * @author zk
     * @date 2023/7/6
     **/
    @GetMapping("/detail")
    public HttpResult selectByKey(Long id) throws SystemException {
        //车辆信息
        KwfTruckDetailVo truckDetailVo = truckService.detail(id);
        return HttpResult.ok(truckDetailVo);
    }

    /**
     * @param truckNo 车牌号
     * @desc 根据车牌号查询
     * @author zk
     * @date 2023/7/18
     **/
    @GetMapping("/findByTruckNo")
    public HttpResult selectByKey(String truckNo) throws SystemException {
        if (StringUtils.isBlank(truckNo)) {
            return HttpResult.error("车牌号不能为空！");
        }

        Long id = null;
        List<Map<String, Object>> trucks = truckService.findList(new HashMap<>(Global.NUMERICAL_SIXTEEN){{ put("wholeTruckNo", truckNo); }});
        if (com.sckw.core.utils.CollectionUtils.isEmpty(trucks)) {
            return HttpResult.ok();
        } else {
            Map<String, Object> truck = trucks.get(0);
            if (StringUtils.isBlank(truck.get("id"))){
                return HttpResult.ok();
            }
            id = Long.parseLong(String.valueOf(truck.get("id")));
        }

        //车辆信息
        KwfTruckDetailVo truckDetailVo = truckService.detail(id);
        return HttpResult.ok(truckDetailVo);
    }

    /**
     * @param params
     * @desc 统计
     * @author zk
     * @date 2023/7/6
     **/
    @PostMapping("/statistics")
    public HttpResult statistics(@RequestBody Map<String, Object> params) throws SystemException {
        Map countMaps = truckService.statistics(params);
        return HttpResult.ok(countMaps);
    }

    /**
     * @param params {page：页数、pageSize：每页条数、。。。}
     * @desc 分页查询
     * @author zk
     * @date 2023/7/6
     **/
    @PostMapping("/select")
    public HttpResult findPage(@RequestBody Map<String, Object> params) throws SystemException {
        // 设置分页参数
        PageHelper.startPage(PageResult.getPage(params), PageResult.getPageSize(params));
        List<KwfTruckVo> list = truckService.findPage(params);
        PageResult pageResult = PageHelperUtil.getPageResult(new PageInfo<>(list));
        return HttpResult.ok(pageResult);
    }

    /**
     * @param params {。。。}
     * @desc 查询
     * @author zk
     * @date 2023/7/6
     **/
    @PostMapping("/findList")
    public HttpResult findList(@RequestBody Map<String, Object> params) throws SystemException {
        params.put("entId", LoginUserHolder.getEntId());
        return HttpResult.ok(truckService.findList(params));
    }

    /**
     * @param params 查询参数
     * @desc 车辆档案-导出
     * @author zk
     * @date 2023/07/11
     **/
    @PostMapping(value = "/export", produces = MediaType.APPLICATION_JSON_VALUE)
    public void export(@RequestBody Map<String, Object> params, HttpServletResponse response) {
        /**查询数据**/
        List<KwfTruckVo> trucks = truckService.findPage(params);

        if (CollectionUtils.isEmpty(trucks)) {
            throw new CustomPromptException(HttpStatus.SUCCESS_CODE, "暂无数据，请确认！");
        }
        ExcelUtil.downData(response, KwfTruckVo.class, trucks);
    }

    /**
     * @param file 导入文件
     * @desc 导入
     * @author zk
     * @date 2023/07/11
     **/
    @PostMapping("/import")
    public HttpResult importExcel(@RequestParam("file") MultipartFile file) {
        return truckService.importExcel(file);
    }

    /**
     * @param params 新增参数
     * @return HttpResult
     * @desc 新增用户
     * @author czh
     * @date 2023/6/14
     */
    @PostMapping("/add")
    public HttpResult add(@Valid @RequestBody KwfTruckDto params) throws SystemException{
        return truckService.add(params);
    }

    /**
     * @param params {}
     * @desc 更新
     * @author zk
     * @date 2023/5/30
     **/
    @PostMapping("/update")
    public HttpResult update(@Valid @RequestBody KwfTruckDto params) throws SystemException {
        return truckService.update(params);
    }

    /**
     * @param {ids：主键ID（多个以逗号隔开）}
     * @desc 删除
     * @author zk
     * @date 2023/7/7
     **/
    @DeleteMapping("/dels")
    public HttpResult del(@RequestParam String ids) throws SystemException {
        return truckService.del(ids);
    }

    /**
     * @param params {}
     * @desc 车辆行驶证信息编辑
     * @author zk
     * @date 2023/7/7
     **/
    @PostMapping("/truckLicenseEdit")
    public HttpResult truckLicenseEdit(@Valid @RequestBody KwfTruckLicenseDto params) throws SystemException {
        return truckService.truckLicenseEdit(params);
    }

    /**
     * @param params {}
     * @desc 车辆道路运输许可证编辑
     * @author zk
     * @date 2023/7/7
     **/
    @PostMapping("/transportLicenseEdit")
    public HttpResult transportLicenseEdit(@Valid @RequestBody KwfTransportLicenseDto params) throws SystemException {
        return truckService.transportLicenseEdit(params);
    }

    /**
     * @desc 企业车辆统计
     * @author zk
     * @date 2023/9/18
     **/
    @GetMapping("/truckStatistics")
    public HttpResult truckStatistics() {
        return HttpResult.ok(truckService.truckStatistics());
    }

    /**
     * @param params {truckNo 車牌號}
     * @desc 车辆查询(业务关联+归属车辆)
     * @author zk
     * @date 2023/7/26
     **/
    @PostMapping("/findTruck")
    public HttpResult findTruck(@RequestBody Map<String, Object> params) {
        return HttpResult.ok(truckService.findTruck(params));
    }

    /**
     * @param truckNos 車牌號集
     * @desc 车辆查询GPS(业务关联 + 归属车辆)
     * @author zk
     * @date 2023/7/26
     **/
    @PostMapping("/findTruckGps")
    public HttpResult findTruckGps(@RequestBody List<String> truckNos) {
        if (CollectionUtils.isEmpty(truckNos)) {
            return HttpResult.ok();
        }

        return HttpResult.ok(truckService.findTruckGps(truckNos));
    }

    /**
     * @param params {truckNos 車牌號集, startTime 開始實際, endTime 結束時間}
     * @desc 车辆查询GPS(通过车牌号查询)
     * @author zk
     * @date 2023/7/26
     **/
    @PostMapping("/findGpsByTruckNo")
    public HttpResult findGpsByTruckNo(@RequestBody @Valid GpsByTruckNoDto params) {
        /*Long hours = (params.getEndTime().getTime() - params.getStartTime().getTime()) /1000/60;
        List data = new ArrayList();
        String str = new KwfTruckController().ReadFile();
        JSONArray array = JSON.parseArray(str);
        for (int i=0; i<array.size(); i++) {
            int aaa = new Random().nextInt(10) / 3;
            int bbb = new Random().nextInt(10) / 4;
            JSONObject obj = array.getJSONObject(i);
            obj.put("truckNo", params.getTruckNo());
            obj.put("businessStatus", aaa == 0 ? 0 : 1);
            obj.put("runStatus", bbb == 0 ? 0 : bbb == 1 ? 1 : 2);
            data.add(obj);
        }*/
        return HttpResult.ok(truckService.queryLocateTrack(params));
    }

    /**
     * @desc 获取JSON文件数据（暂时使用）
     * @author zk
     * @date 2023/8/2
     **/
    public String ReadFile(){
        BufferedReader reader = null;
        String laststr = "";
        try{
            InputStream fileInputStream = getClass().getClassLoader().getResourceAsStream("GPS.json");
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
            reader = new BufferedReader(inputStreamReader);
            String tempString = null;
            while((tempString = reader.readLine()) != null){
                laststr += tempString;
            }
            reader.close();
        }catch(IOException e){
            e.printStackTrace();
        }finally{
            if(reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return laststr;
    }

    /**
     * @param truckNo 车牌号
     * @desc 车牌号查询车辆关联数据
     * @author zk
     * @date 2023/8/2
     **/
    @GetMapping("/findDetailByTruckNo")
    public HttpResult findDetailByTruckNo(@RequestParam String truckNo) {
        if (StringUtils.isBlank(truckNo)) {
            return HttpResult.error("车牌号不能为空！");
        }
        /*Map<String, Object> detail = new HashMap<>(Global.NUMERICAL_SIXTEEN);
        detail.put("truckNo", truckNo);
        detail.put("driverName", "赵先生");
        detail.put("driverPhone", "17358629955");
        detail.put("firmName", "东旭物流有限公司");
        detail.put("detailAddress", "四川省成都市xxx路10号");
        detail.put("lat", "29.48"+new Random().nextInt(10000));
        detail.put("lng", "103.53"+new Random().nextInt(10000));
        detail.put("speed", new Random().nextInt(100));
        detail.put("gpsTime", DateUtils.getCurrentTime());*/
        return HttpResult.ok(truckService.findDetailByTruckNo(truckNo));
    }

}
