package com.zfire.mall.manager.bean.manage.product.price;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
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.ExamineGroup;
import com.zfire.mall.manager.bean.valid.SubmitGroup;
import com.zfire.mall.manager.commonmapper.manage.product.ProductUpdPriceBillReserveMapper;
import com.zfire.mall.manager.enums.ExamineStatusEnum;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.plus.entity.KingDeeMaterial;
import com.zfire.mall.manager.plus.entity.ProductUpdPriceBill;
import com.zfire.mall.manager.plus.entity.ProductUpdPriceBillItem;
import com.zfire.mall.manager.plus.entity.SaleType;
import com.zfire.mall.manager.plus.service.KingDeeMaterialService;
import com.zfire.mall.manager.plus.service.ProductUpdPriceBillItemWalletService;
import com.zfire.mall.manager.plus.service.SaleTypeService;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;


@Data
@ApiModel(value="ProductUpdPriceBillBean对象", description="ProductUpdPriceBillBean对象")
@JsonIgnoreProperties(value = { "createBy","createName","createTime","updateBy","updateName","updateTime","submitBy"
        ,"submitName","submitTime","confirmBy","confirmName","confirmTime","closeBy","closeName","closeTime" }
        , allowGetters = true)
public class ProductUpdPriceBillBean {
    private static final long serialVersionUID=1L;

    @NotBlank(message = "编码不能空", groups = { EditGroup.class, SubmitGroup.class, ExamineGroup.class })
    @ApiModelProperty(value = "编码", notes = "添加时非填充，编辑时必填")
    private String updPriceBillId;

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

    //@NotBlank(message = "请选择部门")
    @ApiModelProperty(value = "部门id", required = true)
    private String adminWebsitId;

    //@NotNull(message = "部门名称不能为空")
    @ApiModelProperty(value = "部门id", required = true)
    private String adminWebsitName;

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

    //@NotNull(message = "业务员名称不能为空")
    @ApiModelProperty(value = "业务员名称", required = true)
    private String serviceName;

    @ApiModelProperty(value = "单据类型 GENERAL=普通 HOME=家用工程")
    private String billType = "GENERAL";

    @ApiModelProperty(value = "单据状态 SAVE=保存 WAIT=提交 OK=通过 FAIL=不通过", notes = "非填充")
    private String examineStatus;

    @ApiModelProperty(value = "备注", notes = "非必填")
    private String remark;

    @ApiModelProperty(value = "审核说明", notes = "非必填")
    private String examineNote;

    @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;

    @Valid
    @NotEmpty(message = "调价明细不能空")
    @ApiModelProperty(value = "调价明细")
    private List<ProductUpdPriceBillItemBean> items;



    public ProductUpdPriceBill generateBillLogic(ProductUpdPriceBillBean productUpdPriceBillBean, AdminUserCom adminUser) {
        productUpdPriceBillBean.setUpdPriceBillId("PUP" + IdWorker.getIdStr());
        productUpdPriceBillBean.setAdminCompanyId(adminUser.getAdminCompanyId());
        productUpdPriceBillBean.setExamineStatus(ExamineStatusEnum.SAVE.toString());

        // 插入主表数据
        ProductUpdPriceBill productUpdPriceBill = new ProductUpdPriceBill();
        BeanUtils.copyProperties(productUpdPriceBillBean, productUpdPriceBill);
        productUpdPriceBill.setCreateName(adminUser.getNickName())
                .setUpdateName(adminUser.getNickName());

        return productUpdPriceBill;
    }

    public void insertItem(ProductUpdPriceBillItemWalletService productUpdPriceBillItemWalletService,
                           ProductUpdPriceBillReserveMapper productUpdPriceBillReserveMapper,
                           SaleTypeService saleTypeService,
                           KingDeeMaterialService kingDeeMaterialService,String billType) {
        List<ProductUpdPriceBillItemBean> items = this.getItems();
        List<SaleType> saleTypes = saleTypeService.lambdaQuery()
                .in(SaleType::getId, items.stream().map(ProductUpdPriceBillItemBean::getSaleTypeId).distinct().collect(Collectors.toList()))
                .list();

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

        // 去重处理
//        items = items.stream().filter(CommonUtils.distinctByKey(ProductUpdPriceBillItemBean::getSaleTypeId))
//                .filter(CommonUtils.distinctByKey(ProductUpdPriceBillItemBean::getMaterialNumber))
//                .collect(Collectors.toList());

        for (ProductUpdPriceBillItemBean item : items) {
            SaleType saleType = saleTypeMap.get(item.getSaleTypeId());
            if (Objects.isNull(saleType)) {
                throw new RemoteServiceException("销售类型不能为空");
            }
            if (CollectionUtils.isEmpty(item.getWallets())) {
                throw new RemoteServiceException("请选择支付钱包");
            }
            KingDeeMaterial kingDeeMaterial = kingDeeMaterialService.getById(item.getMaterialId());

//            MainBean mainBean = productUpdPriceBillReserveMapper.queryMain(item.getMaterialId());

            item.setUpdPriceBillId(this.getUpdPriceBillId());
            item.setSaleTypeName(saleType.getSaleName());
            item.setSaleTypeCode(saleType.getSaleCode());
//            if(mainBean != null) {
//                item.setMainId(mainBean.getMainId());
//                item.setMainName(mainBean.getMainName());
//            }

            ProductUpdPriceBillItem productUpdPriceBillItem = new ProductUpdPriceBillItem();
            BeanUtils.copyProperties(item, productUpdPriceBillItem);

            if (Objects.nonNull(productUpdPriceBillItem.getEndDate()) && !DateUtil.formatDateTime(productUpdPriceBillItem.getEndDate()).contains("23:59:59")) {
                String formatDateTime = DateUtil.formatDateTime(productUpdPriceBillItem.getEndDate());
                String[] splitDate = formatDateTime.split(" ");
                productUpdPriceBillItem.setEndDate(DateUtil.parseDateTime(splitDate[0] + " 23:59:59"));
            }

            if(kingDeeMaterial != null) {
                productUpdPriceBillItem.setK3CategoryId(kingDeeMaterial.getCategoryId());
                productUpdPriceBillItem.setK3CategoryNumber(kingDeeMaterial.getCategoryNumber());
                productUpdPriceBillItem.setK3CategoryName(kingDeeMaterial.getCategoryName());
            }
            productUpdPriceBillItem.setBillType(billType);

            productUpdPriceBillItem.insert();

            item.getWallets().forEach(wallet -> {
                wallet.setUpdPriceBillId(this.getUpdPriceBillId())
                        .setUpdPriceBillItemId(productUpdPriceBillItem.getId());
            });

            productUpdPriceBillItemWalletService.saveBatch(item.getWallets());
        }
    }
}
