package com.hw.qms.controller;

import com.hw.common.core.constant.QmsConstants;
import com.hw.common.core.constant.SecurityConstants;
import com.hw.common.core.constant.WfConstants;
import com.hw.common.core.constant.WmsConstants;
import com.hw.common.core.domain.R;
import com.hw.common.core.exception.ServiceException;
import com.hw.common.core.web.controller.BaseController;
import com.hw.common.core.web.domain.AjaxResult;
import com.hw.common.core.web.page.TableDataInfo;
import com.hw.common.log.annotation.Log;
import com.hw.common.log.enums.BusinessType;
import com.hw.common.security.annotation.RequiresPermissions;
import com.hw.qms.domain.*;
import com.hw.qms.domain.vo.QmsCheckResultDetailVo;
import com.hw.qms.domain.vo.QmsMaterialCheckVo;
import com.hw.qms.domain.vo.QmsQualityInstanceActivityVo;
import com.hw.qms.service.*;
import com.hw.system.api.RemoteFileService;
import com.hw.system.api.RemoteSysCommonService;
import com.hw.system.api.RemoteUserService;
import com.hw.system.api.domain.SysFile;
import com.hw.system.api.domain.common.WfProcessActivity;
import com.hw.system.api.domain.common.vo.WfProcessActivityVo;
import com.hw.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description:质检PDA接口
 * @ProjectName:HwMes
 * @Author:xins
 * @Date:2024-01-26 10:18
 * @Version:1.0
 */
@RestController
@RequestMapping("/mobile")
public class QmsMobileController extends BaseController {
    @Autowired
    private IQmsCheckRuleService qmsCheckRuleService;
    @Autowired
    private IQmsCheckResultService qmsCheckResultService;
    @Autowired
    private IQmsCheckResultDetailService qmsCheckResultDetailService;
    @Autowired
    private IMesBaseBarcodeInfoService mesBaseBarcodeInfoService;
    @Autowired
    private IQmsQualityInstanceService qmsQualityInstanceService;
    @Autowired
    private IQmsCheckInstanceFileService qmsCheckInstanceFileService;
    @Resource
    private RemoteSysCommonService remoteSysCommonService;
    @Resource
    private RemoteFileService remoteFileService;

    /**
     * 扫描物料条码或者通过质检结果详情列表页面点击获取质检结果详情
     */
//    @RequiresPermissions("qms:checkrule:list")
    @GetMapping("/getCheckResultDetail")
    public AjaxResult getCheckResultDetail(QmsMaterialCheckVo qmsMaterialCheckVo) {
        Long checkResultDetailId = qmsMaterialCheckVo.getCheckResultDetailId();
        if (checkResultDetailId != null) {//如果是通过列表页点击进来则根据ID获取
            return success(qmsCheckResultDetailService.selectQmsCheckResultDetailByCheckResultDetailId(checkResultDetailId));
        }

        //扫描物料条码进入获取
        String materialBarcode = qmsMaterialCheckVo.getMaterialBarcode();
        QmsCheckResultDetail qmsCheckResultDetail = qmsCheckResultDetailService.getCheckResultDetail(materialBarcode);
        if (qmsCheckResultDetail != null) {//如果有质检结果，则返回已经保存的质检结果，否则返回需要质检的项目
            return success(qmsCheckResultDetail);
        } else {
            MesBaseBarcodeInfo baseBarcodeInfo = mesBaseBarcodeInfoService.selectMesBaseBarcodeInfoByBarcodeInfo(materialBarcode);
            if (baseBarcodeInfo == null) {
                throw new ServiceException("物料条码有误");
            }
            Long materialId = baseBarcodeInfo.getMaterialId();
            QmsCheckRuleDetail queryCheckRuleDetail = new QmsCheckRuleDetail();
            queryCheckRuleDetail.setTargetId(materialId);
            queryCheckRuleDetail.setTargetType(QmsConstants.QMS_CHECK_RULE_DETAIL_TARGET_TYPE_MATERIAL);
            QmsCheckRule qmsCheckRule = qmsCheckRuleService.selectQmsCheckRuleByTarget(queryCheckRuleDetail);
            Long checkResultId = qmsCheckResultService.insertCheckResult(baseBarcodeInfo, qmsCheckRule);
            qmsCheckRule.setCheckResultId(checkResultId);
            return success(qmsCheckRule);
        }
    }


