package com.jwipc.order.controller.pc;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Pair;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.jwipc.constant.DictCode;
import com.jwipc.constant.FlagConst;
import com.jwipc.dto.ExportDataDTO;
import com.jwipc.log.annotation.AuditLogInter;
import com.jwipc.order.dto.PurchaseOrderDetailListDTO;
import com.jwipc.order.dto.PurchaseOrderDetailUnlockDTO;
import com.jwipc.order.logic.LabelPrintSettingLogic;
import com.jwipc.order.logic.PurchaseOrderDetailLogic;
import com.jwipc.order.model.query.PurchaseOrderDetailQuery;
import com.jwipc.order.model.query.PurchaseOrderDetailsQuery;
import com.jwipc.page.PageUtil;
import com.jwipc.page.PageView;
import com.jwipc.security.LoginUtil;
import com.jwipc.util.EasyExcelUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import static com.jwipc.order.constant.ModuleConst.MODULE_ROOT;

/**
 * <p>
 * 采购订单明细接口
 * </p>
 *
 * @author wt
 * @version 1.0
 * @since 2024/3/4
 */
@RestController
@RequestMapping(MODULE_ROOT + "/purchaseOrderDetail/rest")
@RequiredArgsConstructor
@Slf4j
public class PurchaseOrderDetailRestController {
    private final PurchaseOrderDetailLogic purchaseOrderDetailLogic;
    private final LabelPrintSettingLogic labelPrintSettingLogic;

    /**
     * 采购订单明细列表数据(采购订单->订单明细数据查询)
     *
     * @return
     */
    @RequestMapping("/list")
    public PageView list(PurchaseOrderDetailQuery query) {
        PageView pageView = purchaseOrderDetailLogic.getList(query);
        return pageView;
    }

    /*
     *采购订单-》订单明细查看菜单
     */
    @AuditLogInter(value = "查询", module = "订单明细查看")
    @RequestMapping("order/details")
    public PageView details(PurchaseOrderDetailsQuery query) {
        PageView pageView = purchaseOrderDetailLogic.details(query);
        return pageView;
    }

    /**
     * 采购订单明细列表数据（送货管理->送货单创建查询）
     *
     * @return
     */
    @GetMapping("listForDeliveryCreate")
    public PageView listForDeliveryCreate(PurchaseOrderDetailQuery query) {
        final Pair<List<PurchaseOrderDetailListDTO>, Long> forDeliveryCreate =
                purchaseOrderDetailLogic.getListForDeliveryCreate(
                        query);
        return PageUtil.getPV(forDeliveryCreate.getKey(), forDeliveryCreate.getValue());
    }

