package com.ximai.mes.pro.controller.mobile;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.io.unit.DataUnit;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ximai.common.annotation.Log;
import com.ximai.common.core.controller.BaseController;
import com.ximai.common.core.domain.AjaxResult;
import com.ximai.common.core.page.TableDataInfo;
import com.ximai.common.enums.BusinessType;
import com.ximai.common.exception.ServiceException;
import com.ximai.common.utils.MessageUtils;
import com.ximai.common.utils.SecurityUtils;
import com.ximai.common.utils.data.StringUtils;
import com.ximai.mes.md.domain.MdWorkunit;
import com.ximai.mes.md.service.IMdWorkunitService;
import com.ximai.mes.md.vo.MdWorkunitVo;
import com.ximai.mes.pro.domain.ProFeedback;
import com.ximai.mes.pro.domain.ProProductQrcodeRecord;
import com.ximai.mes.pro.domain.proWorkOrder.ProWorkorder;
import com.ximai.mes.pro.domain.productionSolution.ProProductionSolution;
import com.ximai.mes.pro.domain.productionSolution.ProProductionSolutionProcess;
import com.ximai.mes.pro.domain.productionSolution.ProProductionSolutionProcessDrawing;
import com.ximai.mes.pro.domain.task.ProTask;
import com.ximai.mes.pro.domain.task.ProTaskIssue;
import com.ximai.mes.pro.domain.task.ProTaskWorkorder;
import com.ximai.mes.pro.domain.vo.ProPackagePrintResult;
import com.ximai.mes.pro.domain.vo.ProTaskLinkFileQuery;
import com.ximai.mes.pro.domain.vo.ProTaskQuery;
import com.ximai.mes.pro.domain.vo.task.FeedbackValidateSerialNoParams;
import com.ximai.mes.pro.dto.productionSolution.ProProductionSolutionProcessDrawingDto;
import com.ximai.mes.pro.dto.task.ProTaskLinkFile;
import com.ximai.mes.pro.mapper.proWorkOrder.ProWorkorderMapper;
import com.ximai.mes.pro.mapper.productionSolution.ProProductionSolutionMapper;
import com.ximai.mes.pro.mapper.productionSolution.ProProductionSolutionProcessMapper;
import com.ximai.mes.pro.mapper.task.ProTaskAssistProcessMapper;
import com.ximai.mes.pro.mapper.task.ProTaskMapper;
import com.ximai.mes.pro.mapper.task.ProTaskWorkorderMapper;
import com.ximai.mes.pro.mapper.task.ProTaskWorkunitMapper;
import com.ximai.mes.pro.service.IProFeedbackService;
import com.ximai.mes.pro.service.IProMaterialRequestService;
import com.ximai.mes.pro.service.IProProductQrcodeRecordService;
import com.ximai.mes.pro.service.IProRecoilMaterialService;
import com.ximai.mes.pro.service.proWorkOrder.IProWorkOrderProcessToolService;
import com.ximai.mes.pro.service.proWorkOrder.IProWorkorderService;
import com.ximai.mes.pro.service.productionSolution.IProProductionSolutionProcessDrawingService;
import com.ximai.mes.pro.service.productionSolution.IProProductionSolutionProcessService;
import com.ximai.mes.pro.service.task.IProTaskAssistProcessService;
import com.ximai.mes.pro.service.task.IProTaskIssueService;
import com.ximai.mes.pro.service.task.IProTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;

@Api
@RestController
@RequestMapping("/mobile/pro/protask")
public class ProTaskMobController extends BaseController {

    @Resource
    ProTaskAssistProcessMapper proTaskAssistProcessMapper;
    @Autowired
    private IProTaskService proTaskService;
    @Autowired
    private IProTaskAssistProcessService proTaskAssistProcessService;
    @Autowired
    private IProTaskIssueService proTaskIssueService;
    @Autowired
    private IProMaterialRequestService proMaterialRequestService;
    @Autowired
    private IProRecoilMaterialService proRecoilMaterialService;
    @Autowired
    private IProWorkorderService proWorkorderService;
    @Resource
    private IProWorkOrderProcessToolService proWorkOrderProcessToolService;
    @Resource
    private ProTaskWorkunitMapper proTaskWorkunitMapper;
    @Autowired
    private ProWorkorderMapper proWorkorderMapper;
    @Autowired
    private ProTaskWorkorderMapper proTaskWorkorderMapper;
    @Autowired
    private ProTaskMapper proTaskMapper;
    @Autowired
    private IProFeedbackService proFeedbackService;
    @Autowired
    private IProProductQrcodeRecordService productQrcodeRecordService;
    @Autowired
    private IProProductionSolutionProcessDrawingService productionSolutionProcessDrawingService;
    @Autowired
    private IProProductionSolutionProcessService proProductionSolutionProcessService;
    @Autowired
    ProProductionSolutionMapper proProductionSolutionMapper;
    @Autowired
    private IMdWorkunitService mdWorkunitService;

