package com.zt.plat.module.qms.business.bus.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.zt.plat.module.qms.business.bus.controller.vo.*;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessSampleDispatchDetailDO;
import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessSubSampleDO;
import com.zt.plat.module.qms.business.bus.service.BusinessSampleDispatchDetailService;
import com.zt.plat.module.qms.business.bus.service.BusinessSubSampleService;
import com.zt.plat.module.qms.business.config.controller.vo.ConfigWarehouseLocationPageReqVO;
import com.zt.plat.module.qms.business.config.controller.vo.ConfigWarehouseLocationRespVO;
import com.zt.plat.module.qms.business.config.service.ConfigWarehouseLocationService;
import com.zt.plat.module.qms.enums.QmsCommonConstant;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import com.zt.plat.framework.business.interceptor.BusinessControllerMarker;

import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import jakarta.validation.*;
import jakarta.servlet.http.*;
import java.util.*;
import java.io.IOException;

import com.zt.plat.framework.common.pojo.vo.BatchDeleteReqVO;
import com.zt.plat.framework.common.pojo.PageParam;
import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.framework.common.pojo.CommonResult;
import com.zt.plat.framework.common.util.object.BeanUtils;
import com.zt.plat.framework.datapermission.core.annotation.DeptDataPermissionIgnore;

import static com.zt.plat.framework.common.pojo.CommonResult.success;

import com.zt.plat.framework.excel.core.util.ExcelUtils;

import com.zt.plat.framework.apilog.core.annotation.ApiAccessLog;
import static com.zt.plat.framework.apilog.core.enums.OperateTypeEnum.*;
import static com.zt.plat.module.qms.enums.ErrorCodeConstants.BUSINESS_SUB_SAMPLE_NOT_EXISTS;

import com.zt.plat.module.qms.business.bus.dal.dataobject.BusinessSampleDispatchDO;
import com.zt.plat.module.qms.business.bus.service.BusinessSampleDispatchService;

@Tag(name = "管理后台 - 样品调拨")
@RestController
@RequestMapping("/qms/business-sample-dispatch")
@Validated
@DeptDataPermissionIgnore(enable = "true")
public class BusinessSampleDispatchController implements BusinessControllerMarker {


    @Resource private BusinessSampleDispatchService businessSampleDispatchService;
    @Resource private BusinessSampleDispatchDetailService businessSampleDispatchDetailService;
    @Resource private BusinessSubSampleService businessSubSampleService;
    @Resource private ConfigWarehouseLocationService configWarehouseLocationService;

    @PostMapping("/createTempData")
    @Operation(summary = "创建临时数据")
    public CommonResult<BusinessSampleDispatchRespVO> createTempData() {
        BusinessSampleDispatchSaveReqVO vo = new BusinessSampleDispatchSaveReqVO();
        vo.setCancelStatus("-1");
        return success(businessSampleDispatchService.createBusinessSampleDispatch(vo));
    }

    @PutMapping("/update")
    @Operation(summary = "更新样品调拨")
    public CommonResult<Boolean> updateBusinessSampleDispatch(@Valid @RequestBody BusinessSampleDispatchSaveReqVO updateReqVO) {
        updateReqVO.setCancelStatus("0");
        updateReqVO.setFlowStatus(QmsCommonConstant.NOT_START);
        businessSampleDispatchService.updateBusinessSampleDispatch(updateReqVO);
        return success(true);
    }

    @PostMapping("/addOrRemoveSample")
    @Operation(summary = "增加或移除样品")
    public CommonResult<Boolean> addOrRemoveSample(@Valid @RequestBody BusinessSampleDispatchSaveReqVO updateReqVO) {
        businessSampleDispatchService.addOrRemoveSample(updateReqVO, true);
        return success(true);
    }

