package com.zfire.mall.manager.logic.ship;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zfire.mall.manager.bean.ExcelData;
import com.zfire.mall.manager.bean.admin.AdminUserCom;
import com.zfire.mall.manager.bean.invoice.InvoiceApplicationOrderBody;
import com.zfire.mall.manager.bean.invoice.InvoiceApplicationOrderProjectBody;
import com.zfire.mall.manager.bean.requisition.RequisitionBean;
import com.zfire.mall.manager.bean.ship.ShipDocumentBean;
import com.zfire.mall.manager.bean.ship.ShipDocumentDetail;
import com.zfire.mall.manager.bean.ship.ShipDocumentProjectBean;
import com.zfire.mall.manager.bean.ship.ShipDocumentProjectDetail;
import com.zfire.mall.manager.commonmapper.InvoiceMapper;
import com.zfire.mall.manager.commonmapper.ShipMapper;
import com.zfire.mall.manager.enums.InvoiceCustomerEnum;
import com.zfire.mall.manager.logic.common.CommonLogic;
import com.zfire.mall.manager.logic.invoice.InvoiceLogic;
import com.zfire.mall.manager.plus.entity.*;
import com.zfire.mall.manager.enums.ExamineStatusEnum;
import com.zfire.mall.manager.plus.service.PickManagerService;
import com.zfire.mall.manager.plus.service.PickManagerShipService;
import com.zfire.mall.manager.plus.service.ShipDocumentPasswordService;
import com.zfire.mall.manager.plus.service.ShipDocumentService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author change
 */
@Service
@Slf4j
public class ShipLogic {

    @Autowired
    ShipMapper shipMapper;

    @Autowired
    ShipDocumentService shipDocumentService;


    @Autowired
    ShipDocumentPasswordService shipDocumentPasswordService;

    @Autowired
    InvoiceMapper invoiceMapper;

    @Autowired
    InvoiceLogic invoiceLogic;

    @Autowired
    CommonLogic commonLogic;

    @Autowired
    PickManagerShipService pickManagerShipService;

    @Autowired
    PickManagerService pickManagerService;

    public IPage<ShipDocumentBean> list(String k3serviceId,String id,String mainOrderId,String categoryName, String customerName, String materialName, String specification, String startTime,
                                        String endTime, String customerNumber, Integer pageNum, Integer pageSize,String serviceId) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : "";

