package com.zfire.mall.manager.bean.engin.info;

import cn.hutool.core.date.DateUtil;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.zfire.mall.manager.bean.admin.AdminUserCom;
import com.zfire.mall.manager.bean.valid.EditGroup;
import com.zfire.mall.manager.bean.valid.NotBeforeToday;
import com.zfire.mall.manager.enums.ExamineStatusEnum;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.plus.entity.EnginInfoOrder;
import com.zfire.mall.manager.plus.entity.EnginInfoOrderItem;
import com.zfire.mall.manager.plus.entity.KingDeeMaterial;
import com.zfire.mall.manager.plus.entity.SaleType;
import com.zfire.mall.manager.plus.service.KingDeeMaterialService;
import com.zfire.mall.manager.plus.service.SaleTypeService;
import com.zfire.mall.manager.utils.ApplicationContextUtils;
import com.zfire.mall.manager.utils.CommonUtils;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.BeanUtils;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Data
@ApiModel
@NoArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties(value = { "createBy","createName","createTime","updateBy","updateName","updateTime","submitBy"
        ,"submitName","submitTime","confirmBy","confirmName","confirmTime" }, allowGetters = true)
public class EnginInfoOrderBean {

    private static final long serialVersionUID=1L;

    @NotBlank(message = "工程信息id不能为空", groups = EditGroup.class)
    @ApiModelProperty(value = "工程信息id")
    private String enginInfoId;

    @ApiModelProperty(value = "企业id")
    private String adminCompanyId;

    @ApiModelProperty(value = "工程信息单号")
    private String enginInfoNo;

    @ApiModelProperty(value = "订单日期")
    private Date orderDate;

//    @NotBlank(message = "产品大类不能空")
    @ApiModelProperty(value = "产品大类")
    private String mainId;

    @ApiModelProperty(value = "产品大类名称")
    private String mainName;

    @ApiModelProperty(value = "客户id")
    private String customerId;

    @ApiModelProperty(value = "客户编码")
    private String customerNumber;

    @ApiModelProperty(value = "客户名称")
    private String customerName;

    @ApiModelProperty(value = "项目名称")
    private String projectName;

    @ApiModelProperty(value = "项目类型")
    private String projectType;

    @ApiModelProperty(value = "项目说明")
    private String projectNote;

    @ApiModelProperty(value = "机型类型")
    private String machineType;

    @ApiModelProperty(value = "使用单位")
    private String useUnit;

    @ApiModelProperty(value = "安装地址")
    private String installAddress;

    @ApiModelProperty(value = "工程编号")
    private String projectNo;

    @ApiModelProperty(value = "厂工程编号")
    private String enginFactoryNo;

    @ApiModelProperty(value = "工程登录类型")
    private String enginSignType;

    @ApiModelProperty(value = "行业类别")
    private String tradeCategory;

    @ApiModelProperty(value = "联系人")
    private String linkman;

    @ApiModelProperty(value = "联系电话")
    private String phone;

    @ApiModelProperty(value = "固定电话")
    private String tel;

    @ApiModelProperty(value = "第几申报")
    private String declareNo;

    @ApiModelProperty(value = "权限分类")
    private String powerCategory;

    @NotBlank(message = "业务员不能为空")
    @ApiModelProperty(value = "业务员")
    private String serviceId;

    @ApiModelProperty(value = "业务员名称")
    private String serviceName;

    @NotNull(message = "合同有效期不能为空")
    @NotBeforeToday(message = "不能少于当前日期")
    @ApiModelProperty(value = "合同有效期")
    @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
    private Date contractExpireDate;

    @ApiModelProperty(value = "提前完结状态 true=提前完结  false=未提前完结")
    private Boolean endStatus;

    @ApiModelProperty(value = "格力回复")
    private String geLiNote;

    @ApiModelProperty(value = "格力内部备注")
    private String geLiInerNote;

    @ApiModelProperty(value = "文件编号")
    private String fileNo;

    @ApiModelProperty(value = "备注")
    private String remark;

    @ApiModelProperty(value = "审核说明")
    private String examineNote;

    @ApiModelProperty(value = "单据状态 SAVE=保存 WAIT=待审核 OK=通过 FAIL=不通过 CLOSE=关闭")
    private String examineStatus;

    @ApiModelProperty(value = "创建人")
    private String createBy;

    @ApiModelProperty(value = "创建人名称")
    private String createName;

    @ApiModelProperty(value = "创建时间")
    private Date createTime;

    @ApiModelProperty(value = "更新人")
    private String updateBy;

    @ApiModelProperty(value = "更新人名称")
    private String updateName;

    @ApiModelProperty(value = "更新时间")
    private Date updateTime;

    @ApiModelProperty(value = "提交人")
    private String submitBy;

    @ApiModelProperty(value = "提交人名称")
    private String submitName;

    @ApiModelProperty(value = "提交时间")
    private Date submitTime;

    @ApiModelProperty(value = "审核人")
    private String confirmBy;

    @ApiModelProperty(value = "审核人名称")
    private String confirmName;

    @ApiModelProperty(value = "审核时间")
    private Date confirmTime;