    /**
     * 新增质检结果详情
     */
//    @RequiresPermissions("qms:checkresultdetail:add")
    @Log(title = "质检结果详情", businessType = BusinessType.INSERT)
    @PostMapping("/saveCheckResultDetail")
    public AjaxResult saveCheckResultDetail(@RequestBody QmsCheckResultDetail qmsCheckResultDetail) {
        if (qmsCheckResultDetail.getCheckResultDetailId() == null) {
            return toAjax(qmsCheckResultDetailService.insertQmsCheckResultDetail(qmsCheckResultDetail));
        } else {
            return toAjax(qmsCheckResultDetailService.updateQmsCheckResultDetail(qmsCheckResultDetail));
        }

    }


    /**
     * 获取批次质检结果列表
     */
//    @RequiresPermissions("qms:checkrule:list")
    @GetMapping("/getCheckResults")
    public TableDataInfo getCheckResults(QmsCheckResult qmsCheckResult) {
        startPage();
        List<QmsCheckResult> list = qmsCheckResultService.selectQmsCheckResultJoinList(qmsCheckResult);
        return getDataTable(list);
    }

    /**
     * 获取批次质检结果详情列表信息
     */
//    @RequiresPermissions("qms:checkrule:list")
    @GetMapping("/getCheckResult")
    public AjaxResult getCheckResult(QmsCheckResult qmsCheckResult) {
        QmsCheckResultDetailVo qmsCheckResultDetailVo = qmsCheckResultDetailService.getCheckResultDetailVo(qmsCheckResult.getCheckResultId());
        int batchAmount = mesBaseBarcodeInfoService.selectBarcodeInfoCountByBatchcode(qmsCheckResult.getMaterialBatch());
        qmsCheckResultDetailVo.setBatchAmount(batchAmount);
        qmsCheckResultDetailVo.setCheckMode(qmsCheckResult.getCheckMode());
        qmsCheckResultDetailVo.setCheckSample(qmsCheckResult.getCheckSample());
        return success(qmsCheckResultDetailVo);
    }

    /**
     * 获取批次质检结果详情列表
     */
//    @RequiresPermissions("qms:checkrule:list")
    @GetMapping("/getCheckResultDetails")
    public TableDataInfo getCheckResultDetails(QmsCheckResultDetail qmsCheckResultDetail) {
        startPage();
        List<QmsCheckResultDetail> list = qmsCheckResultDetailService.selectQmsCheckResultDetailList(qmsCheckResultDetail);
        return getDataTable(list);
    }


    /**
     * 更新质检结果状态
     */
//    @RequiresPermissions("qms:checkresultdetail:add")
    @Log(title = "质检结果", businessType = BusinessType.AUDIT)
    @PostMapping("/auditCheckResult")
    public AjaxResult auditCheckResult(@RequestBody QmsCheckResult qmsCheckResult) {
        return toAjax(qmsCheckResultService.auditQmsCheckResult(qmsCheckResult));
    }

