package com.huigou.topsun.ep.change.controller;

import com.huigou.cache.DictUtil;
import com.huigou.cache.SystemCache;
import com.huigou.context.Operator;
import com.huigou.context.OrgUnit;
import com.huigou.data.domain.query.QueryPageRequest;
import com.huigou.topsun.ep.change.application.EpChangeFormApplication;
import com.huigou.topsun.ep.change.application.EpChangeFormImplItemApplication;
import com.huigou.topsun.ep.change.application.EpChangeFormStockItemApplication;
import com.huigou.topsun.ep.change.domain.EpChangeForm;
import com.huigou.topsun.ep.change.domain.query.EpChangeFormQueryRequest;
import com.huigou.topsun.ep.order.controller.EpSaleOrderCancelController;
import com.huigou.uasp.annotation.ControllerMapping;
import com.huigou.uasp.bmp.common.BizBillStatus;
import com.huigou.uasp.bpm.engine.application.ActApplication;
import com.huigou.uasp.client.CommonController;
import com.huigou.util.SDO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: xin.lu
 * @Date: 2024/06/19/10:05
 * @Description:
 */
@Controller
@ControllerMapping("/epChangeForm")
public class EpChangeFormController extends CommonController {
    private final static Logger LOG = LoggerFactory.getLogger(EpChangeFormController.class);
    @Override
    protected String getPagePath() {
        return "/biz/topsun/ep/change/";
    }

    @Resource
    private EpChangeFormApplication epChangeFormApplication;
    @Autowired
    private EpChangeFormImplItemApplication changeFormImplItemApplication;
    @Autowired
    private EpChangeFormStockItemApplication changeFormStockItemApplication;
    @Autowired
    private ActApplication actApplication;

    public String forwardEpChangeFormList(){
        return forward("epChangeFormList");
    }

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

    public String forwardEpChangeFormDetail(){
        this.putAttribute("processDefinitionKey", EpChangeFormApplication.PROCESS_DEFINITION_KEY);
        // 新增的时候procUnitId一定要设置成Apply，不然jsp页面的所有表单元素是readonly状态
        this.putAttribute("procUnitId", "Apply");
        EpChangeForm epChangeForm = new EpChangeForm();
        epChangeForm.setStatusId(BizBillStatus.APPLYING.getId());
        /**
         * 设置jsp页面初始化填充数据，如果不设置， 那么在jsp页面上填写完表单之后立即提交申请TaskDescription获取不到时间和相关人员信息
         */
        Operator operator = getOperator();
        epChangeForm.setDefaultValues(new OrgUnit(operator.getFullId(), operator.getFullName()));
        Map<String, String> reasonForChange = new HashMap<>();
        String type = this.getSDO().getString("type");
        if ("product".equals(type)){
            reasonForChange = DictUtil.getDictionary("reasonForChange");
            reasonForChange.remove("MATERIAL CHANGE");
            this.putAttribute("reasonForChangeList",reasonForChange);
            return forward("epChangeFormDetail",epChangeForm);
        }else {
            epChangeForm.setReasonForChange("MATERIAL CHANGE");
            return forward("epMaterialChangeFormDetail",epChangeForm);
        }
    }

    public String showEpChangeFormDetail(){
        SDO sdo = this.getSDO();
        String id = sdo.getBizId();
        EpChangeForm epChangeForm = epChangeFormApplication.findEpChangeFormById(id);
        Map<String, String> reasonForChange = new HashMap<>();
        if ("MATERIAL CHANGE".equals(epChangeForm.getReasonForChange())){
            return forward("epMaterialChangeFormDetail",epChangeForm);
        }
        reasonForChange = DictUtil.getDictionary("reasonForChange");
        reasonForChange.remove("MATERIAL CHANGE");
        this.putAttribute("reasonForChangeList",reasonForChange);
        return forward("epChangeFormDetail",epChangeForm);
    }

    public String slicedEpChangeFormImplItems(){
        SDO sdo = this.getSDO();
        EpChangeFormQueryRequest queryRequest = sdo.toQueryRequest(EpChangeFormQueryRequest.class);
        return toResult(changeFormImplItemApplication.findByEpChangeFormId(queryRequest));
    }

