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

import cn.hutool.core.collection.CollUtil;
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.utils.data.ExceptionUtil;
import com.ximai.mes.pro.domain.ProFeedback;
import com.ximai.mes.pro.domain.proWorkOrder.ProWorkorder;
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.ProTaskQuery;
import com.ximai.mes.pro.domain.vo.proWorkOrder.WorkorderPackagePrint;
import com.ximai.mes.pro.domain.vo.task.FeedbackPackageAddParams;
import com.ximai.mes.pro.domain.vo.task.FeedbackPackageInfo;
import com.ximai.mes.pro.domain.vo.task.FeedbackPackageQueryParams;
import com.ximai.mes.pro.mapper.proWorkOrder.ProWorkorderMapper;
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.IProRecoilMaterialService;
import com.ximai.mes.pro.service.proWorkOrder.IProWorkOrderProcessToolService;
import com.ximai.mes.pro.service.proWorkOrder.IProWorkorderService;
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 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;


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

    @ApiOperation("查询状态未完成的生产任务接口")
    @GetMapping("/buttonList/{taskWorkunitIds}")
    public List<Map<String, String>> buttonList(@PathVariable Long[] taskWorkunitIds) {
        ExceptionUtil.checkTrueThrowException(taskWorkunitIds.length == 0, "参数非法");
        List<Map<String, String>> result = new ArrayList<>();
        for (Long workunitId : taskWorkunitIds) {
            boolean b1 = proMaterialRequestService.checkMaterialRequestIsExist(workunitId);
            boolean b2 = proRecoilMaterialService.checkRecoilMaterialIsExist(workunitId);
            boolean b3 = proWorkOrderProcessToolService.checkProcessToolIsExsit(workunitId);
            boolean b4 = proMaterialRequestService.checkMaterialRequestExist(workunitId);

            Map<String, String> map = new HashMap<>();
            map.put("materialView", b1 ? "1" : "0");
            map.put("recoilMaterialView", b2 ? "1" : "0");
            map.put("processToolView", b3 ? "1" : "0");
            map.put("MaterialRequestView", b4 ? "1" : "0");
            map.put("MaterialReturnView", b4 ? "1" : "0");
            map.put("taskWorkunitId", String.valueOf(workunitId));
            result.add(map);
        }
        return result;
    }


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

        return getManualDataTable(rst);
    }

    /**
     * 根据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));
    }

    @ApiOperation("包装工序生产报工")
    @Log(title = "包装工序生产报工", businessType = BusinessType.INSERT)
    @PostMapping("/feedBackPackage")
    @ResponseBody
    public AjaxResult<List<WorkorderPackagePrint>> feedBackPackage(FeedbackPackageAddParams feedback) {
        return AjaxResult.success(proTaskService.feedBackPackage(feedback));
    }

    @ApiOperation("包装工序报工列表")
    @PostMapping("/listFeedBackPackage")
    @ResponseBody
    public AjaxResult<FeedbackPackageInfo> listFeedBackPackage(@RequestBody FeedbackPackageQueryParams query) {
        if (query.getMergePack() == 1 && (query.getPackNum() == null || query.getPackNum() == 0)) {
            query.setPackNum(Integer.MAX_VALUE);
        }
        FeedbackPackageInfo rst = proTaskService.listFeedBackPackage(query);
        return AjaxResult.success(rst);
    }

    /**
     * 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);
    }


}
