/*
 * Author: wangjian
 * 生成controller
 */
package com.tofly.gpsboot.controller.maintain;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.log.annotation.ToFlyAppLog;
import com.tofly.gpsboot.common.Constant;
import com.tofly.gpsboot.common.business.ExcelExportFileTypeEnum;
import com.tofly.gpsboot.controller.BaseController;
import com.tofly.gpsboot.exception.BusinessException;
import com.tofly.gpsboot.service.maintain.RepairorderService;
import com.tofly.gpsboot.strategy.ExcelStrategyContext;
import com.tofly.gpsboot.util.ExcelUtil;
import com.tofly.pojo.maintain.Repairorder;
import com.tofly.pojo.maintain.dto.RepairorderDto;
import com.tofly.pojo.maintain.dto.RepairuserChildDto;
import com.tofly.pojo.maintain.vo.AuxiliarySingleVo;
import com.tofly.pojo.maintain.vo.RepairorderVo;
import com.tofly.pojo.maintain.vo.datail.RepairOrderDetailNewVo;
import com.tofly.pojo.maintain.vo.datail.RepairOrderDetailVo;
import com.tofly.pojo.maintain.vo.datail.RepairOrderOverVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 抢维修工单信息表
 *
 * @author admin
 * @date Tue Apr 06 00:00:00 CST 2021
 */
@RestController
@RequestMapping("/repairorder")
@Api(tags = "抢维修工单信息表接口")
@Slf4j
public class RepairorderController extends BaseController<Repairorder, RepairorderVo> {
    @Autowired
    private RepairorderService service;
    @Autowired
    private ExcelStrategyContext excelStrategyContext;


    @Autowired
    public RepairorderController(RepairorderService service) {
        init(service);
    }