    public String slicedEpChangeFormStockItems(){
        SDO sdo = this.getSDO();
        EpChangeFormQueryRequest queryRequest = sdo.toQueryRequest(EpChangeFormQueryRequest.class);
        //String epChangeFormId = sdo.getString("epChangeFormId");
        return toResult(changeFormStockItemApplication.findByEpChangeFormId(queryRequest));
    }

    public String deleteEpChangeFormImplItem(){
        SDO sdo = this.getSDO();
        List<String> ids = sdo.getIds();
        changeFormImplItemApplication.deleteItems(ids);
        return success();
    }

    public String deleteEpChangeFormStockItem(){
        SDO sdo = this.getSDO();
        List<String> ids = sdo.getIds();
        changeFormStockItemApplication.deleteItems(ids);
        return success();
    }

    /**
     * 打印
     * @return
     */
    public String print() {
        SDO sdo = this.getSDO();
        String id = sdo.getId();
        EpChangeFormQueryRequest queryRequest = sdo.toQueryRequest(EpChangeFormQueryRequest.class);
        queryRequest.setId(id);
        Map<String, Object> objectMap = this.epChangeFormApplication.slicedEpChangeFormList(queryRequest);
        List<Map<String, Object>> objectMaps = (List<Map<String, Object>>) objectMap.get("Rows");
        Map<String,Object> map = objectMaps.get(0);
        map.put("deptName",map.get("deptName")+"-"+map.get("personMemberName"));
        String[] split = map.get("reasonForChange").toString().split(",");
        String[] splitText = map.get("reasonForChangeTextView").toString().split(",");
        List<String> strings = Arrays.asList(split);
        List<String> stringTexts = Arrays.asList(splitText);
        StringBuilder change = new StringBuilder();
        for (int i = 0; i < strings.size(); i++) {
            String s = strings.get(i);
            change.append("  √ ").append(s).append(" ").append(stringTexts.get(i));
        }
        map.put("reasonForChange",change.toString());

        StringBuilder effective = new StringBuilder();
        String[] splitE = map.get("changeEffective").toString().split(",");
        String[] splitETextView = map.get("changeEffectiveTextView").toString().split(",");
        List<String> stringList = Arrays.asList(splitE);
        List<String> stringListTextView = Arrays.asList(splitETextView);
        for (int i = 0; i < stringList.size(); i++) {
            String s = stringList.get(i);
            effective.append("  √  ").append(s).append(" ").append(stringListTextView.get(i));
        }
        map.put("changeEffective",effective.toString());
        File file = new File(SystemCache.getRealPath() +"/images/bsnLogo.png");
        try {
            FileInputStream inputFile = new FileInputStream(file);
            byte[] buffer = new byte[inputFile.available()];
            inputFile.read(buffer);
            inputFile.close();
            BASE64Encoder base64Encoder = new BASE64Encoder();
            String encode = base64Encoder.encode(buffer);
            map.put("bsnPng",encode);
        }catch (Exception e) {
            LOG.error("异常信息:" + e.getMessage());
        }
        // 获取Grid数据
        QueryPageRequest pageModel = queryRequest.getPageModel();
        pageModel.setPageSize(20);
        queryRequest.setPageModel(pageModel);
        queryRequest.setEpChangeFormId(id);
        Map<String, Object> implItemMap = changeFormImplItemApplication.findByEpChangeFormId(queryRequest);
        Map<String, Object> stockItemMap = changeFormStockItemApplication.findByEpChangeFormId(queryRequest);
        List<Map<String, Object>> mapList = this.epChangeFormApplication.queryApprovalPersons(id);
        List<Map<String, Object>> implItemMaps = (List<Map<String, Object>>) implItemMap.get("Rows");
        List<Map<String, Object>> stockItemMaps = (List<Map<String, Object>>) stockItemMap.get("Rows");
        map.put("printTime", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm").format(LocalDateTime.now()));
        map.put("implItemMaps", implItemMaps);
        map.put("stockItemMaps", stockItemMaps);
        map.put("approvals", mapList);
        String pintPage = String.format("/print/topsun/epChangeForm.ftl");
        return outputAndProcUnitHandlerPDF(pintPage, id, map);
    }
}
