package com.prolog.cs.base.gsp.controller;

import cn.hutool.core.collection.CollUtil;
import com.prolog.cs.base.gsp.QueryDTO;
import com.prolog.cs.base.gsp.dao.GspUpkeepCheckMapper;
import com.prolog.cs.base.gsp.dao.GspUpkeepCheckPlanMapper;
import com.prolog.cs.base.gsp.model.GspUpkeepCheck;
import com.prolog.cs.base.gsp.model.GspUpkeepCheckPlan;
import com.prolog.cs.base.gsp.service.GspUpkeepCheckPlanService;
import com.prolog.cs.base.gsp.service.GspUpkeepCheckService;
import com.prolog.cs.base.gsp.vo.GspUpkeepCheckVO;
import com.prolog.framework.authority.core.dto.UserDTO;
import com.prolog.framework.authority.user.UserTemplate;
import com.prolog.framework.bz.common.print.PrintData;
import com.prolog.framework.bz.common.print.ReportData;
import com.prolog.framework.common.message.RestMessage;
import com.prolog.framework.log.aop.annotation.UserLog;
import com.prolog.framework.utils.DateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.cglib.beans.BeanMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotEmpty;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 打印控制类
 *
 * @author Xiong
 */
@Api(tags = "单据打印")
@RestController
@RequestMapping("/print")
public class PrintController {

    @Autowired
    private UserTemplate userTemplate;

    @Autowired
    private GspUpkeepCheckMapper mapper;

    @Autowired
    private GspUpkeepCheckPlanMapper gspUpkeepCheckPlanMapper;

    @Autowired
    private GspUpkeepCheckService gspUpkeepCheckService;

    @Autowired
    private GspUpkeepCheckPlanService gspUpkeepCheckPlanService;

    /**
     * 养护打印
     */
    @ApiOperation("养护打印")
    @GetMapping("/getGSPUpkeepPrintData")
    @UserLog()
    public RestMessage<Object> getGspYHPrintData(QueryDTO upkeepCheckDTO) {
        UserDTO userDTO = userTemplate.getUserDTO();
        if (upkeepCheckDTO.getEndTime() != null) {
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(upkeepCheckDTO.getEndTime());
            calendar.add(Calendar.DATE, 1);//1表示明天,-1表示昨天
            upkeepCheckDTO.setEndTime(calendar.getTime());//这个时间就是第二天
        }
        GspUpkeepCheckPlan plan = gspUpkeepCheckPlanMapper.findById(upkeepCheckDTO.getPlanId(), GspUpkeepCheckPlan.class);
        List<GspUpkeepCheck> list = mapper.findList(upkeepCheckDTO);
        List<GspUpkeepCheckVO> gspUpkeepCheckVOS = gspUpkeepCheckService.spellGspUpkeepCheckVOSPage(list);

        PrintData pd = new PrintData();
        Map<String, List<GspUpkeepCheckVO>> collect = gspUpkeepCheckVOS.stream().collect(Collectors.groupingBy(x -> x.getItemHealthCategoryName()));
        Set<Map.Entry<String, List<GspUpkeepCheckVO>>> entries = collect.entrySet();
        List<ReportData> rdList = new ArrayList<ReportData>();
        for (Map.Entry<String, List<GspUpkeepCheckVO>> entry : entries) {
            // 组装报表头
            ReportData rd = new ReportData();
            Map<String, Object> head = new HashMap<>();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
            head.put("printDate", sdf.format(new Date()));
            if (CollUtil.isNotEmpty(gspUpkeepCheckVOS)) {
                head.put("cargoOwnerName", gspUpkeepCheckVOS.get(0).getCargoOwnerName());
                head.put("warehouseName", gspUpkeepCheckVOS.get(0).getWarehouseName());
            }
            head.put("itemHealthCategoryName",entry.getKey());
            head.put("enterpriseName",userDTO.getEnterpriseName());
            head.put("billNo", plan.getCode());
            head.put("operBy", userDTO.getNickname());
            head.put("isProtected","普通");
            if(plan.getIsProtected()!=null&&plan.getIsProtected()==1){
                head.put("isProtected","重点");
            }
            List<Map<String, Object>> tableList = new ArrayList<Map<String, Object>>();
            for (GspUpkeepCheckVO dto : entry.getValue()) {
                dto.setShowExpiredDate(DateUtils.format(dto.getValidUntil(), "yyyy-MM-dd"));
                // 格式化生产日期
                dto.setShowProductionDate(DateUtils.format(dto.getPdateFrom(), "yyyy-MM-dd"));
                dto.setQualityStatus("合格");
                // 放单纯的规格数据
                dto.setSpec(dto.getSpecification());
                dto.setSpecification(dto.getItemName() + "/" + dto.getSpecification());
                tableList.add(BeanMap.create(dto));
                rd.setHead(head);
                rd.setTable(tableList);
                rdList.add(rd);
            }
        }
        pd.setData(rdList);
        return RestMessage.newInstance(true, "success", pd);
    }

    /**
     * 批量删除待审核破损申请
     */
    @ApiOperation("更新养护打印次数")
    @PostMapping("/updateGspYHPrintCount")
    public RestMessage<Object> updateGspYHPrintCount(@NotEmpty(message = "请选择数据操作") @RequestBody String planId) {
        gspUpkeepCheckPlanMapper.updateGspYHPrintCount(planId);
        return RestMessage.newInstance(true, "success", null);
    }

}
