package com.gci.boot.modules.vehicles.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gci.boot.annotation.Query.handle.QueryGenerator;
import com.gci.boot.annotation.permission.DataPermission;
import com.gci.boot.common.log.annotation.AddSysLog;
import com.gci.boot.common.util.MinioUtils;
import com.gci.boot.common.util.StringUtil;
import com.gci.boot.common.util.ValidatorUtil;
import com.gci.boot.common.validated.SaveValidated;
import com.gci.boot.common.validated.UpdateValidated;
import com.gci.boot.common.vo.Result;
import com.gci.boot.constant.CommonConstant;
import com.gci.boot.enums.FileExtension;
import com.gci.boot.modules.driver.service.ITbDriverSignInService;
import com.gci.boot.modules.msg.enums.SenderTypeEnum;
import com.gci.boot.modules.msg.enums.WorkOrderType;
import com.gci.boot.modules.msg.service.MsgPushService;
import com.gci.boot.modules.msg.vo.MsgRedisVO;
import com.gci.boot.modules.projects.entity.Projects;
import com.gci.boot.modules.projects.service.IProjectsService;
import com.gci.boot.modules.vehicles.entity.TbViolationRecord;
import com.gci.boot.modules.vehicles.service.ITbViolationRecordService;
import com.gci.boot.modules.vehicles.vo.MessageVO;
import com.gci.boot.modules.vehicles.vo.RegexTemplateVO;
import com.gci.boot.modules.vehicles.vo.VehicleProjectVO;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Api(tags="违章记录表对象")
@Slf4j
@RestController
@RequestMapping("/vehicles/violation")
public class TbViolationRecordController {
    @Autowired
    private ITbViolationRecordService violationRecordService;
    @Autowired
    private IProjectsService projectsService;
    @Autowired
    private MinioUtils minioUtils;
    @Autowired
    private ITbDriverSignInService driverSignInService;
    @Autowired
    private MsgPushService msgPushService;
    @Value("${failExcel}")
    private String failExcel;