        IPage<ShipDocumentBean> list = shipMapper.list(new Page<>(pageNum, pageSize),k3serviceId, id,mainOrderId, customerName, materialName, specification, startTime,
                endTime, customerNumber,customerId,adminUser.getServiceIds(),categoryName,serviceId,adminUser.getK3CategoryIds());
        return list;
    }

    public ShipDocumentDetail detail(String id) {
        ShipDocumentDetail shipDocumentDetail = shipMapper.detailShip(id);
        for (InvoiceApplicationOrderBody shipDocumentOrder : shipDocumentDetail.getInvoicePickBeans()) {
            PickManagerShip one = pickManagerShipService.lambdaQuery().eq(PickManagerShip::getInvoiceOrderId, shipDocumentOrder.getId()).last("limit 1").one();

            if (one != null) {
                PickManager pickManager = pickManagerService.getById(one.getPickId());
                shipDocumentDetail.setPickType(pickManager.getPickType());
            }
            shipDocumentOrder.setEnginOrderNo(shipDocumentDetail.getEnginOrderNo());
        }
        return shipDocumentDetail;
    }

    public void update(ShipDocument shipDocument) {
        shipDocumentService.updateById(shipDocument);
    }

    public IPage<ShipDocumentProjectBean> listProject(String refRegionWork,String mainOrderId,String id,String enginOrderNo,String categoryName,String refEnginRecordNo, String customerName,
                                                      String materialName, String specification, String startTime, String endTime, String customerNumber,
                                                      Integer pageNum, Integer pageSize, String orderType,String serviceId) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : "";

        IPage<ShipDocumentProjectBean> shipDocumentProjectBeanIPage = shipMapper.listProject(new Page<>(pageNum, pageSize), refRegionWork,mainOrderId,id,enginOrderNo,categoryName,refEnginRecordNo, customerName, materialName,
                specification, startTime, endTime, customerNumber, orderType,customerId,adminUser.getServiceIds(),serviceId);
        return shipDocumentProjectBeanIPage;
    }

    public ShipDocumentProjectDetail detailProject(String id) {
        ShipDocumentProjectDetail detail = shipMapper.detailProject(id);
        for (InvoiceApplicationOrderProjectBody shipDocumentOrder : detail.getInvoicePickBeans()) {
            shipDocumentOrder.setEnginOrderNo(detail.getEnginOrderNo());
        }
        return detail;
    }

    public Integer shipPassword(String id) {
        int i = (int) ((Math.random() * 9 + 1) * 100000);
        ShipDocumentPassword shipDocumentPassword = new ShipDocumentPassword();
        shipDocumentPassword.setShipId(id);
        shipDocumentPassword.setPrintPassword(i);
        shipDocumentPassword.insert();
        return i;
    }


    public IPage<ShipDocumentPassword> listShipPassword(String id, Integer pageNum, Integer pageSize) {
        return shipDocumentPasswordService.lambdaQuery().eq(ShipDocumentPassword::getShipId,id).page(new Page<>(pageNum,pageSize));
    }

    /**
     * 退货单数据导出
     * @param shipDocumentBeans
     * @return
     */
    public ExcelData eExport(List<ShipDocumentBean> shipDocumentBeans){
        String[] titles = new String[]{"销售类型","发货单号","发货日期","仓库","订单号","经销商编码","经销商名称","存货类别", "物料编码","厂产品代码","产品名称",
                "规格型号","价税合计","无税金额","无税单价","数量","未出库数量","订单备注","发货申请备注","表体备注","表头业务员","表体业务员","存货分类","物料分组"};
        List<List<Object>> rows = new ArrayList<>();
        for (ShipDocumentBean shipDocumentBean : shipDocumentBeans) {
            List<Object> row = new ArrayList<>();
            row.add(shipDocumentBean.getSaleTypeName());
            row.add(shipDocumentBean.getId());
            row.add(DateUtil.formatDateTime(shipDocumentBean.getOrderTime()));
            row.add(shipDocumentBean.getCorrespondName());
            row.add(shipDocumentBean.getMainOrderId());
            row.add(shipDocumentBean.getCustomerNumber());
            row.add(shipDocumentBean.getCustomerName());
            row.add(shipDocumentBean.getCategoryName());
            row.add(shipDocumentBean.getMaterialCode());
            row.add(shipDocumentBean.getMaterialOldNumber());
            row.add(shipDocumentBean.getMaterialName());
            row.add(shipDocumentBean.getSpecification());
          //  row.add(shipDocumentBean.getTotalPrice());
          //  row.add(shipDocumentBean.getPrice() * shipDocumentBean.getQty());
            row.add(shipDocumentBean.getPayAmount());
            row.add(shipDocumentBean.getNoTotalAmount());
            row.add(shipDocumentBean.getAfterTaxPrice());
            row.add(shipDocumentBean.getRefundableQty());
            row.add(shipDocumentBean.getSalesStatus().equals(0)?shipDocumentBean.getRefundableQty():0);
            row.add(shipDocumentBean.getHeaderRemark());
            row.add(shipDocumentBean.getRemark());
            row.add(shipDocumentBean.getInvoiceRemark());
            row.add(shipDocumentBean.getK3ServiceName());
            row.add(shipDocumentBean.getServiceName());
            row.add(shipDocumentBean.getCategoryName());
            row.add(shipDocumentBean.getMaterialGroupName());
            rows.add(row);
        }
        ExcelData excelData = new ExcelData();
        excelData.setRows(rows);
        excelData.setTitles(Arrays.asList(titles));
        return excelData;
    }

    /**
     * 工程发货单数据导出
     * @param shipDocumentBeans
     * @return
     */
    public ExcelData pExport(List<ShipDocumentProjectBean> shipDocumentBeans){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String[] titles;
        if (StringUtils.isNotEmpty(adminUser.getCustomerNumber()) && (adminUser.getCustomerNumber().equals(InvoiceCustomerEnum.GEJIANG_FOSHAN.getCode())
                || adminUser.getCustomerNumber().equals(InvoiceCustomerEnum.GEJIANG_FOSHAN.getCode()))) {
            titles = new String[]{"发货单号", "发货申请日期", "仓库", "工程登录编号", "工程名称",
                    "使用单位", "经销商编码", "经销商名称", "产品名称", "规格型号", "计量单位",
                    "数量", "备注信息", "制单人", "制单日期", "审单人", "审单日期", "订单号", "工程编号", "单价", "总金额", "返利金额","同步到格匠采购入库单","同步失败原因","存货分类","物料分组"};
        }else {
            titles = new String[]{"发货单号", "发货申请日期", "仓库", "工程登录编号", "工程名称",
                    "使用单位", "经销商编码", "经销商名称", "产品名称", "规格型号", "计量单位",
                    "数量", "备注信息", "制单人", "制单日期", "审单人", "审单日期", "订单号", "工程编号", "单价", "总金额", "返利金额","存货分类","物料分组"};
        }
        List<List<Object>> rows = new ArrayList<>();
        for (ShipDocumentProjectBean shipDocumentBean : shipDocumentBeans) {
            List<Object> row = new ArrayList<>();
            row.add(shipDocumentBean.getId());
            row.add(DateUtil.formatDate(shipDocumentBean.getOrderTime()));
            row.add(shipDocumentBean.getCorrespondName());
            row.add(shipDocumentBean.getRefEnginRecordNo());
            row.add(shipDocumentBean.getRefProjectName());
            row.add(shipDocumentBean.getRefUseUnit());
            row.add(shipDocumentBean.getCustomerNumber());
            row.add(shipDocumentBean.getCustomerName());
            row.add(shipDocumentBean.getMaterialName());
            row.add(shipDocumentBean.getSpecification());
            row.add(shipDocumentBean.getUnit());
            row.add(shipDocumentBean.getRefundableQty());
            row.add(shipDocumentBean.getRemark());
            row.add(shipDocumentBean.getCreateBy());
            row.add(DateUtil.formatDate(shipDocumentBean.getCreateTime()));
            row.add(shipDocumentBean.getApprovalName());
            row.add(DateUtil.formatDate(shipDocumentBean.getApprovalTime()));
            row.add(shipDocumentBean.getEnginOrderNo());
            row.add(shipDocumentBean.getRefProjectNo());
            row.add(shipDocumentBean.getSinglePayPrice());
            row.add(shipDocumentBean.getPayAmount());
            row.add(shipDocumentBean.getRebateAmount());
            row.add(shipDocumentBean.getCategoryName());
            row.add(shipDocumentBean.getMaterialGroupName());
            rows.add(row);
        }
        ExcelData excelData = new ExcelData();
        excelData.setRows(rows);
        excelData.setTitles(Arrays.asList(titles));
        return excelData;
    }

    public ExcelData pProjectExport(List<ShipDocumentProjectBean> records) {
        String[] titles = new String[]{"发货单号","发货申请日期","仓库","订单号","工程登录编号","经销商编码","经销商名称",
                "使用单位","产品名称","物料编码","厂产品代码","规格型号", "数量","单价","总金额","安装地址","联系人","固定电话",
                "移动电话","销售类型","项目类别","行业类别","跨区厂编号","保证函","不扣押金",
                "第几次申报","备注信息","格力内部备注","区域","业务员","实装物料编号","实装厂产品编码","实装规格型号",
                "发货申请备注","二级经销商代码",
                "制单人","制单日期","审单人","审单日期","返利金额","存货类别","物料分组"};
        List<List<Object>> rows = new ArrayList<>();
        for (ShipDocumentProjectBean shipDocumentBean : records) {
            List<Object> row = new ArrayList<>();
            row.add(shipDocumentBean.getId());
            row.add(DateUtil.formatDate(shipDocumentBean.getOrderTime()));
            row.add(shipDocumentBean.getCorrespondName());
            row.add(shipDocumentBean.getEnginOrderNo());
            row.add(shipDocumentBean.getRefEnginRecordNo());
            row.add(shipDocumentBean.getCustomerNumber());
            row.add(shipDocumentBean.getCustomerName());
            row.add(shipDocumentBean.getRefUseUnit());
            row.add(shipDocumentBean.getMaterialName());
            row.add(shipDocumentBean.getMaterialCode());
            row.add(shipDocumentBean.getMaterialOldNumber());
            row.add(shipDocumentBean.getSpecification());
            row.add(shipDocumentBean.getRefundableQty());
            row.add(shipDocumentBean.getSinglePayPrice());
            row.add(shipDocumentBean.getPayAmount());
            row.add(shipDocumentBean.getRefInstallAddress());
            row.add(shipDocumentBean.getRefLinkman());
            row.add(shipDocumentBean.getRefTel());
            row.add(shipDocumentBean.getRefPhone());
            row.add(shipDocumentBean.getSaleTypeName());
            row.add(shipDocumentBean.getRefProjectType());
            row.add(shipDocumentBean.getRefTradeCategory());
            row.add(shipDocumentBean.getRefFactoryNo());
            row.add(shipDocumentBean.getRefPromiseProvide());
            row.add(shipDocumentBean.getTakeDeposit()?"不扣":"扣");
            row.add(shipDocumentBean.getRefDeclareNo());
            row.add(shipDocumentBean.getHeaderRemark());
            row.add(shipDocumentBean.getGeLiInerNote());
            row.add(shipDocumentBean.getRefRegionWork());
            row.add(shipDocumentBean.getK3ServiceName());
            row.add(shipDocumentBean.getRealMaterialNumber());
            row.add(shipDocumentBean.getRealMaterialOldNumber());
            row.add(shipDocumentBean.getRealSpecification());
            row.add(shipDocumentBean.getRemark());
            row.add(shipDocumentBean.getSecondCustomerNumber());
            row.add(shipDocumentBean.getCreateBy());
            row.add(DateUtil.formatDate(shipDocumentBean.getCreateTime()));
            row.add(shipDocumentBean.getApprovalName());
            row.add(DateUtil.formatDate(shipDocumentBean.getApprovalTime()));
            row.add(shipDocumentBean.getRebateAmount());
            row.add(shipDocumentBean.getCategoryName());
            row.add(shipDocumentBean.getMaterialGroupName());
            rows.add(row);
        }
        ExcelData excelData = new ExcelData();
        excelData.setRows(rows);
        excelData.setTitles(Arrays.asList(titles));
        return excelData;
    }
}
