package com.bonus.material.back.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import com.bonus.common.biz.config.ListPagingUtil;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.core.utils.ServletUtils;
import com.bonus.common.log.enums.OperaType;
import com.bonus.material.archives.service.ArchivesService;
import com.bonus.material.back.domain.*;
import com.bonus.material.back.domain.vo.*;
import com.bonus.material.basic.domain.BmUnit;
import com.bonus.material.common.annotation.PreventRepeatSubmit;
import com.bonus.material.repair.domain.RepairApplyDetails;
import com.bonus.material.task.mapper.TmTaskMapper;
import com.bonus.system.api.RemoteFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.bonus.common.log.annotation.SysLog;
import com.bonus.common.security.annotation.RequiresPermissions;
import com.bonus.material.back.service.IBackApplyInfoService;
import com.bonus.common.core.web.controller.BaseController;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.core.utils.poi.ExcelUtil;
import org.springframework.web.multipart.MultipartFile;

/**
 * 退料任务Controller
 *
 * @author xsheng
 * @date 2024-10-16
 */
@Api(tags = "退料任务接口")
@RestController
@RequestMapping("/back_apply_info")
public class BackApplyInfoController extends BaseController {

    @Autowired
    private IBackApplyInfoService backApplyInfoService;

    @Resource
    private RemoteFileService sysFileService;

    @Resource
    private ArchivesService archivesService;

    @Resource
    private TmTaskMapper taskMapper;

    /**
     * 查询退料任务列表
     */
    @ApiOperation(value = "查询退料任务列表")
//    @RequiresPermissions("back:info:list")
    @GetMapping("/list")
    public AjaxResult list(BackApplyInfo backApplyInfo) {
        backApplyInfo.setIsExport(false);
        Integer pageIndex = Convert.toInt(ServletUtils.getParameter("pageNum"), 1);
        Integer pageSize = Convert.toInt(ServletUtils.getParameter("pageSize"), 10);
        List<BackApplyInfo> list = backApplyInfoService.selectBackApplyInfoList(backApplyInfo);
        return AjaxResult.success(ListPagingUtil.paging(pageIndex, pageSize, list));
    }

    /**
     * 查询未签字退料任务列表
     * @param backApplyInfo
     * @return
     */
    @ApiOperation(value = "查询未签字退料任务列表")
    @GetMapping("/getNoSignList")
    public AjaxResult getNoSignList(BackApplyInfo backApplyInfo) {
        Integer pageIndex = Convert.toInt(ServletUtils.getParameter("pageNum"), 1);
        Integer pageSize = Convert.toInt(ServletUtils.getParameter("pageSize"), 10);
        List<BackApplyInfo> list = backApplyInfoService.getNoSignList(backApplyInfo);
        return AjaxResult.success(ListPagingUtil.paging(pageIndex, pageSize, list));
    }

    /**
     * 查询材料员待确认的任务
     * @param backApplyInfo
     * @return
     */
    @ApiOperation(value = "查询材料员待确认的任务")
    @GetMapping("/getCompleteBackTaskList")
    public AjaxResult getCompleteBackTaskList(BackApplyInfo backApplyInfo) {
        Integer pageIndex = Convert.toInt(ServletUtils.getParameter("pageNum"), 1);
        Integer pageSize = Convert.toInt(ServletUtils.getParameter("pageSize"), 10);
        List<BackApplyInfo> list = backApplyInfoService.getCompleteBackTaskList(backApplyInfo);
        return AjaxResult.success(ListPagingUtil.paging(pageIndex, pageSize, list));
    }

    /**
     * 材料员确认接口
     * @param backApplyInfo
     * @return
     */
    @ApiOperation(value = "材料员确认接口")
    @PostMapping("/confirmMaterial")
    public AjaxResult confirmMaterial(@RequestBody BackApplyInfo backApplyInfo) {
        int confirmResult = backApplyInfoService.confirmMaterial(backApplyInfo);
        return confirmResult > 0 ? success("确认成功") : error("确认失败");
    }