    /**
     * 分页列表查询
     *
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AddSysLog("违章记录-分页列表查询")
    @GetMapping(value = "/list")
    @DataPermission(item="tb_violation_record.projectId", sqlIds = {"com.gci.boot.modules.vehicles.mapper.TbViolationRecordMapper.selectPage"})
    public Result<?> queryPageList(TbViolationRecord violationRecord,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        Page<TbViolationRecord> page = new Page<TbViolationRecord>(pageNo, pageSize);
        LambdaQueryWrapper<TbViolationRecord> lambdaQueryWrapper = QueryGenerator.initQueryWrapper(TbViolationRecord.class, violationRecord);
        IPage<TbViolationRecord> pageList = violationRecordService.page(page, lambdaQueryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     */
    @AddSysLog("违章记录-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody @Validated(SaveValidated.class) TbViolationRecord violationRecord) {
        Projects projects = projectsService.getById(violationRecord.getProjectId());
        if(Objects.nonNull(projects)){
            violationRecord.setProjectName(projects.getProjectName());
        }
        violationRecordService.save(violationRecord);
        //推送微信消息
        ThreadUtil.execAsync(()->{
            msgPushService.pushMsgToRedis(new MsgRedisVO(
                    SenderTypeEnum.YYWB.getSendType() +","+SenderTypeEnum.CUSTOMER.getSendType(),violationRecord.getId(),
                    violationRecord.getProjectId(), WorkOrderType.VIOLATION.getType(),"未处理",
                    DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"),projects.getProjectName() + "新增违章，请及时查看"));
        });
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     */
    @AddSysLog("违章记录-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody @Validated(UpdateValidated.class) TbViolationRecord violationRecord) {
        Projects projects = projectsService.getById(violationRecord.getProjectId());
        if(Objects.nonNull(projects)){
            violationRecord.setProjectName(projects.getProjectName());
        }
        if(Objects.nonNull(violationRecord.getHandleResult()) && 1==violationRecord.getHandleResult()){
            if(Objects.isNull(violationRecord.getHandleTime()) || Objects.isNull(violationRecord.getHandleVoucher())){
                return Result.error(101,"请选择处理时间及上传处理凭证！");
            }
        }
        violationRecordService.updateById(violationRecord);
        return Result.ok("编辑成功！");
    }

    /**
     * 删除
     */
    @AddSysLog("违章记录-删除")
    @DeleteMapping(value = "/realDelete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        violationRecordService.removeById(id);
        return Result.ok("删除成功！");
    }

    /**
     * 作废
     */
    @AddSysLog("违章记录-作废")
    @DeleteMapping(value = "/cancel")
    public Result<?> cancel(@RequestParam(name = "id", required = true) String id) {
        violationRecordService.update(new LambdaUpdateWrapper<TbViolationRecord>().eq(TbViolationRecord::getId,id).set(TbViolationRecord::getCancelFlag,1));
        return Result.ok("作废成功！");
    }

    /**
     * 恢复
     */
    @AddSysLog("违章记录-恢复")
    @DeleteMapping(value = "/unCancel")
    public Result<?> unCancel(@RequestParam(name = "id", required = true) String id) {
        violationRecordService.update(new LambdaUpdateWrapper<TbViolationRecord>().eq(TbViolationRecord::getId,id).set(TbViolationRecord::getCancelFlag,0));
        return Result.ok("作废成功！");
    }

    /**
     * 批量删除
     */
    @AddSysLog("违章记录-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> realDeleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        violationRecordService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 文件上传
     */
    @AddSysLog("违章记录-文件上传")
    @PostMapping("/upload")
    public Result<?> upload(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");
        if (ObjectUtil.isEmpty(file)) {
            return Result.error("请正确上传文件！");
        }
        return Result.ok(minioUtils.uploadFileValid(file, FileExtension.PIC.getNameList()));
    }

    /**
     * 导出
     * @return
     */
    @AddSysLog("违章记录-导出")
    @GetMapping("/export")
    @DataPermission(item="tb_violation_record.projectId", sqlIds = {"com.gci.boot.modules.vehicles.mapper.TbViolationRecordMapper.selectList"})
    public Result<?> export(TbViolationRecord violationRecord,HttpServletResponse response){
        try (OutputStream output = response.getOutputStream()){

            String fileName = "违章记录表.xlsx";
            try {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ";" + "filename*=utf-8''" + fileName);

            LambdaQueryWrapper<TbViolationRecord> lambdaQueryWrapper = QueryGenerator.initQueryWrapper(TbViolationRecord.class, violationRecord);
            List<TbViolationRecord> list = violationRecordService.list(lambdaQueryWrapper);
            EasyExcel.write(output, TbViolationRecord.class).sheet("违章记录").doWrite(list);

        } catch (IOException e) {
            return Result.error("导出错误！");
        }
        return Result.ok();
    }

    /**
     * 获取车牌-项目-责任人列表
     */
    @AddSysLog("违章记录-获取车牌-项目-责任人列表")
    @GetMapping(value = "/queryVehicleProject")
    public Result<?> queryVehicleProject() {
        List<VehicleProjectVO> list = violationRecordService.queryVehicleProject();
        return Result.ok(list);
    }

    /**
     * 获取车牌下拉列表
     */
    @AddSysLog("违章记录-获取车牌下拉列表")
    @GetMapping(value = "/queryAllVehicle")
    public Result<?> queryAllVehicle() {
        List<VehicleProjectVO> list = violationRecordService.queryAllVehicle();
        return Result.ok(list);
    }

    /**
     * 获取项目下拉列表
     */
    @AddSysLog("违章记录-获取项目下拉列表")
    @GetMapping(value = "/queryAllProject")
    @DataPermission(item="A.projectId", sqlIds = {"com.gci.boot.modules.vehicles.mapper.TbViolationRecordMapper.queryProjects"})
    public Result<?> queryAllProject() {
        List<VehicleProjectVO> list = violationRecordService.queryAllProject();
        return Result.ok(list);
    }

    /**
     * 解析短信获取车牌、时间、地点、违章分类
     */
    @AddSysLog("违章记录-解析短信获取车牌、时间、地点、违章分类")
    @PostMapping(value = "/analyzeMessage")
    public Result<?> analyzeMessage(@RequestBody RegexTemplateVO templateVO) {
        if(Objects.isNull(templateVO) || StrUtil.isBlank(templateVO.getTemplate())){
            return Result.error(101,"违章短信不能为空！");
        }
        String str = StringUtil.checkString2(templateVO.getTemplate(),500);
        if(StrUtil.isNotBlank(str)){
            return Result.error(101,str);
        }

        MessageVO vo = violationRecordService.analyzeMessage(templateVO.getTemplate());
        return Result.ok(vo);
    }

    /**
     * 新增违章行为
     */
    @AddSysLog("违章记录-新增违章行为")
    @PostMapping(value = "/addViolationBehavior")
    public Result<?> addViolationBehavior(@RequestBody MessageVO vo) {
        String str = violationRecordService.addViolationBehavior(vo);
        if(StrUtil.isNotBlank(str) && str.contains("存在")){
            return Result.error(101,str);
        }else{
            return Result.ok(str);
        }
    }

    /**
     * 车牌、时间获取打卡司机
     */
    @AddSysLog("违章记录-车牌、时间获取打卡司机")
    @GetMapping(value = "/queryDriverByPlateNumberAndTime")
    public Result<?> queryDriverByPlateNumberAndTime(String plateNumber, String time) {
        String name = driverSignInService.queryDriverByPlateNumberAndTime(plateNumber, time);
        return Result.ok(name);
    }

    /**
     * 导入
     */
    @AddSysLog(value = "违章-导入")
    @PostMapping("/import")
    public Result<?> listImport(HttpServletRequest request) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
        MultipartFile file = multipartRequest.getFile("file");
        if (ObjectUtil.isEmpty(file)) {
            return Result.error("请正确上传文件！");
        }
        if(!ValidatorUtil.isExcelFile(file)){
            return Result.error("导入文件必须为excel!");
        }
        return violationRecordService.msgImport(file);
    }

    /**
     * 导入错误信息下载
     */
    @AddSysLog(value = "违章-导入错误信息下载")
    @GetMapping("/downFail")
    public Result<?> downFail(HttpServletResponse response,String path) throws IOException {
        // 设置输出的格式
        // 循环取出流中的数据
        String fullPath = failExcel + path;
        try (InputStream stream = ResourceUtil.getStream(fullPath)) {
            response.setCharacterEncoding("utf-8");
            response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("维修信息导入异常数据", "utf-8"));
            response.setContentType("application/x-xls;");
            response.setHeader("content-type", "application/octet-stream");
            byte[] b = new byte[1024 * 10];
            int len;
            while ((len = stream.read(b)) > 0) {
                response.getOutputStream().write(b, 0, len);
            }
            // 下载完成后删除文件
            new Thread(() -> {
                try {
                    //延迟 3 秒,避免文件被占用
                    Thread.sleep(3000);
                    ValidatorUtil.deleteFile(fullPath);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        } catch (IORuntimeException e){
            e.printStackTrace();
            return Result.error("文件不存在!");
        }catch (Exception e) {
            e.printStackTrace();
            return Result.error("导出异常!");
        }
        return Result.ok();
    }

    /**
     * 导入模板下载
     */
    @AddSysLog(value = "违章-导入模板下载")
    @GetMapping("/downTemplate")
    public Result<?> downImport(HttpServletResponse response) throws IOException {
        // 设置输出的格式
        // 循环取出流中的数据
        try (InputStream stream = ResourceUtil.getStream("excelTemplate/违章短信导入模板.xlsx")) {
            response.setCharacterEncoding("utf-8");
            response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("违章短信导入模板", "utf-8"));
            response.setContentType("application/x-xls;");
            response.setHeader("content-type", "application/octet-stream");
            byte[] b = new byte[1024 * 10];
            int len;
            while ((len = stream.read(b)) > 0) {
                response.getOutputStream().write(b, 0, len);
            }
        } catch (IORuntimeException e){
            e.printStackTrace();
            return Result.error("文件不存在!");
        }catch (Exception e) {
            e.printStackTrace();
            return Result.error("导出异常!");
        }
        return Result.ok();
    }
}