    /**
     * 采购订单明细导出
     *
     * @return
     */
    @PostMapping("exportForDeliveryCreate")
    public void exportForDeliveryCreate(HttpServletResponse response, String exportFiled, String queryStr) throws
            IOException
    {
        // 查询数据列表，直接调用列表的查询，无需特殊改动
        final PurchaseOrderDetailQuery query = JSON.parseObject(queryStr, PurchaseOrderDetailQuery.class);
        final Pair<List<PurchaseOrderDetailListDTO>, Long> listLongPair =
                purchaseOrderDetailLogic.getListForDeliveryCreate(
                        query, true);
        //需要自己往里面增加
        List<ExportDataDTO> exportDataDTOS = JSON.parseArray(exportFiled, ExportDataDTO.class);
        final ExportDataDTO exportDataDTO = ExportDataDTO.builder().field("id").title("系统主键(不能删除)").build();
        exportDataDTOS.add(0, exportDataDTO);
        boolean isSpecial = false;
        if (LoginUtil.isSupplier()) {
            //判断当前的供应商是否有角色编码
            final List<String> roleCodes = LoginUtil.getRoleCodes();
            if (roleCodes.contains(DictCode.SUPPLIER_SPECIAL_ROLE)) {
                isSpecial = true;
            }
        }
        //动态导出工具类，只需要修改导出excel名称
        final List<PurchaseOrderDetailListDTO> key = listLongPair.getKey();
        for (PurchaseOrderDetailListDTO purchaseOrderDetailListDTO : key) {
            //如果已经解锁unlockFlag = 1, 则送货数量=解锁数量
            if (Objects.nonNull(purchaseOrderDetailListDTO.getUnlockFlag()) &&
                    purchaseOrderDetailListDTO.getUnlockFlag().equals(FlagConst.Y.getCode())) {
                purchaseOrderDetailListDTO.setDeliveryNum(purchaseOrderDetailListDTO.getUnlockNum());
            //送货数量=未清数量-在途送货数量   可送数量=未清数量-在途送货数量 //A-订单交货 B-计划交货
            } else if (purchaseOrderDetailListDTO.getMarkFlag().equals("A")) {
                purchaseOrderDetailListDTO.setEnableNum(
                        purchaseOrderDetailListDTO.getNoClearNum().subtract(purchaseOrderDetailListDTO.getOnlineNum()));
                purchaseOrderDetailListDTO.setDeliveryNum(
                        purchaseOrderDetailListDTO.getNoClearNum().subtract(purchaseOrderDetailListDTO.getOnlineNum()));
            //否则送货数量=可送数量
            } else {
                purchaseOrderDetailListDTO.setDeliveryNum(purchaseOrderDetailListDTO.getEnableNum());
            }
            if (isSpecial) {
                purchaseOrderDetailListDTO.setRemark(purchaseOrderDetailListDTO.getRemark());
            }
        }
        String filePrefix = "送货单创建-";
        if (StrUtil.isNotEmpty(query.getExportType()) && query.getExportType().equals("1")) {
            filePrefix = "解锁导出数据-";
        }
        //隐藏的第二行修改为不隐藏，采购说排序后会导致行不存在了，导致导入失败。 2024-09-10 邓京术
        EasyExcelUtils.trendsModelWriteTow(response,
                filePrefix + DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN), "sheet", key,
                exportDataDTOS);
    }

    /**
     * 解锁数据采购订单明细导出
     *
     * @return
     */
    @PostMapping("exportUnlockForDeliveryCreate")
    public void exportUnlockForDeliveryCreate(HttpServletResponse response, String queryStr, String exportFiled) throws
            IOException
    {
//        List<String> idList = Arrays.asList(ids.split(","));
        List<PurchaseOrderDetailUnlockDTO> list = JSON.parseArray(queryStr, PurchaseOrderDetailUnlockDTO.class);

        List<String> idList = list.stream()
                .map(item -> item.getId().toString()) // 取大写字母
                .collect(Collectors.toList());
        // 查询数据列表，直接调用列表的查询，无需特殊改动
        final List<PurchaseOrderDetailListDTO> key =
                purchaseOrderDetailLogic.getListUnlockForDeliveryCreate(idList);
        //需要自己往里面增加
        List<ExportDataDTO> exportDataDTOS = JSON.parseArray(exportFiled, ExportDataDTO.class);
        final ExportDataDTO exportDataDTO = ExportDataDTO.builder().field("id").title("系统主键(不能删除)").build();
        exportDataDTOS.add(0, exportDataDTO);
        boolean isSpecial = false;
        if (LoginUtil.isSupplier()) {
            //判断当前的供应商是否有角色编码
            final List<String> roleCodes = LoginUtil.getRoleCodes();
            if (roleCodes.contains(DictCode.SUPPLIER_SPECIAL_ROLE)) {
                isSpecial = true;
            }
        }
        //动态导出工具类，只需要修改导出excel名称
        for (PurchaseOrderDetailListDTO purchaseOrderDetailListDTO : key) {
            if (Objects.nonNull(purchaseOrderDetailListDTO.getUnlockFlag()) &&
                    purchaseOrderDetailListDTO.getUnlockFlag().equals(FlagConst.Y.getCode())) {
                purchaseOrderDetailListDTO.setDeliveryNum(purchaseOrderDetailListDTO.getUnlockNum());
            } else if (purchaseOrderDetailListDTO.getMarkFlag().equals("A")) {
                purchaseOrderDetailListDTO.setEnableNum(
                        purchaseOrderDetailListDTO.getNoClearNum().subtract(purchaseOrderDetailListDTO.getOnlineNum()));
                purchaseOrderDetailListDTO.setDeliveryNum(
                        purchaseOrderDetailListDTO.getNoClearNum().subtract(purchaseOrderDetailListDTO.getOnlineNum()));
            } else {
                purchaseOrderDetailListDTO.setDeliveryNum(purchaseOrderDetailListDTO.getEnableNum());
            }
            if (isSpecial) {
                purchaseOrderDetailListDTO.setRemark(purchaseOrderDetailListDTO.getRemark());
            }
        }
        String filePrefix = "解锁导出数据-";
        EasyExcelUtils.trendsModelWrite(response,
                filePrefix + DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN), "sheet", key,
                exportDataDTOS);
    }

    /**
     * 采购订单明细导出
     *
     * @return
     */
    @PostMapping("export")
    public void export(HttpServletResponse response, String exportFiled, String queryStr) throws IOException {
        // 查询数据列表，直接调用列表的查询，无需特殊改动
        final PurchaseOrderDetailQuery purchaseOrderQuery = JSON.parseObject(queryStr, PurchaseOrderDetailQuery.class);
        final List<PurchaseOrderDetailListDTO> exportData = purchaseOrderDetailLogic.listAll(
                purchaseOrderQuery);
        //定义空字段
        List<ExportDataDTO> exportDataDTOS = new ArrayList<>();
        exportDataDTOS.add(ExportDataDTO.builder().title("").field("id").build());
        exportDataDTOS.add(ExportDataDTO.builder().title("").field("orderId").build());
        exportDataDTOS.addAll(JSON.parseArray(exportFiled, ExportDataDTO.class));

        //动态导出工具类，只需要修改导出excel名称
        EasyExcelUtils.trendsModelWrite(response,
                "订单明细数据-" + DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN), "sheet", exportData,
                JSON.toJSONString(exportDataDTOS));
    }

    @GetMapping("getInfoForLabelPrint")
    public ResponseEntity getInfoForLabelPrint(String orderCode, String materialCode) {
        return ResponseEntity.ok(purchaseOrderDetailLogic.getInfoForLabelPrint(orderCode, materialCode));
    }

    @GetMapping("checkOriginIsRequired")
    public ResponseEntity checkOriginIsRequired(String materialCode) {
        Boolean ret = labelPrintSettingLogic.originIsRequired(materialCode);
        return ResponseEntity.ok(ret);
    }

    @GetMapping("planList")
    public PageView planList(String orderCode, String row) {
        return purchaseOrderDetailLogic.getPlanList(orderCode, row);
    }

    @GetMapping("componentList")
    public PageView componentList(String orderCode, String row, String planLine) {
        return purchaseOrderDetailLogic.getComponentList(orderCode, row, planLine);
    }

    @GetMapping("costList")
    public PageView costList(String orderCode, String row) {
        return purchaseOrderDetailLogic.getCostList(orderCode, row);
    }

    @PostMapping("unlock")
    public ResponseEntity unlock(@RequestBody List<PurchaseOrderDetailUnlockDTO> unlockDTO) {
        purchaseOrderDetailLogic.unlock(unlockDTO);
        return ResponseEntity.ok().build();
    }

    @PostMapping("importUnlock")
    public ResponseEntity importUnlock(MultipartFile file) throws IOException {
        purchaseOrderDetailLogic.importUnlock(file);
        return ResponseEntity.ok().build();
    }
}