    @PostMapping("/addBySampleReturnCode")
    @Operation(summary = "按归库码增加样品")
    public CommonResult<Boolean> addBySampleReturnCode(@RequestBody JSONObject param) {
        String id = param.getString("id");
        String sampleReturnCode = param.getString("sampleReturnCode");
        String warehouseCode = param.getString("warehouseCode");
        if(ObjectUtils.isEmpty(warehouseCode)){
            return CommonResult.error(BUSINESS_SUB_SAMPLE_NOT_EXISTS.getCode(), "请选择仓库，再扫描样品！");
        }
        BusinessSubSampleDO businessSubSampleDO = businessSubSampleService.getBySampleReturnCode(sampleReturnCode);
        if(businessSubSampleDO == null)
            return CommonResult.error(BUSINESS_SUB_SAMPLE_NOT_EXISTS.getCode(), "未查询到此样品！");
        //判断样品状态、库位
//        String sampleWarehouseCode = businessSubSampleDO.getWarehouseCode();  //todo 判断库位
        ConfigWarehouseLocationPageReqVO warehouseReqVO = new ConfigWarehouseLocationPageReqVO();
        warehouseReqVO.setId(businessSubSampleDO.getConfigWarehouseLocationInfomationId());
        PageResult<ConfigWarehouseLocationRespVO> warehousePage = configWarehouseLocationService.getConfigWarehouseLocationPage(warehouseReqVO);
        if(warehousePage.getTotal() == 0){
            return CommonResult.error(BUSINESS_SUB_SAMPLE_NOT_EXISTS.getCode(), "未查询到样品所在仓库，请检查样品码是否正确！");
        }
        ConfigWarehouseLocationRespVO warehouse = warehousePage.getList().get(0);
        if(!warehouseCode.equals(warehouse.getWarehouseCode())){
            return CommonResult.error(BUSINESS_SUB_SAMPLE_NOT_EXISTS.getCode(), "此样品所在仓库为："+warehouse.getWarehouseName()+"，请检查样品码是否正确！");
        }

        String returnStatus = businessSubSampleDO.getReturnStatus();
        if(!QmsCommonConstant.COMPLETED.equals(returnStatus)){
            return CommonResult.error(BUSINESS_SUB_SAMPLE_NOT_EXISTS.getCode(), "样品状态为："+returnStatus+"，不能调拨！");
        }
        String dispatchStatus = businessSubSampleDO.getDispatchStatus();
        if("1".equals(dispatchStatus)){
            return CommonResult.error(BUSINESS_SUB_SAMPLE_NOT_EXISTS.getCode(), "样品已被调拨：请归还后再调拨！");
        }
        BusinessSampleDispatchDetailPageReqVO reqVO = new BusinessSampleDispatchDetailPageReqVO();
        reqVO.setParentId(Long.valueOf(id));
        reqVO.setSampleReturnCode(sampleReturnCode);
        PageResult<BusinessSampleDispatchDetailExtendRespVO> pageDetailList = businessSampleDispatchDetailService.getBusinessSampleDispatchDetailPage(reqVO);
        if(pageDetailList.getTotal() > 0){
            return CommonResult.error(BUSINESS_SUB_SAMPLE_NOT_EXISTS.getCode(), "次样品已添加，请勿重复添加！");
        }
        List<Long> sampleIds = new ArrayList<>();
        sampleIds.add(businessSubSampleDO.getId());
        BusinessSampleDispatchSaveReqVO updateReqVO = new BusinessSampleDispatchSaveReqVO();
        updateReqVO.setId(Long.valueOf(id));
        updateReqVO.setAddSubSampleIds(sampleIds);
        businessSampleDispatchService.addOrRemoveSample(updateReqVO, false);
        return success(true);
    }

    @PostMapping("/createProcessInstance")
    @Operation(summary = "发起流程")
    public CommonResult<BusinessSampleDispatchRespVO> createProcessInstance(@Valid @RequestBody BusinessSampleDispatchSaveReqVO vo) {
        return businessSampleDispatchService.createProcessInstance(vo);
    }

    @PostMapping("/execDispatch")
    @Operation(summary = "执行调拨")
    public CommonResult<String> execDispatch(@Valid @RequestBody BusinessSampleDispatchSaveReqVO vo) {
        return businessSampleDispatchService.execDispatch(vo);
    }

    @PostMapping("/execGiveback")
    @Operation(summary = "调拨归还")
    public CommonResult<String> execGiveback(@RequestBody JSONObject vo) {
        return businessSampleDispatchService.execGiveback(vo);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除样品调拨")
    @Parameter(name = "id", description = "编号", required = true)
//    @PreAuthorize("@ss.hasPermission('qms:business-sample-dispatch:delete')")
    public CommonResult<Boolean> deleteBusinessSampleDispatch(@RequestParam("id") Long id) {
        businessSampleDispatchService.deleteBusinessSampleDispatch(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除样品调拨")
    @PreAuthorize("@ss.hasPermission('qms:business-sample-dispatch:delete')")
    public CommonResult<Boolean> deleteBusinessSampleDispatchList(@RequestBody BatchDeleteReqVO req) {
        businessSampleDispatchService.deleteBusinessSampleDispatchListByIds(req.getIds());
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得样品调拨")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
//    @PreAuthorize("@ss.hasPermission('qms:business-sample-dispatch:query')")
    public CommonResult<BusinessSampleDispatchRespVO> getBusinessSampleDispatch(@RequestParam("id") Long id) {
        BusinessSampleDispatchDO businessSampleDispatch = businessSampleDispatchService.getBusinessSampleDispatch(id);
        return success(BeanUtils.toBean(businessSampleDispatch, BusinessSampleDispatchRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得样品调拨分页")
//    @PreAuthorize("@ss.hasPermission('qms:business-sample-dispatch:query')")
    public CommonResult<PageResult<BusinessSampleDispatchRespVO>> getBusinessSampleDispatchPage(@Valid BusinessSampleDispatchPageReqVO pageReqVO) {
        PageResult<BusinessSampleDispatchDO> pageResult = businessSampleDispatchService.getBusinessSampleDispatchPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, BusinessSampleDispatchRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出样品调拨 Excel")
    @PreAuthorize("@ss.hasPermission('qms:business-sample-dispatch:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportBusinessSampleDispatchExcel(@Valid BusinessSampleDispatchPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<BusinessSampleDispatchDO> list = businessSampleDispatchService.getBusinessSampleDispatchPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "样品调拨.xls", "数据", BusinessSampleDispatchRespVO.class,
                        BeanUtils.toBean(list, BusinessSampleDispatchRespVO.class));
    }

}