    /**
     * 上传退料单PDF文件
     */
    @PostMapping("/uploadPdf")
    @SysLog(title = "上传退料单PDF", businessType = OperaType.INSERT, module = "仓储管理->上传退料单PDF")
    public AjaxResult uploadPdf(@RequestParam("file") MultipartFile file, @RequestParam("id") Long id) {
        try {
            AjaxResult result = sysFileService.upload(file);
            if (!result.isSuccess()) {
                return AjaxResult.error("SysFile文件服务上传失败：" + result.get("msg"));
            }
            //电子档案工程同步,第一次执行时间较长
            syncProject();

            @SuppressWarnings("unchecked")
            Map<String, Object> jsonObject = (Map<String, Object>) result.get("data");
            String fileName = file.getOriginalFilename();
            String filePath = jsonObject.get("url").toString();

            return archivesService.uploadArchivesProjectPdf("退料单", fileName, filePath, Math.toIntExact(id));
        } catch (Exception e) {
            logger.error("上传退料单PDF文件失败", e);
            return AjaxResult.error("领料单档案保存失败：" + e.getMessage());
        }
    }

    /**
     * 查询修试查询-退料查询列表
     * @param dto
     * @return
     */
    @ApiOperation(value = "查询修试查询-退料查询列表")
    @GetMapping("/selectBackApplyList")
    public AjaxResult selectBackApplyList(BackApplyVo dto) {
        Integer pageIndex = Convert.toInt(ServletUtils.getParameter("pageNum"), 1);
        Integer pageSize = Convert.toInt(ServletUtils.getParameter("pageSize"), 10);
        List<BackApplyVo> list = backApplyInfoService.selectBackApplyList(dto);
        return AjaxResult.success(ListPagingUtil.paging(pageIndex, pageSize, list));
    }

    /**
     * 导出退料查询列表
     * @param response
     * @param dto
     */
    @PostMapping("/exportBackApplyList")
    public void exportBackApplyList(HttpServletResponse response, BackApplyVo dto) {
        List<BackApplyVo> list = backApplyInfoService.selectBackApplyList(dto);
        ExcelUtil<BackApplyVo> util = new ExcelUtil<BackApplyVo>(BackApplyVo.class);
        util.exportExcel(response, list, "退料查询数据");
    }

    /**
     * 查询修试查询-退料查询二级列表
     * @param dto
     * @return
     */
    @ApiOperation(value = "查询修试查询-退料查询二级列表")
    @GetMapping("/selectSecondList")
    public AjaxResult selectSecondList(BackApplyInfoVo dto) {
        BackApplyInfoVo list = backApplyInfoService.selectSecondList(dto);
        return AjaxResult.success(list);
    }

    /**
     * 导出修试查询-退料查询二级列表
     * @param response
     * @param dto
     */
    @PostMapping("/exportSecondList")
    public void exportSecondList(HttpServletResponse response, BackApplyInfoVo dto) {
        List<BackApplyInfoVo> list = new ArrayList<>();
        BackApplyInfoVo vo = backApplyInfoService.selectSecondList(dto);
        list.add(vo);
        ExcelUtil<BackApplyInfoVo> util = new ExcelUtil<BackApplyInfoVo>(BackApplyInfoVo.class);
        util.exportExcel(response, list, "退料查询数据");
    }

    /**
     * 根据单位和工程id查询领料机具
     * @param dto
     * @return
     */
    @ApiOperation(value = "根据单位和工程id查询领料机具")
    @GetMapping("/getMachineById")
    public AjaxResult getMachineById(BackApplyInfo dto){
        return backApplyInfoService.getMachineById(dto);
    }

    /**
     * 根据单位和工程id查询领料机具
     * @param dto
     * @return
     */
    @ApiOperation(value = "根据单位和工程id查询领料机具")
    @GetMapping("/selectMachineById")
    public AjaxResult selectMachineById(BackApplyInfo dto){
        return backApplyInfoService.selectMachineById(dto);
    }