    @ApiModelProperty(value = "弃审人")
    private String abandonBy;

    @ApiModelProperty(value = "弃审人名称")
    private String abandonName;

    @ApiModelProperty(value = "是否计划单 true=是 false=否")
    private Boolean isPlanOrder;

    @ApiModelProperty(value = "弃审时间")
    private Date abandonTime;

    @NotEmpty(message = "工程信息明细不能空")
    @Size(min = 1, message = "调价明细不能长度少于1")
    @ApiModelProperty(value = "工程信息明细")
    private List<EnginInfoOrderItemBean> items;

    @ApiModelProperty(value = "审批结果")
    private boolean examineResult = false;

    public EnginInfoOrder handleTargetInfo(AdminUserCom adminUser) {
//        ProductCategory productCategory = productCategoryService.lambdaQuery()
//                .eq(ProductCategory::getProductCategoryId, this.mainId)
//                .one();
//        if (Objects.isNull(productCategory)) {
//            throw new RemoteServiceException("产品大类不存在");
//        }
//        this.mainName = productCategory.getProductCategoryName();

        EnginInfoOrder enginInfoOrder = new EnginInfoOrder();
        BeanUtils.copyProperties(this, enginInfoOrder);
        enginInfoOrder.setCreateBy(CommonUtils.getUsername())
                .setContractExpireDate(DateUtil.parseDateTime(DateUtil.formatDate(enginInfoOrder.getContractExpireDate()) + " 23:59:59"))
                .setCreateName(CommonUtils.getNickName())
                .setUpdateBy(CommonUtils.getUsername())
                .setUpdateName(CommonUtils.getNickName())
                .setExamineStatus(ExamineStatusEnum.SAVE.toString());

        return enginInfoOrder;
    }


    public List<EnginInfoOrderItem> handleTargetItem() {
        KingDeeMaterialService kingDeeMaterialService = ApplicationContextUtils.getBean(KingDeeMaterialService.class);
        SaleTypeService saleTypeService = ApplicationContextUtils.getBean(SaleTypeService.class);

        List<KingDeeMaterial> kingDeeMaterials = kingDeeMaterialService.lambdaQuery()
                .in(KingDeeMaterial::getId, this.items.stream()
                        .map(EnginInfoOrderItemBean::getMaterialId)
                        .collect(Collectors.toList())).list();

        List<SaleType> saleTypes = saleTypeService.lambdaQuery()
                .in(SaleType::getId, items.stream().map(EnginInfoOrderItemBean::getSaleTypeId).distinct().collect(Collectors.toList()))
                .list();

        Map<String, KingDeeMaterial> kingDeeMaterialMap = kingDeeMaterials.stream()
                .collect(Collectors.toMap(KingDeeMaterial::getId, Function.identity(), (key1, key2) -> key2));

        Map<String, SaleType> saleTypeMap = saleTypes.stream()
                .collect(Collectors.toMap(SaleType::getId, Function.identity()));

        // 去重复
        Collection<EnginInfoOrderItemBean> items = this.items.stream()
                .collect(Collectors.toMap(v -> v.getSaleTypeId() + "|" + v.getMaterialId(),
                        Function.identity(),
                        (key1, key2) -> key2))
                .values();

        return items.stream().map(enginInfoOrderItemBean -> {
            EnginInfoOrderItem infoOrderItem = new EnginInfoOrderItem();
            KingDeeMaterial kingDeeMaterial = kingDeeMaterialMap.get(enginInfoOrderItemBean.getMaterialId());
            SaleType saleType = saleTypeMap.get(enginInfoOrderItemBean.getSaleTypeId());
            if (Objects.isNull(kingDeeMaterial)) {
                throw new RemoteServiceException(enginInfoOrderItemBean.getMaterialName() + "：产品不存在，请检查");
            }
            if (Objects.isNull(saleType)) {
                throw new RemoteServiceException("销售类型不能为空");
            }
            BeanUtils.copyProperties(enginInfoOrderItemBean, infoOrderItem);

            infoOrderItem.setId(null)
                    .setEnginInfoId(this.enginInfoId)
                    .setEnginInfoNo(this.enginInfoNo)
                    .setSaleTypeId(enginInfoOrderItemBean.getSaleTypeId())
                    .setSaleTypeCode(saleType.getSaleCode())
                    .setSaleTypeName(saleType.getSaleName())
                    .setMaterialName(kingDeeMaterial.getName())
                    .setMaterialNumber(kingDeeMaterial.getNumber())
                    .setMaterialOldNumber(kingDeeMaterial.getOldNumber())
                    .setSpecification(kingDeeMaterial.getSpecification())
                    .setUnit(kingDeeMaterial.getBaseUnitId())
                    .setK3CategoryId(kingDeeMaterial.getCategoryId())
                    .setK3CategoryName(kingDeeMaterial.getCategoryName())
                    .setK3CategoryNumber(kingDeeMaterial.getCategoryNumber())
                    .setTaxRate(kingDeeMaterial.getTaxRateId());
            return infoOrderItem;
        }).collect(Collectors.toList());
    }

}