    @GetMapping("/page")
    @ApiOperation(value = "分页查询")
    @ToFlyAppLog(title = "分页查询抢维修工单信息")
    public ResultRespone<Page<RepairorderVo>> getRepairorderPage(Page page, @ModelAttribute RepairorderDto parDto) {
        ResultRespone<Page<RepairorderVo>> rest = new ResultRespone<>();
        try {
            rest.setResult(service.getRepairOrderPage(page, parDto));
        } catch (BusinessException e) {
            rest.setCode(e.getRetCd());
            rest.setMessage(e.getMsgDes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rest;
    }

    @ApiOperation(value = "新增基本信息对象")
    @PostMapping("/save")
    @ToFlyAppLog(title = "新增抢维修工单信息")
    public ResultRespone<Object> saveRepairorder(@Valid @ModelAttribute RepairorderDto parDto, @RequestParam(value = "result", required = false) BindingResult result, @RequestParam(value = "fileList", required = false) List<MultipartFile> fileList) {
        ResultRespone<Object> rest = new ResultRespone<>();
        // 数据校验 判空返回
        if (!Optional.ofNullable(super.validRest(rest, result)).isPresent()) {
            try {
                Repairorder repairorder = service.savaPlanInfo(fileList, parDto);
                rest.setResult(repairorder.getId());
            } catch (BusinessException e) {
                rest.setCode(e.getRetCd());
                rest.setMessage(e.getMsgDes());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return rest;
    }

    @ApiOperation(value = "新增基本信息对象Feign调用")
    @PostMapping("/saveFeign")
    public ResultRespone<Object> saveRepairOrderFeign(@RequestBody RepairorderDto parDto) {
        ResultRespone<Object> rest = new ResultRespone<>();
        try {
            log.info("新增工单热线传入对象 {}", JSON.toJSONString(parDto));
            // 将对应的派工人作为审核人(创建人)
            List<RepairuserChildDto> repairUserChildDtoList = parDto.getRepairUserChildDtoList();
            if (null != repairUserChildDtoList && repairUserChildDtoList.size() > 0) {
                Long respUser = repairUserChildDtoList.get(0).getRespUser();
                parDto.setDispatchingId(respUser);
                parDto.setCreateUser(respUser);
            }
            Repairorder repairorder = service.savaPlanInfo(null, parDto);
            rest.setResult(repairorder.getId());
        } catch (BusinessException e) {
            rest.setCode(e.getRetCd());
            rest.setMessage(e.getMsgDes());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return rest;
    }

    @ApiOperation(value = "修改基本信息")
    @PutMapping("/updata")
    @ToFlyAppLog(title = "修改抢维修工单信息")
    public ResultRespone<Object> updateByIdRepairorder(@Valid RepairorderDto parDto, BindingResult result, @RequestParam(value = "fileList", required = false) List<MultipartFile> fileList) {
        ResultRespone<Object> rest = new ResultRespone<>();
        // 数据校验 判空返回
        if (!Optional.ofNullable(super.validRest(rest, result)).isPresent()) {
            try {
                service.updatePlanInfo(fileList, parDto);
            } catch (BusinessException e) {
                rest.setCode(e.getRetCd());
                rest.setMessage(e.getMsgDes());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return rest;

    }

    @GetMapping("/{id}")
    @ApiOperation(value = "通过ID查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Long")
    })
    @ToFlyAppLog(title = "通过ID查询抢维修工单信息")
    public ResultRespone<Repairorder> getByIdRepairorder(@PathVariable Long id) {
        ResultRespone<Repairorder> rest = new ResultRespone<>();
        try {
            return super.getById(id);
        } catch (BusinessException e) {
            rest.setCode(e.getRetCd());
            rest.setMessage(e.getMsgDes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rest;
    }

    @GetMapping("/getPlanRepairOrderDetail")
    @ApiOperation(value = "通过ID查询抢维修工单详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "flag", value = "是否展示部门下所有数据 是则填1 个人不填为空", required = false, dataType = "String")
    })
    @ToFlyAppLog(title = "通过ID查询抢维修工单详情")
    public ResultRespone<RepairOrderDetailVo> getPlanRepairOrderDetail(@RequestParam(value = "id") Long id, @RequestParam(value = "flag", required = false) String flag) {
        ResultRespone<RepairOrderDetailVo> rest = new ResultRespone<>();
        try {
            RepairOrderDetailVo planInfo = service.getPlanInfo(id, flag);
            rest.setResult(planInfo);
        } catch (BusinessException e) {
            rest.setCode(e.getRetCd());
            rest.setMessage(e.getMsgDes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rest;
    }

    @ApiOperation(value = "通过ID批量删除基本信息对象")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "idList", value = "单个或批量删除,多个请用,隔开", required = true, dataType = "String")
    })
    @DeleteMapping("/deleteByIds")
    @ToFlyAppLog(title = "通过ID批量删除抢维修工单详情")
    public ResultRespone<Object> removeByIdListRepairorder(String idList) {
        ResultRespone<Object> rest = new ResultRespone<>();
        try {
            List<Long> longList = Arrays.stream(idList.split(Constant.CSV)).map(s -> Long.parseLong(s.trim()))
                    .collect(Collectors.toList());
            service.deletePlanInfo(longList);
        } catch (BusinessException e) {
            rest.setCode(e.getRetCd());
            rest.setMessage(e.getMsgDes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rest;
    }


    @GetMapping("/orderRejected")
    @ApiOperation(value = "工单驳回")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "repairOrderId", value = "工单id", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "notes", value = "驳回说明", required = true, dataType = "String")

    })
    @ToFlyAppLog(title = "工单驳回")
    public ResultRespone<Boolean> orderRejected(Long repairOrderId, String notes) {
        ResultRespone<Boolean> rest = new ResultRespone<>();
        try {
            Boolean rejected = service.orderRejected(repairOrderId, notes);
            rest.setResult(rejected);
        } catch (BusinessException e) {
            rest.setCode(e.getRetCd());
            rest.setMessage(e.getMsgDes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rest;
    }

    @GetMapping("/orderForwarding")
    @ApiOperation(value = "工单转发")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "repairOrderId", value = "工单id", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "forwardingUserId", value = "转发人id", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "notes", value = "转发说明", required = true, dataType = "String")

    })
    @ToFlyAppLog(title = "工单转发")
    public ResultRespone<Boolean> orderForwarding(Long repairOrderId, Long forwardingUserId, String notes) {
        ResultRespone<Boolean> rest = new ResultRespone<>();
        try {
            Boolean rejected = service.orderForwarding(repairOrderId, forwardingUserId, notes);
            rest.setResult(rejected);
        } catch (BusinessException e) {
            rest.setCode(e.getRetCd());
            rest.setMessage(e.getMsgDes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rest;
    }

    @GetMapping("/getAuxiliarySingle")
    @ApiOperation(value = "获取用户部门今天已签到的所有用户最新位置信息列表")
    @ToFlyAppLog(title = "获取用户部门今天已签到的所有用户最新位置信息列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deptIds", value = "部门id（多个用,分隔）", required = false, dataType = "String"),
            @ApiImplicitParam(name = "flag", value = "是否获取所有部门人员 1是", required = false, dataType = "String"),
    })
    public ResultRespone<List<AuxiliarySingleVo>> getAuxiliarySingle(@RequestParam(value = "deptIds", required = false) String deptIds, @RequestParam(value = "flag", required = false) String flag) {
        ResultRespone<List<AuxiliarySingleVo>> rest = new ResultRespone<>();
        try {
            List<AuxiliarySingleVo> auxiliarySingle = service.getAuxiliarySingle(deptIds, flag);
            rest.setResult(auxiliarySingle);
        } catch (BusinessException e) {
            rest.setCode(e.getRetCd());
            rest.setMessage(e.getMsgDes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rest;
    }

    @GetMapping("/terminationRepairOrder")
    @ApiOperation(value = "终止抢维修工单")
    @ToFlyAppLog(title = "终止抢维修工单")
    public ResultRespone<Boolean> terminationRepairOrder(@RequestParam("orderId") String orderId) {
        ResultRespone<Boolean> rest = new ResultRespone<>();
        try {
            Boolean aBoolean = service.terminationRepairOrder(orderId);
            rest.setResult(aBoolean);
        } catch (BusinessException e) {
            rest.setResult(false);
            rest.setCode(e.getRetCd());
            rest.setMessage(e.getMsgDes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rest;
    }

    @GetMapping("/getNewRepairOrderDetail")
    @ApiOperation(value = "获取新抢维修工单详情")
    @ToFlyAppLog(title = "获取新抢维修工单详情")
    public ResultRespone<RepairOrderDetailNewVo> getNewRepairOrderDetail(@RequestParam("orderId") Long orderId) {
        ResultRespone<RepairOrderDetailNewVo> rest = new ResultRespone<>();
        try {
            rest.setResult(service.getRepairOrderDetailNewVo(orderId));
        } catch (BusinessException e) {
            rest.setCode(e.getRetCd());
            rest.setMessage(e.getMsgDes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rest;
    }

    @GetMapping("/getWorkOrdersByDevice")
    @ApiOperation(value = "根据设备编码获取对应工单列表信息")
    @ToFlyAppLog(title = "根据设备编码获取对应工单列表信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "equipmentCode", value = "设备编码", required = true, dataType = "String"),
    })
    public ResultRespone<List<RepairorderVo>> getWorkOrdersByDevice(@RequestParam("equipmentCode") String equipmentCode) {
        ResultRespone<List<RepairorderVo>> rest = new ResultRespone<>();
        try {
            rest.setResult(service.getWorkOrdersByDevice(equipmentCode));
        } catch (BusinessException e) {
            rest.setCode(e.getRetCd());
            rest.setMessage(e.getMsgDes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rest;
    }

    @GetMapping("/getRepairOrderOverVo")
    @ApiOperation(value = "获取已完成抢维修工单 处理地址对象列表")
    @ToFlyAppLog(title = "获取已完成抢维修工单 处理地址对象列表")
    public ResultRespone<List<RepairOrderOverVo>> getRepairOrderOverVo() {
        ResultRespone<List<RepairOrderOverVo>> rest = new ResultRespone<>();
        try {
            rest.setResult(service.getRepairOrderOverVo());
        } catch (BusinessException e) {
            rest.setCode(e.getRetCd());
            rest.setMessage(e.getMsgDes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rest;
    }


    /**
     * 导出wordd文档
     */
    @GetMapping(value = "/downloadWord")
    @ApiOperation(value = "导出word文档")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "工单id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "flag", value = "若flag为空则查询当前用户下所属部门的所有子任务", required = false, dataType = "String")

    })
    @ToFlyAppLog(title = "导出抢维修工单word文档")
    public void ExportWord(String orderId, String flag, HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (StringUtils.isEmpty(orderId)) {
            return;
        }
        String templateServiceType = "repairorderService";
        String templateFlag = "0";
        // 根据templateServiceType,templateFlag获取对应模板数据
        ExcelExportFileTypeEnum excelExportFileTypeEnum = ExcelExportFileTypeEnum.getExcelExportFileTypeEnum(templateServiceType, templateFlag);
        if (null == excelExportFileTypeEnum) {
            return;
        }
        Repairorder repairorder = new Repairorder();
        repairorder.setId(Long.valueOf(orderId));
        // 从模型类型枚举根据templateServiceType获取策略对应模板数据
        List<Map<String, Object>> dataList = excelStrategyContext.getExportData(templateServiceType, templateFlag, repairorder.toString());
        ExcelUtil.export(dataList.get(0), excelExportFileTypeEnum, Constant.FILE_PATH_TEST_EXPORT_EXCEL, response);

    }


}