    /**
     * 根据typeId查询领料机具列表
     * @param dto
     * @return
     */
    @ApiOperation(value = "根据typeId查询领料机具列表")
    @GetMapping("/selectMachineByIdList")
    public AjaxResult selectMachineByIdList(BackApplyInfo dto){
        Integer pageIndex = Convert.toInt(ServletUtils.getParameter("pageNum"), 1);
        Integer pageSize = Convert.toInt(ServletUtils.getParameter("pageSize"), 10);
        List<MaCodeVo> list = backApplyInfoService.selectMachineByIdList(dto);
        return AjaxResult.success(ListPagingUtil.paging(pageIndex, pageSize, list));
    }

    /**
     * 根据typeId查询领料机具列表
     * @param dto
     * @return
     */
    @ApiOperation(value = "根据typeId查询领料机具列表")
    @GetMapping("/selectMachineByIdListQrScan")
    public AjaxResult selectMachineByIdListQrScan(BackApplyInfo dto){
        List<MaCodeVo> list = backApplyInfoService.selectMachineByIdList(dto);
        return AjaxResult.success(list);
    }

    /**
     * app根据设备编码去检索领料详情
     * @param dto
     * @return
     */
    @ApiOperation(value = "app编码检索")
//    @RequiresPermissions("back:info:list")
    @GetMapping("/getMachine")
    public AjaxResult getMachine(BackApplyInfo dto){
        return backApplyInfoService.getMachine(dto);
    }

    /**
     * app根据设备编码去检索退料工程
     * @param dto
     * @return
     */
    @ApiOperation(value = "app编码退料任务建立")
//    @RequiresPermissions("back:info:list")
    @GetMapping("/getMachineByCode")
    public AjaxResult getMachineByCode(BackApplyInfo dto){
        return AjaxResult.success(backApplyInfoService.getMachineByCode(dto));
    }

    /**
     * 导出退料任务列表
     */
    @ApiOperation(value = "导出退料任务列表")
    @PreventRepeatSubmit
//    @RequiresPermissions("back:info:export")
    @SysLog(title = "退料任务", businessType = OperaType.EXPORT, logType = 1,module = "仓储管理->导出退料任务")
    @PostMapping("/export")
    public void export(HttpServletResponse response, BackApplyInfo backApplyInfo) {
        backApplyInfo.setIsExport(true);
        List<BackApplyInfo> list = backApplyInfoService.selectBackApplyInfoList(backApplyInfo);
        ExcelUtil<BackApplyInfo> util = new ExcelUtil<BackApplyInfo>(BackApplyInfo.class);
        util.exportExcel(response, list, "退料任务数据");
    }

    /**
     * 获取退料任务详细信息
     */
    @ApiOperation(value = "获取退料任务详细信息")
//    @RequiresPermissions("back:info:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id,
                              @RequestParam(value = "keyWord", required = false) String keyWord) {
        return backApplyInfoService.selectBackApplyInfoById(id, keyWord);
    }

    /**
     * 查询退料任务详情信息
     * @param backApplyDetails
     * @return
     */
    @ApiOperation(value = "查询退料任务详情信息")
//    @RequiresPermissions("back:info:query")
    @GetMapping(value = "/getDetailsById")
    public AjaxResult getDetailsById(BackApplyDetails backApplyDetails) {
        return success(backApplyInfoService.getDetailsById(backApplyDetails));
    }

    /**
     * 新增退料任务
     */
    @ApiOperation(value = "新增退料任务")
    @PreventRepeatSubmit
//    @RequiresPermissions("back:info:add")
    @SysLog(title = "退料任务", businessType = OperaType.INSERT, logType = 1,module = "仓储管理->新增退料任务")
    @PostMapping
    public AjaxResult add(@Valid @RequestBody BackApplyRequestVo dto) {
        try {
            return backApplyInfoService.insertBackApplyInfo(dto);
        } catch (Exception e) {
            return error("系统错误, " + e.getMessage());
        }
    }

    /**
     * 新增退料任务app
     * @param dto
     * @return
     */
    @ApiOperation(value = "新增退料任务app")
    @PreventRepeatSubmit
