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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.text.StrJoiner;
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.StringUtils;
import com.ximai.common.utils.poi.ExcelUtil;
import com.ximai.mes.pro.domain.proWorkOrder.ProWorkOrderSoDirective;
import com.ximai.mes.pro.domain.proWorkOrder.ProWorkOrderSoSizeItem;
import com.ximai.mes.pro.domain.task.ProPackagePrintRecord;
import com.ximai.mes.pro.domain.vo.ProPackagePrintRecordQuery;
import com.ximai.mes.pro.domain.vo.ProPackagePrintRecordVo;
import com.ximai.mes.pro.domain.vo.proWorkOrder.WorkorderPackagePrint;
import com.ximai.mes.pro.domain.vo.task.BlPackagePrintParams;
import com.ximai.mes.pro.domain.vo.task.RePackagePrintParams;
import com.ximai.mes.pro.service.proWorkOrder.IProWorkOrderSoDirectiveService;
import com.ximai.mes.pro.service.proWorkOrder.IProWorkOrderSoSizeItemService;
import com.ximai.mes.pro.service.task.IProPackagePrintRecordService;
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.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 包装标签打印记录表Controller
 *
 * @author generator
 * @date 2024-03-19
 */
@RestController
@RequestMapping("/pro/packagePrintRecord")
public class ProPackagePrintRecordController extends BaseController {
    @Autowired
    private IProPackagePrintRecordService proPackagePrintRecordService;
    @Autowired
    private IProWorkOrderSoSizeItemService proWorkOrderSoSizeItemService;
    @Autowired
    private IProWorkOrderSoDirectiveService proWorkOrderSoDirectiveService;

    /**
     * 查询包装标签打印记录表列表
     */
    @PreAuthorize("@ss.hasPermi('pro:packagePrintRecord:list')")
    @GetMapping("/list")
    @ApiOperation("包装标签查询")
    public TableDataInfo<ProPackagePrintRecordVo> list(ProPackagePrintRecordQuery proFdPackagePrintRecord) {
        TableDataInfo<ProPackagePrintRecordVo> rst = new TableDataInfo<ProPackagePrintRecordVo>();
        startPage();
        QueryWrapper<ProPackagePrintRecord> query = new QueryWrapper<ProPackagePrintRecord>();
        query.eq(proFdPackagePrintRecord.getTaskWorkunitId()!=null,"task_workunit_id",proFdPackagePrintRecord.getTaskWorkunitId());
        query.eq(proFdPackagePrintRecord.getWorkorderId()!=null,"workorder_id",proFdPackagePrintRecord.getWorkorderId());
        query.eq(proFdPackagePrintRecord.getWorkorderSoDirectiveId()!=null,"workorder_so_directive_id",proFdPackagePrintRecord.getWorkorderSoDirectiveId());
        query.eq(proFdPackagePrintRecord.getWorkorderSoSizeItemId()!=null,"workorder_so_size_item_id",proFdPackagePrintRecord.getWorkorderSoSizeItemId());
        query.eq(proFdPackagePrintRecord.getFeedbackId()!=null,"feedback_id",proFdPackagePrintRecord.getFeedbackId());
        query.eq(StringUtils.isNotEmpty(proFdPackagePrintRecord.getBarcode()),"barcode",proFdPackagePrintRecord.getBarcode());
        query.eq(StringUtils.isNotEmpty(proFdPackagePrintRecord.getQrcode()),"qrcode",proFdPackagePrintRecord.getQrcode());
        query.orderByAsc("create_time");
        List<ProPackagePrintRecord> list = proPackagePrintRecordService.selectProPackagePrintRecordList(query);
        //查询指令与SIZE属性
        QueryWrapper<ProWorkOrderSoDirective> qw = new QueryWrapper<ProWorkOrderSoDirective>();
        qw.eq("workorder_id", proFdPackagePrintRecord.getWorkorderId());
        Map<Long, ProWorkOrderSoDirective> directiveMap = proWorkOrderSoDirectiveService.selectProWorkOrderSoDirectiveList(qw).stream()
                .collect(Collectors.toMap(s1 -> s1.getWorkorderSoDirectiveId(), s2 -> s2));
        QueryWrapper<ProWorkOrderSoSizeItem> sizeQuery = new QueryWrapper<ProWorkOrderSoSizeItem>();
        sizeQuery.in("workorder_id", proFdPackagePrintRecord.getWorkorderId());
        Map<Long, ProWorkOrderSoSizeItem> sizeMap = proWorkOrderSoSizeItemService.selectProWorkOrderSoSizeItem(sizeQuery).stream()
                .collect(Collectors.toMap(s1 -> s1.getWorkorderSoSizeItemId(), s2 -> s2));
        TableDataInfo<ProPackagePrintRecord> pageList = getDataTable(list);
        List<ProPackagePrintRecordVo> rstList = new ArrayList<ProPackagePrintRecordVo>();
        list.forEach(s -> {
            ProPackagePrintRecordVo temp = new ProPackagePrintRecordVo();
            BeanUtil.copyProperties(s, temp);
            if (directiveMap.containsKey(s.getWorkorderSoDirectiveId())) {
                temp.setDirective(directiveMap.get(s.getWorkorderSoDirectiveId()).getClientCmd());
            }else if(s.getWorkorderSoDirectiveId()==null){
                if(directiveMap.values().stream().findFirst().isPresent()){
                    temp.setDirective(directiveMap.values().stream().findFirst().get().getClientCmd());
                }
            }
            if (sizeMap.containsKey(s.getWorkorderSoSizeItemId())) {
                temp.setStandardSize(sizeMap.get(s.getWorkorderSoSizeItemId()).getStandardSize());
                temp.setDirective(sizeMap.get(s.getWorkorderSoSizeItemId()).getClientCmd());
            }else if(StringUtils.isNotEmpty(s.getWorkorderSoSizeItemIds())){
                StrJoiner joiner = StrJoiner.of(",");
                for(String t : s.getWorkorderSoSizeItemIds().split(",")){
                    joiner.append(sizeMap.get(Long.valueOf(t)).getStandardSize());
                }
                temp.setStandardSize(joiner.toString());
            }
            rstList.add(temp);
        });
        rst.setRows(rstList);
        rst.setTotal(pageList.getTotal());
        rst.setCode(pageList.getCode());
        rst.setMsg(pageList.getMsg());
        return rst;
    }