    /**
     * 获取批次质检结果详情列表信息4不合格处置
     */
//    @RequiresPermissions("qms:checkrule:list")
    @GetMapping("/getCheckResult4Handle")
    public AjaxResult getCheckResult4Handle(QmsCheckResult qmsCheckResult) {
        //todo:修改工单时，根据用户工单流程步骤权限判断显示哪些
        QmsCheckResultDetailVo qmsCheckResultDetailVo = qmsCheckResultDetailService.getCheckResultDetailVo(qmsCheckResult.getCheckResultId());
        int batchAmount = mesBaseBarcodeInfoService.selectBarcodeInfoCountByBatchcode(qmsCheckResult.getMaterialBatch());
        qmsCheckResultDetailVo.setBatchAmount(batchAmount);
        qmsCheckResultDetailVo.setCheckMode(qmsCheckResult.getCheckMode());
        qmsCheckResultDetailVo.setCheckSample(qmsCheckResult.getCheckSample());
        qmsCheckResultDetailVo.setMaterialCode(qmsCheckResult.getMaterialCode());
        qmsCheckResultDetailVo.setMaterialName(qmsCheckResult.getMaterialName());
        qmsCheckResultDetailVo.setCheckRuleType(qmsCheckResult.getCheckRuleType());

        QmsQualityInstance qmsQualityInstance = qmsQualityInstanceService.selectQmsQualityInstanceByCheckResultId(qmsCheckResult.getCheckResultId());
        Long processActivityOrder = 1L;
        List<QmsQualityInstanceActivity> qmsQualityInstanceActivities = new ArrayList<>();
        if (qmsQualityInstance != null) {
            qmsQualityInstanceActivities = qmsQualityInstance.getQmsQualityInstanceActivityList();

            QmsQualityInstanceActivity lastQualityInstanceActivity = qmsQualityInstanceActivities.get(qmsQualityInstanceActivities.size() - 1);
            processActivityOrder = lastQualityInstanceActivity.getProcessStepOrder() + 1;//获取下一步的流程实例步骤

            QmsCheckInstanceFile queryCheckInstanceFile = new QmsCheckInstanceFile();
            queryCheckInstanceFile.setTargetType(WfConstants.QMS_FILE_TARGET_TYPE_QUALITY_INSTANCE_ACTIVITY);
            queryCheckInstanceFile.setTargetId(qmsQualityInstance.getQualityInstanceId());
            List<QmsCheckInstanceFile> qmsCheckInstanceFiles = qmsCheckInstanceFileService.selectQmsCheckInstanceFileList(queryCheckInstanceFile);

            qmsCheckResultDetailVo.setQmsCheckInstanceFiles(qmsCheckInstanceFiles);

            qmsCheckResultDetailVo.setWfInstsanceStatus(qmsQualityInstance.getWfInstanceStatus());

        } else {
            qmsCheckResultDetailVo.setWfInstsanceStatus(WfConstants.WF_INSTANCE_STATUS_TO_START);
            qmsCheckResultDetailVo.setPicEditedAble(true);
        }

        WfProcessActivityVo queryProcessActivityVo = new WfProcessActivityVo();
        queryProcessActivityVo.setWfProcessId(WfConstants.WF_QUALITY_ABNORMAL_PROCESS_ID);
        queryProcessActivityVo.setProcessActivityOrder(processActivityOrder);
        R<WfProcessActivity> processActivityResult = remoteSysCommonService.getWfProcessActivityByUI(queryProcessActivityVo, SecurityConstants.INNER);
        if (processActivityResult != null) {
            WfProcessActivity wfProcessActivity = processActivityResult.getData();
            if (wfProcessActivity != null) {
                QmsQualityInstanceActivity qmsQualityInstanceActivity = new QmsQualityInstanceActivity();
                qmsQualityInstanceActivity.setProcessActivityId(wfProcessActivity.getProcessActivityId());
                qmsQualityInstanceActivity.setProcessHandleStatus(QmsConstants.QMS_PROCESS_HANDLE_STATUS_EXECUTING);
                qmsQualityInstanceActivity.setProcessStepOrder(wfProcessActivity.getProcessActivityOrder());
                qmsQualityInstanceActivity.setEditedAble(true);
                qmsQualityInstanceActivities.add(qmsQualityInstanceActivity);
            }
        }

        qmsCheckResultDetailVo.setQmsQualityInstanceActivities(qmsQualityInstanceActivities);


        return success(qmsCheckResultDetailVo);
    }


    /**
     * 不合格处置保存
     */
//    @RequiresPermissions("qms:checkresultdetail:add")
    @Log(title = "质检工单实例", businessType = BusinessType.INSERT)
    @PostMapping("/handleQualityInstance")
    public AjaxResult handleQualityInstance(QmsQualityInstanceActivityVo qmsQualityInstanceActivityVo,
                                            @RequestParam(value = "files") List<MultipartFile> files) {
        List<String> fileUrls = new ArrayList<>();
        for (MultipartFile file : files) {
            R<SysFile> sysFileR = remoteFileService.upload(file);
            SysFile sysFile = sysFileR.getData();
            fileUrls.add(sysFile.getUrl());
        }
        return success(qmsQualityInstanceService.handleQualityInstance(qmsQualityInstanceActivityVo,fileUrls));
    }
}