//    @RequiresPermissions("back:info:add")
    @SysLog(title = "退料任务", businessType = OperaType.INSERT, logType = 1,module = "仓储管理->新增退料任务app")
    @PostMapping("/insertApp")
    public AjaxResult insertApp(@RequestBody BackAppRequestVo dto) {
        try {
            return backApplyInfoService.insertApp(dto);
        } catch (Exception e) {
            return error("系统错误, " + e.getMessage());
        }
    }

    /**
     * 修改退料任务
     */
    @ApiOperation(value = "修改退料任务")
    @PreventRepeatSubmit
//    @RequiresPermissions("back:info:edit")
    @SysLog(title = "退料任务", businessType = OperaType.UPDATE, logType = 1,module = "仓储管理->修改退料任务")
    @PostMapping("/edit")
    public AjaxResult edit(@Valid @RequestBody BackApplyRequestVo dto) {
        try {
            return backApplyInfoService.updateBackApplyInfo(dto);
        } catch (Exception e) {
            return error("系统错误, " + e.getMessage());
        }
    }

    @ApiOperation(value = "修改退料任务打印状态")
    @PreventRepeatSubmit
//    @RequiresPermissions("back:info:edit")
    @SysLog(title = "退料任务", businessType = OperaType.UPDATE, logType = 1,module = "仓储管理->修改退料任务")
    @PostMapping("/editPrintStatus")
    public AjaxResult editPrintStatus(@RequestBody BackApplyInfo dto) {
        try {
            return backApplyInfoService.editPrintStatus(dto.getId());
        } catch (Exception e) {
            return error("系统错误, " + e.getMessage());
        }
    }

    @ApiOperation(value = "修改退料任务电子签名")
    @PreventRepeatSubmit
//    @RequiresPermissions("back:info:edit")
    @SysLog(title = "退料任务电子签名", businessType = OperaType.UPDATE, logType = 1,module = "仓储管理->修改退料任务电子签名")
    @PostMapping("/updateSignById")
    public AjaxResult updateSignById(@RequestBody BackApplyInfo dto) {
        try {
            return toAjax(backApplyInfoService.updateSignById(dto));
        } catch (Exception e) {
            return error("系统错误, " + e.getMessage());
        }
    }

    /**
     * 退料申请提交
     */
    @ApiOperation(value = "退料申请提交")
    @PreventRepeatSubmit
//    @RequiresPermissions("back:info:submit")
    @SysLog(title = "退料任务", businessType = OperaType.UPDATE, logType = 1,module = "仓储管理->退料申请提交")
    @PostMapping("/submitBackApply")
    public AjaxResult submitBackApply(@RequestBody BackApplyInfo backApplyInfo) {
        try {
            BmUnit unit = taskMapper.selectBmUnitInfo(backApplyInfo);
            if (unit != null && unit.getTypeId() == null) {
                throw new ServiceException("单位类型为空");
            }
            // 根据提交id判断是否已经在维修表中存在
            if (backApplyInfo.getId() != null) {
                List<RepairApplyDetails> list = taskMapper.selectBackApplyInfoById(backApplyInfo);
                if (CollectionUtil.isNotEmpty(list)) {
                    return AjaxResult.error("不允许重复提交，请稍候再试!");
                }
            }
            if (unit != null && unit.getTypeId() == 1731L) {
                // 班组退料提交
                return backApplyInfoService.submitBzBackApply(backApplyInfo);
            }
            return backApplyInfoService.submitBackApply(backApplyInfo);
        } catch (Exception e) {
            return error("系统错误, " + e.getMessage());
        }
    }

    /**
     * 打印状态变更
     */
    @ApiOperation(value = "打印状态变更")
    @PreventRepeatSubmit
    @RequiresPermissions("back:info:edit")
    @SysLog(title = "退料任务--打印", businessType = OperaType.UPDATE, module = "退料任务->打印")
    @PostMapping("/editPrint")
    public AjaxResult editPrint(@RequestBody BackApplyInfo backApplyInfo) {
        try {
            return backApplyInfoService.editPrintStatus(backApplyInfo.getId());
        } catch (Exception e) {
            return error("系统错误, " + e.getMessage());
        }
    }

    /**
     * 删除退料任务
     */
    @ApiOperation(value = "删除退料任务")
    @PreventRepeatSubmit
