package com.sckw.fleet.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
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.StringUtils;
import com.sckw.core.web.constant.HttpStatus;
import com.sckw.core.web.context.LoginUserHolder;
import com.sckw.core.web.response.BaseResult;
import com.sckw.core.web.response.HttpResult;
import com.sckw.excel.utils.ExcelUtil;
import com.sckw.fleet.model.dto.*;
import com.sckw.fleet.model.request.AssociatedTrackAddRequest;
import com.sckw.fleet.model.request.AssociatedTrackRequest;
import com.sckw.fleet.model.request.DriverAssociatedTruckSaveRequest;
import com.sckw.fleet.model.vo.KwfDriverAssociatedTrackVO;
import com.sckw.fleet.model.vo.KwfDriverDetailVo;
import com.sckw.fleet.model.vo.KwfDriverVo;
import com.sckw.fleet.service.KwfDriverService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * @author zk
 * @desc 司机
 * @date 2023/7/6 0006
 */
@RestController
@RequestMapping("/kwfDriver")
@Tag(name = "司机管理", description = "提供司机相关操作接口")
public class KwfDriverController {

    @Autowired
    KwfDriverService driverService;

    /**
     * @param id 主键ID
     * @desc 根据主键查询
     * @author zk
     * @date 2023/7/6
     **/
    @GetMapping("/detail")
    public HttpResult selectByKey(Long id) throws SystemException {
        //司机信息
        KwfDriverDetailVo driverDetailVo = driverService.detail(id);
        return HttpResult.ok(driverDetailVo);
    }

    /**
     * @param phone 司机手机号
     * @desc 根据司机手机号查询
     * @author zk
     * @date 2023/7/18
     **/
    @GetMapping("/findByPhone")
    public HttpResult findByPhone(String phone) throws SystemException {
        if (StringUtils.isBlank(phone)) {
            return HttpResult.error("手机号不能为空！");
        }

        //获取司机信息
        Long id = null;
        List<Map<String, Object>> drivers = driverService.findList(new HashMap<>(Global.NUMERICAL_SIXTEEN){{ put("phone", phone); }});
        if (com.sckw.core.utils.CollectionUtils.isEmpty(drivers)) {
            return HttpResult.ok();
        } else {
            Map<String, Object> driver = drivers.get(0);
            if (StringUtils.isBlank(driver.get("id"))){
                return HttpResult.ok();
            }
            id = Long.parseLong(String.valueOf(driver.get("id")));
        }

        //司机信息
        KwfDriverDetailVo driverDetailVo = driverService.detail(id);
        return HttpResult.ok(driverDetailVo);
    }