    @GetMapping("/getlist")
    public AjaxResult getIssueList(ProTaskIssue proTaskIssue) {
        List<ProTaskIssue> list = proTaskIssueService.selectProTaskIssueList(proTaskIssue);
        return AjaxResult.success(list);
    }

    /**
     * 查询工作站的生产任务
     */
    @ApiOperation("查询状态未完成的生产任务接口")
    @GetMapping("/getTaskList")
    public TableDataInfo<ProTask> list(ProTaskQuery proTask) {
        startPage();
        List<ProTask> rst = proTaskService.getTaskList(proTask);

        return getDataTable(rst);
    }

    /**
     * 查询工作站的生产任务
     */
    @ApiOperation("查询状态未完成的生产任务接口")
    @GetMapping("/getAllTaskList")
    public TableDataInfo<ProTask> getAllTaskList(ProTaskQuery proTask) {
        startPage();
        List<MdWorkunitVo> list = mdWorkunitService.selectMdWorkunitListByUser(new QueryWrapper<MdWorkunit>().eq("user_name", SecurityUtils.getUsername()));
        if(list.size() < 1){
            return getDataTable(new ArrayList<ProTask>());
        }
        if(proTask == null){
            proTask = new ProTaskQuery();
        }
        proTask.setWorkunitIdList(list.stream().map(mdWorkunitVo -> mdWorkunitVo.getWorkunitId()).collect(Collectors.toList()));
        List<ProTask> rst = proTaskService.getTaskList(proTask);
        return getDataTable(rst);
    }



    /**
     * 查询工作站的生产任务
     */
    @ApiOperation("查询任务关联附件")
    @GetMapping("/listLinkFile")
    public AjaxResult<List<ProTaskLinkFile>> listLinkFile(ProTaskLinkFileQuery proTaskQuery) {

        List<ProTaskLinkFile> list = new ArrayList<>();
        ProTask protask = proTaskService.selectProTaskByTaskId(proTaskQuery.getTaskId());
        ProWorkorder proWorkorder = proWorkorderService.selectListByQw(new QueryWrapper<ProWorkorder>().eq("t1.workorder_code", protask.getArrangeCode()))
                .stream().findFirst().orElseThrow(()->new ServiceException(MessageUtils.message("pro.workOrder.error.not.exist")));
        QueryWrapper<ProProductionSolutionProcess>  proProductionSolutionProcessQuery = new QueryWrapper<>();
        proProductionSolutionProcessQuery.eq("production_solution_id",proWorkorder.getProductionSolutionId());
        proProductionSolutionProcessQuery.eq("process_id",protask.getProcessId());
        List<ProProductionSolutionProcess>  proProductionSolutionProcesses = proProductionSolutionProcessService.selectProProductionSolutionProcessList(proProductionSolutionProcessQuery);
        if(proProductionSolutionProcesses.size() > 0){
            QueryWrapper<ProProductionSolutionProcessDrawing> query = new QueryWrapper<>();
            query.eq("t1.item_id", proWorkorder.getProductId());
            query.eq("t1.production_solution_id", proWorkorder.getProductionSolutionId());
            query.in("t2.production_solution_process_id",proProductionSolutionProcesses.stream()
                    .map(proProductionSolutionProcess -> proProductionSolutionProcess.getProductionSolutionProcessId()).collect(Collectors.toList()));
            List<ProProductionSolutionProcessDrawing> tempList = productionSolutionProcessDrawingService.selectProcessDrawingJoinSolution(query);
            tempList.stream().filter(s->s!=null).forEach(s -> {
                ProTaskLinkFile file = new ProTaskLinkFile();
                file.setFileName(s.getFileOriginalName());
                file.setFileType("工序图纸");
                file.setFilePath(s.getFilePath());
                list.add(file);
            });
        }
        ProProductionSolution proProductionSolution = proProductionSolutionMapper.selectProProductionSolutionByProductionSolutionId(proWorkorder.getProductionSolutionId());
        if(proProductionSolution != null && StringUtils.isNotEmpty(proProductionSolution.getFilePath())){
            List<Map<String,Object>> fileMap = (List<Map<String, Object>>) JSONArray.parse(proProductionSolution.getFilePath());
            if(fileMap != null){
                for (Map<String,Object> map : fileMap){
                    ProTaskLinkFile file = new ProTaskLinkFile();
                    file.setFileName((String) map.get("originalFilename"));
                    file.setFileType("通用图纸");
                    file.setFilePath((String) map.get("filePath"));
                    list.add(file);
                }
            }
        }
        return AjaxResult.success(list);
    }