//    @RequiresPermissions("back:info:remove")
    @SysLog(title = "退料任务", businessType = OperaType.DELETE, logType = 1,module = "仓储管理->删除退料任务")
	@PostMapping("/deleteById")
    public AjaxResult remove(@RequestBody BackApplyInfo backApplyInfo) {
        return backApplyInfoService.deleteBackApplyInfoById(backApplyInfo.getId());
    }

    /**
     * todo :删除退料任务,仅供app使用（整张单据删除时，里面有内容，不允许删除）
     */
    @ApiOperation(value = "APP删除退料任务")
    @PreventRepeatSubmit
    @PostMapping("/deleteByApp")
    public AjaxResult deleteByApp(@RequestBody BackApplyInfo backApplyInfo) {
        return backApplyInfoService.deleteByApp(backApplyInfo.getId());
    }

    /**
     * app内层删除退料任务
     */
    @ApiOperation(value = "app内层删除退料任务")
    @PreventRepeatSubmit
    //@RequiresPermissions("back:info:remove")
    @SysLog(title = "退料任务", businessType = OperaType.DELETE, logType = 1,module = "仓储管理->删除退料任务")
	@PostMapping("/delete")
    public AjaxResult delete(@RequestBody BackApplyInfo backApplyInfo) {
        return backApplyInfoService.delete(backApplyInfo);
    }

    @ApiOperation(value = "app查询单个类型设备编码")
    @RequiresPermissions("back:info:list")
    @SysLog(title = "退料任务", businessType = OperaType.QUERY, logType = 1,module = "仓储管理->app查询单个类型设备编码")
	@GetMapping("/getMaCodeList")
    public AjaxResult getMaCodeList(BackApplyInfo backApplyInfo) {
        return backApplyInfoService.getMaCodeList(backApplyInfo);
    }

    /**
     * app编码查看保存
     * @param maCode
     * @return
     */
    @ApiOperation(value = "app编码查看保存")
    @PreventRepeatSubmit
    //@RequiresPermissions("back:info:edit")
    @SysLog(title = "退料任务", businessType = OperaType.UPDATE, logType =  1,module = "仓储管理->删除退料任务")
	@PostMapping("/updateMaCode")
    public AjaxResult updateMaCode(@RequestBody MaCode maCode) {
        return backApplyInfoService.updateMaCode(maCode);
    }

    /**
     * 查询工程是否结算
     * @param backApplyInfo
     * @return
     */
    @ApiOperation(value = "查询工程是否结算")
    @PostMapping("/selectIsSltById")
    public AjaxResult selectIsSltById(@RequestBody BackApplyInfo backApplyInfo) {
        return backApplyInfoService.selectIsSltById(backApplyInfo);
    }

    /**
     * app退料退回
     * @param backApplyDetails
     * @return
     */
    @ApiOperation(value = "app退料退回")
    @PreventRepeatSubmit
    @PostMapping("/backOutBack")
    public AjaxResult backOutBack(@NotNull(message = "领料出库信息不能为空") @RequestBody BackApplyDetails backApplyDetails) {
        try {
            return backApplyInfoService.backOutBack(backApplyDetails);
        } catch (Exception e) {
            return error("系统错误, " + e.getMessage());
        }
    }





    /**  -------装卸单开始-------  */

    /**
     * 新增装卸单
     */
    @ApiOperation(value = "新增装卸单")
    @PreventRepeatSubmit
    @SysLog(title = "新增装卸单", businessType = OperaType.INSERT, logType = 1, module = "业务办理->新增装卸单")
    @PostMapping("/addHandlingOrder")
    public AjaxResult addHandlingOrder(@RequestBody HandlingOrder bean) {
        return backApplyInfoService.addHandlingOrder(bean);
    }


    /**
     * 装卸单列表展示
     */
    @ApiOperation(value = "装卸单列表展示")
    @GetMapping("/getHandlingOrderList")
    public AjaxResult getHandlingOrderList(HandlingOrder bean) {
        Integer pageIndex = Convert.toInt(ServletUtils.getParameter("pageNum"), 1);
        Integer pageSize = Convert.toInt(ServletUtils.getParameter("pageSize"), 10);
        try {
            List<HandlingOrder> list = backApplyInfoService.getHandlingOrderList(bean);
            return AjaxResult.success(ListPagingUtil.paging(pageIndex, pageSize, list));
        } catch (Exception e) {
            return AjaxResult.success(ListPagingUtil.paging(pageIndex, pageSize, new ArrayList<>()));
        }
    }


    @ApiOperation(value = "获取排号")
    @PostMapping("/getSort")
    public AjaxResult getSort(@RequestBody HandlingOrder bean) {
        return backApplyInfoService.getSort(bean);
    }

    @ApiOperation(value = "上传排号")
    @PreventRepeatSubmit
    @PostMapping("/uploadSort")
    public AjaxResult uploadSort(@RequestBody HandlingOrder bean) {
        return backApplyInfoService.uploadSort(bean);
    }

    @ApiOperation(value = "删除装卸单")
    @PostMapping("/delHandlingOrder")
    public AjaxResult delHandlingOrder(@RequestBody HandlingOrder bean) {
        return backApplyInfoService.delHandlingOrder(bean);
    }



    /**  -------装卸单结束-------  */





    /**  -------出门证开始-------  */

    /**
     * 出门证列表展示
     */
    @ApiOperation(value = "出门证列表展示")
    @GetMapping("/getExitPermitList")
    public AjaxResult getExitPermitList(ExitPermit bean) {
        Integer pageIndex = Convert.toInt(ServletUtils.getParameter("pageNum"), 1);
        Integer pageSize = Convert.toInt(ServletUtils.getParameter("pageSize"), 10);
        try {
            List<ExitPermit> list = backApplyInfoService.getExitPermitList(bean);
            return AjaxResult.success(ListPagingUtil.paging(pageIndex, pageSize, list));
        } catch (Exception e) {
            return AjaxResult.success(ListPagingUtil.paging(pageIndex, pageSize, new ArrayList<>()));
        }

    }

    /**
     * 新增出门证
     */
    @ApiOperation(value = "新增出门证")
    @PreventRepeatSubmit
    @SysLog(title = "新增出门证", businessType = OperaType.INSERT, logType = 1, module = "业务办理->新增出门证")
    @PostMapping("/addExitPermit")
    public AjaxResult addExitPermit(@RequestBody ExitPermit bean) {
        return backApplyInfoService.addExitPermit(bean);
    }

    /**  -------出门证结束-------  */


    /**
     * 电子档案工程同步
     */
    public void syncProject() {
        //1、查询未同步的工程信息
        List<BackApplyInfo> list = backApplyInfoService.selectNotSyncProject();
        if (list.size()>0){
            for (BackApplyInfo backApplyInfo : list){
                //2、将所有工程信息插入archives_record_info，并返回id
                backApplyInfoService.syncProject(backApplyInfo);
                if (backApplyInfo.getId()!=null){
                    //3、将返回的每个id插入archives_record_details
                    backApplyInfoService.syncProjectDetails(backApplyInfo);
                }
            }
        }



    }

}