    /**
     * @param params
     * @desc 统计
     * @author zk
     * @date 2023/7/6
     **/
    @PostMapping("/statistics")
    public HttpResult statistics(@RequestBody Map<String, Object> params) throws SystemException {
        Map countMaps = driverService.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<KwfDriverVo> list = driverService.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(driverService.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<KwfDriverVo> drivers = driverService.findPage(params);

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

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

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

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

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

    /**
     * @param params {}
     * @desc 司机身份证信息编辑
     * @author zk
     * @date 2023/7/7
     **/
    @PostMapping("/driverCardEdit")
    public HttpResult driverCardEdit(@Valid @RequestBody KwfDriverCardDto params) throws SystemException {
        return driverService.driverCardEdit(params);
    }

    /**
     * @param params {}
     * @desc 司机驾驶证信息编辑
     * @author zk
     * @date 2023/7/7
     **/
    @PostMapping("/driverLicenseEdit")
    public HttpResult driverLicenseEdit(@Valid @RequestBody KwfDriverLicenseDto params) throws SystemException {
        return driverService.driverLicenseEdit(params);
    }

    /**
     * @param params {}
     * @desc 司机从业资格证信息编辑
     * @author zk
     * @date 2023/7/7
     **/
    @PostMapping("/driverQualiEdit")
    public HttpResult driverQualiEdit(@Valid @RequestBody KwfDriverQualificationDto params) throws SystemException {
        return driverService.driverQualificationEdit(params);
    }

    /**
     * @param {password 旧密码、newPassword 新密码、account 账号}
     * @desc 修改密码
     * @author zk
     * @date 2023/07/11
     **/
    @PostMapping("/updatePassword")
    public HttpResult updatePassword(@Valid @RequestBody UpdatePasswordDto params) {
        return driverService.updatePassword(params);
    }

    /**
     * @param {driverId 司机主键id/登陆后缓存中取、phone 手机号、captcha 短信验证码}
     * @desc 更换手机号
     * @author zk
     * @date 2023/07/11
     **/
    @PostMapping("/replacePhone")
    public HttpResult replacePhone(@Valid @RequestBody ReplacePhoneDto params) {
        return driverService.replacePhone(params);
    }

    /**
     * @param {account 账号、password 密码、captcha 验证码}
     * @desc 忘记密码
     * @author zk
     * @date 2023/08/15
     **/
    @PostMapping("/forgetPassword")
    public HttpResult forgetPassword(@RequestHeader(name = "System-Type") int systemType,
                                     @RequestHeader(name = "Client-Type") String clientType,
                                     @RequestBody @Valid ForgetPasswordDto params) {
        return driverService.forgetPassword(params);
    }

    /**
     * @desc 企业司机统计
     * @author zk
     * @date 2023/9/18
     **/
    @GetMapping("/driverStatistics")
    public HttpResult driverStatistics() {
        return HttpResult.ok(driverService.driverStatistics());
    }


    /**
     * @param params 新增参数
     * @return HttpResult
     * @desc 绑定车辆
     * @author czh
     * @date 2023/6/14
     */
    @PostMapping("/bindTruck")
    public HttpResult bindTruck(@RequestBody @Valid KwfBindTruckDto params) {
        return driverService.bindTruck(params);
    }

    /**
     * 查询司机关联车辆信息
     *
     * @param param
     * @return
     */
    @Operation(summary = "查询司机关联车辆信息", description = "查询司机关联车辆列表")
    @PostMapping("/queryAssociatedTrack")
    public BaseResult<List<KwfDriverAssociatedTrackVO>> queryAssociatedTrack(@RequestBody @Valid AssociatedTrackRequest param){
        List<KwfDriverAssociatedTrackVO> kwfDriverAssociatedTrackVOS = driverService.queryAssociatedTrack(param);
        return BaseResult.success(kwfDriverAssociatedTrackVOS);
    }

    /**
     * 新增司机关联车辆
     *
     * @param param
     * @return
     */
    @Operation(summary = "新增司机关联车辆", description = "新增司机关联车辆")
    @PostMapping("/addAssociatedTrack")
    public BaseResult addAssociatedTrack(@RequestBody @Valid AssociatedTrackAddRequest param){
        driverService.addAssociatedTrack(param);
        return BaseResult.success();
    }

    @Operation(summary = "保存车辆并关联司机", description = "保存车辆档案并关联司机")
    @PostMapping("/saveTruckAndAssociate")
    public BaseResult saveTruckAndAssociate(@RequestBody @Valid DriverAssociatedTruckSaveRequest param){
        driverService.saveTruckAndAssociate(param);
        return BaseResult.success();
    }

    /**
     * 删除司机关联车辆
     *
     * @param id
     * @return
     */
    @Operation(summary = "删除司机关联车辆", description = "删除司机关联车辆")
    @PostMapping("/deleteAssociatedTrack")
    public BaseResult deleteAssociatedTrack(@RequestParam Long id){
        driverService.deleteAssociatedTrack(id);
        return BaseResult.success();
    }


    /**
     * 切换关联车辆
     *
     * @param id
     * @return
     */
    @Operation(summary = "切换关联车辆", description = "切换关联车辆")
    @PostMapping("/switchAssociatedTrack")
    public BaseResult switchAssociatedTrack(@RequestParam Long id){
        driverService.switchAssociatedTrack(id);
        return BaseResult.success();
    }

    /**
     * 解绑车辆
     *
     * @param param
     * @return
     */
    @Operation(summary = "解绑车辆", description = "解绑车辆")
    @PostMapping("/unbindTruck")
    public BaseResult unbindTruck(@RequestBody @Valid KwfBindTruckDto param){
        driverService.unbindTruck(param);
        return BaseResult.success();
    }


    /**
     * @desc 保存车库
     * @author zk
     * @date 2023/7/6
     **/
    @PostMapping("/saveAssociatedTruck")
    public BaseResult saveAssociatedTruck(@RequestBody SaveAssociatedTruckParam param) {

        driverService.saveAssociatedTruck(param);
        return BaseResult.success();
    }

    @PostMapping("/countDriver")
    public HttpResult countDriver(@RequestParam("entId") Long entId) {
        Integer driverCount = driverService.countDriversByEntId(entId);
        return HttpResult.ok(driverCount);
    }

}