    /**
     * 根据TaskCode获取生产任务详情
     *
     * @return
     */
    @GetMapping("/getProTaskByTaskCode")
    public AjaxResult getProTaskByTaskCode(@RequestParam("taskCode") String taskCode) {
        return AjaxResult.success(proTaskService.selectProTaskByTaskCode(taskCode));
    }

    /**
     * 获取生产任务详细信息
     */
    @ApiOperation("查询生产任务详情接口")
    @PreAuthorize("@ss.hasPermi('mes:pro:protask:query')")
    @GetMapping(value = "/{taskId}")
    public AjaxResult getInfo(@PathVariable("taskId") Long taskId) {
        return AjaxResult.success(proTaskService.selectProTaskByTaskId(taskId));
    }


    /**
     * 修改生产任务状态
     */
    @ApiOperation("修改生产任务状态接口")
    @Log(title = "生产任务", businessType = BusinessType.UPDATE)
    @PostMapping("/change")
    @ResponseBody
    public AjaxResult changeStatus(ProTask proTask) {
        proTaskService.changeStatus(proTask);
        return AjaxResult.success();
    }


    @ApiOperation("生产报工")
    @Log(title = "生产报工", businessType = BusinessType.INSERT)
    @PostMapping("/feedback")
    @ResponseBody
    public AjaxResult<List<ProPackagePrintResult>> feedBack(ProFeedback feedback) {
        return AjaxResult.success(proTaskService.feedBack(feedback));
    }

    /**
     * 修改工序任务外协关系
     */
    @Log(title = "外协报工", businessType = BusinessType.INSERT)
    @RequestMapping(value = "/assistFeedback", method = RequestMethod.POST)
    public AjaxResult assistFeedback(@RequestBody ProFeedback proFeedback) {
        return toAjax(proTaskAssistProcessService.feedBack(proFeedback));
    }

    /**
     * pad端查看图片按钮显示的工单
     *
     * @return
     */
    @GetMapping("/getProWorkder")
    public AjaxResult getProWorkderTaskID(@RequestParam("taskId") Long taskId) {
        List<ProWorkorder> workorderList = new ArrayList<>();
        ProTaskWorkorder proTaskWorkorder = new ProTaskWorkorder();
        proTaskWorkorder.setTaskId(taskId);
        List<ProTaskWorkorder> proTaskWorkorders = proTaskWorkorderMapper.selectProTaskWorkorderList(proTaskWorkorder);
        for (ProTaskWorkorder pro : proTaskWorkorders) {
            QueryWrapper<ProWorkorder> proWorkorderQueryWrapper = new QueryWrapper<>();
            proWorkorderQueryWrapper.eq("workorder_id", pro.getWorkorderId());
            ProWorkorder proWorkorder = proWorkorderMapper.selectListByQw(proWorkorderQueryWrapper).get(0);
            workorderList.add(proWorkorder);
        }
        List<ProWorkorder> collect = workorderList.stream().collect(
                collectingAndThen(
                        toCollection(() -> new TreeSet<>(Comparator.comparing(ProWorkorder::getProductName))),
                        ArrayList::new));

        return AjaxResult.success(collect);
    }

    /**
     * 查看下一道工序
     */
    @GetMapping("/feedBackNextProcess")
    public AjaxResult feedbackNextProcess(ProTask protask) {
        ProTask task = proTaskService.selectProTaskByTaskId(protask.getTaskId());
        ProTask task1 = new ProTask();
        QueryWrapper<ProTask> query = new QueryWrapper<>();
        query.notIn("task_id", protask.getTaskId());
        query.eq("task_batch", task.getTaskBatch());
        query.ge("ordinal", task.getOrdinal());
        query.orderByAsc("ordinal");
        List<ProTask> proTasks = proTaskMapper.selectProTaskJoinProcess(query);
        if (CollUtil.isNotEmpty(proTasks)) {
            task1 = proTasks.get(0);
            if (Objects.nonNull(task1)) {
                ProTask proTask = proTaskMapper.selectWorkunitTaskId(task1.getTaskId());
                task1.setWorkunitName(proTask.getWorkunitName());
            }
        }
        return AjaxResult.success(task1);
    }

    /**
     * 验证序列号报工
     */
    @ApiOperation("验证序列号报工")
    @PostMapping("/validateSerialNo")
    public AjaxResult<Boolean> validateSerialNo(@RequestBody FeedbackValidateSerialNoParams validateSerialNoParams) {
        proFeedbackService.validateSerialNo(validateSerialNoParams,false);
        return AjaxResult.success(true);
    }


}
