package com.huigou.topsun.sap.nonProducePick.controller;

import com.huigou.cache.DictUtil;
import com.huigou.context.Operator;
import com.huigou.context.OrgUnit;
import com.huigou.data.domain.query.QueryPageRequest;
import com.huigou.topsun.common.CommonUtils;
import com.huigou.topsun.ep.change.domain.query.EpChangeFormQueryRequest;
import com.huigou.topsun.sap.nonProducePick.application.NonProducePickApplication;
import com.huigou.topsun.sap.nonProducePick.application.NonProducePickItemApplication;
import com.huigou.topsun.sap.nonProducePick.domain.NonProducePick;
import com.huigou.topsun.sap.nonProducePick.domain.NonProducePickItem;
import com.huigou.topsun.sap.nonProducePick.domain.query.NonProducePickQueryRequest;
import com.huigou.topsun.sap.nonProducePick.vo.PDABackPickVo;
import com.huigou.topsun.sap.nonProducePick.vo.PDANonProducePickItemVo;
import com.huigou.topsun.sap.purchaseOrder.controller.SapPurchaseOrderController;
import com.huigou.uasp.annotation.ControllerMapping;
import com.huigou.uasp.annotation.SkipAuth;
import com.huigou.uasp.bmp.common.BizBillStatus;
import com.huigou.uasp.client.CommonController;
import com.huigou.util.ClassHelper;
import com.huigou.util.JSONUtil;
import com.huigou.util.SDO;
import com.topsunit.query.annotations.Param;
import org.apache.commons.lang.StringUtils;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.krysalis.barcode4j.HumanReadablePlacement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther: xin.lu
 * @Date: 2024/03/13/10:45
 * @Description:
 */
@Controller
@ControllerMapping("/nonProducePick")
//@CrossOrigin(origins = "*")

public class NonProducePickController extends CommonController {
    private final static Logger LOG = LoggerFactory.getLogger(NonProducePickController.class);
    @Override
    protected String getPagePath() {
        return "/biz/topsun/sap/nonProducePick/";
    }

    @Resource
    private NonProducePickApplication nonProducePickApplication;
    @Autowired
    private NonProducePickItemApplication nonProducePickItemApplication;

    public String forwardNonProducePickList(){
        return forward("nonProducePickList");
    }

    public String slicedNonProducePickList(){
        SDO sdo = this.getSDO();
        NonProducePickQueryRequest queryRequest = sdo.toQueryRequest(NonProducePickQueryRequest.class);
        Map<String, Object> map = nonProducePickApplication.slicedNonProducePickList(queryRequest);
        return toResult(map);
    }

    public String forwardNonProducePickDetail(){
        this.putAttribute("processDefinitionKey", NonProducePickApplication.PROCESS_DEFINITION_KEY);
        // 新增的时候procUnitId一定要设置成Apply，不然jsp页面的所有表单元素是readonly状态
        this.putAttribute("procUnitId", "Apply");
        NonProducePick nonProducePick = new NonProducePick();
        nonProducePick.setStatusId(BizBillStatus.APPLYING.getId());
        /**
         * 设置jsp页面初始化填充数据，如果不设置， 那么在jsp页面上填写完表单之后立即提交申请TaskDescription获取不到时间和相关人员信息
         */
        Operator operator = getOperator();
        nonProducePick.setDefaultValues(new OrgUnit(operator.getFullId(), operator.getFullName()));
        nonProducePick.setIsChargeOff("0");
        return forward("nonProducePickDetail",nonProducePick);
    }

    public String showNonProducePickDetail(){
        SDO sdo = this.getSDO();
        String id = sdo.getBizId();
        NonProducePick nonProducePick = nonProducePickApplication.findNonProducePickById(id);
        return forward("nonProducePickDetail",nonProducePick);
    }

    /**
     * 打印
     * @return
     */
    public String print() {
        SDO sdo = this.getSDO();
        String id = sdo.getId();
        NonProducePick nonProducePick = this.nonProducePickApplication.findNonProducePickById(id);
        Map<String, Object> map = ClassHelper.beanToMap(nonProducePick);
        if (StringUtils.isNotBlank(nonProducePick.getKostl())) {
            map.put("pickType","成本中心领料");
        }
        if (StringUtils.isNotBlank(nonProducePick.getAufnr())) {
            map.put("pickType","内部订单领料");
        }
        // 获取Grid数据
        List<NonProducePickItem> itemList = nonProducePickItemApplication.findByNonProducePickId(id);
        map.put("printTime", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm").format(LocalDateTime.now()));
        map.put("itemList", itemList);
        BigDecimal bigDecimal = itemList.stream().map(NonProducePickItem::getErfmg).reduce(BigDecimal.ZERO, BigDecimal::add);
        map.put("count",bigDecimal);
        Set<String> usedSet = itemList.stream()
                .map(nonProducePickItem -> {
                    return DictUtil.getDictionaryDetailText("used",nonProducePickItem.getUsed());
                })
                .collect(Collectors.toSet());
        String used = String.join(",", usedSet);
        map.put("used",used);
        File file = new File(nonProducePick.getMessage()+".png");
        if(!file.exists()) {
            String IMG_TYPE_PNG = "image/png";
            try {
                map.put("barCode", CommonUtils.genBarCode128(nonProducePick.getMessage(), IMG_TYPE_PNG, file,128,10, HumanReadablePlacement.HRP_NONE));
            } catch (IOException e) {
                throw new RuntimeException("条形码生成失败：" + e.getMessage());
            }
        } else {
            map.put("barCode",file);
        }
        String pintPage = String.format("/print/topsun/nonProducePick.ftl");
        return outputAndProcUnitHandlerPDF(pintPage, id, map);
    }

    public String chargeOff(){
        SDO sdo = this.getSDO();
        String message = sdo.getString("message");
        nonProducePickApplication.chargeOff(message);
        return success();
    }

    //// 允许多个域名
    //@CrossOrigin(origins = {"http://front1.com", "http://front2.com"})
    @SkipAuth
    @RequestMapping( value = "/getNonProducePick",method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getNonProducePick(@RequestBody Map<String, List<String>> requestBody){
        LOG.info("PDA退料查询数据=={}", JSONUtil.toString(requestBody));
        HashMap<String, Object> messageMap = new HashMap<>();
        messageMap.put("CODE","S");
        messageMap.put("MSG","成功");
        List<PDANonProducePickItemVo> itemVoList = new ArrayList<>();
        try {
            List<String> rsnums = requestBody.get("rsnums");
            itemVoList = nonProducePickApplication.getNonProducePick(rsnums);
            messageMap.put("DATA",itemVoList);
        }catch (RuntimeException e){
            messageMap.put("CODE","E");
            messageMap.put("MSG",e.getMessage());
            messageMap.put("DATA","");
        }
        return messageMap;
    }

    @SkipAuth
    @RequestMapping( value = "/backNonProducePick",method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> backNonProducePick(@RequestBody PDABackPickVo requestBody){
        LOG.info("PDA退料返回数据=={}", JSONUtil.toString(requestBody));
        HashMap<String, Object> messageMap = new HashMap<>();
        messageMap.put("CODE","S");
        messageMap.put("MSG","成功");
        messageMap.put("DATA","");
        try {
            nonProducePickApplication.backNonProducePick(requestBody);
        }catch (RuntimeException e){
            messageMap.put("CODE","E");
            messageMap.put("MSG",e.getMessage());
            messageMap.put("DATA","");
        }
        return messageMap;
    }
}