    /**
     * 导出包装标签打印记录表列表
     */
    @PreAuthorize("@ss.hasPermi('pro:packagePrintRecord:export')")
    @Log(title = "包装标签打印记录表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ProPackagePrintRecordQuery proFdPackagePrintRecord) {
        List<ProPackagePrintRecord> list = proPackagePrintRecordService.selectProPackagePrintRecordList(proFdPackagePrintRecord);
        ExcelUtil<ProPackagePrintRecord> util = new ExcelUtil<ProPackagePrintRecord>(ProPackagePrintRecord.class);
        util.exportExcel(response, list, "包装标签打印记录表数据");
    }

    /**
     * 获取包装标签打印记录表详细信息
     */
    @PreAuthorize("@ss.hasPermi('pro:packagePrintRecord:query')")
    @GetMapping(value = "/{recordId}")
    public AjaxResult getInfo(@PathVariable("recordId") Long recordId) {
        return AjaxResult.success(proPackagePrintRecordService.selectProPackagePrintRecordByRecordId(recordId));
    }

    /**
     * 新增包装标签打印记录表
     */
    @PreAuthorize("@ss.hasPermi('pro:packagePrintRecord:add')")
    @Log(title = "包装标签打印记录表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ProPackagePrintRecord proFdPackagePrintRecord) {
        return toAjax(proPackagePrintRecordService.insertProPackagePrintRecord(proFdPackagePrintRecord));
    }

    /**
     * 修改包装标签打印记录表
     */
    @PreAuthorize("@ss.hasPermi('pro:packagePrintRecord:edit')")
    @Log(title = "包装标签打印记录表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ProPackagePrintRecord proFdPackagePrintRecord) {
        return toAjax(proPackagePrintRecordService.updateProPackagePrintRecord(proFdPackagePrintRecord));
    }

    /**
     * 删除包装标签打印记录表
     */
    @PreAuthorize("@ss.hasPermi('pro:packagePrintRecord:remove')")
    @Log(title = "包装标签打印记录表", businessType = BusinessType.DELETE)
    @DeleteMapping("/{recordIds}")
    public AjaxResult remove(@PathVariable Long[] recordIds) {
        return toAjax(proPackagePrintRecordService.deleteProPackagePrintRecordByRecordIds(recordIds));
    }

    /**
     * 批量修改打印记录
     */
    @PreAuthorize("@ss.hasPermi('pro:packagePrintRecord:batchUpdate')")
    @PostMapping("/batchUpdate")
    @ApiOperation("批量修改打印记录")
    public AjaxResult batchUpdate(@RequestBody List<ProPackagePrintRecord> list) {
        proPackagePrintRecordService.batchUpdate(list);
        return AjaxResult.success();
    }

    @PreAuthorize("@ss.hasPermi('pro:packagePrintRecord:recordPackagePrintInfo')")
    @PostMapping("/recordPackagePrintInfo")
    @ApiOperation("记录打印次数并返回打印数据")
    public AjaxResult<List<WorkorderPackagePrint>> recordPackagePrintInfo(@RequestParam("workorderId") Long workorderId,
                                                                          @RequestParam("recordIds") Long[] recordIds) {
        List<ProPackagePrintRecord> tempList = new ArrayList<ProPackagePrintRecord>();
        for (Long recordId : recordIds) {
            ProPackagePrintRecord record = proPackagePrintRecordService.selectProPackagePrintRecordByRecordId(recordId);
            tempList.add(record);
        }
        List<WorkorderPackagePrint> rst = proPackagePrintRecordService.recordPackagePrintInfo(workorderId, tempList);
        return AjaxResult.success(rst);
    }

    @PostMapping("/rePackageInfoPrint")
    @ApiOperation("包装标签补打印")
    public AjaxResult<List<WorkorderPackagePrint>> rePackageInfoPrint(@RequestBody RePackagePrintParams params) {
        List<WorkorderPackagePrint> rst = proPackagePrintRecordService.rePackageInfoPrint(params);
        return AjaxResult.success(rst);
    }

    @PostMapping("/blPackagePrintInfo")
    @ApiOperation("装箱标签打印")
    public AjaxResult<List<WorkorderPackagePrint>> blPackagePrintInfo(@RequestBody BlPackagePrintParams params) {
        List<WorkorderPackagePrint> rst = proPackagePrintRecordService.blPackageInfoPrintOrInsert(params);
        return AjaxResult.success(rst);
    }

}
