package com.yh.saas.plugin.yiliangyiyun.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.winsea.svc.base.base.entity.CommonCompany;
import com.winsea.svc.base.base.entity.CommonStaff;
import com.winsea.svc.base.base.service.ICommonCompanyService;
import com.winsea.svc.base.base.service.ICommonStaffService;
import com.winsea.svc.base.security.util.AuthSecurityUtils;
import com.yh.saas.common.support.util.IdGenerator;
import com.yh.saas.common.support.util.StringUtils;
import com.yh.saas.plugin.yiliangyiyun.constant.StatusEnum;
import com.yh.saas.plugin.yiliangyiyun.entity.*;
import com.yh.saas.plugin.yiliangyiyun.exception.YException;
import com.yh.saas.plugin.yiliangyiyun.exception.YExceptionEnum;
import com.yh.saas.plugin.yiliangyiyun.mapper.WeighingManagementMapper;
import com.yh.saas.plugin.yiliangyiyun.service.*;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yh.saas.plugin.yiliangyiyun.util.QRCodeUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 检斤管理 服务实现类
 * </p>
 *
 * @author Gdc
 * @since 2021-09-06
 */
@Service
public class WeighingManagementServiceImpl extends ServiceImpl<WeighingManagementMapper, WeighingManagement> implements IWeighingManagementService {

    @Autowired
    private IPaymentManagementService paymentManagementService;
    @Autowired
    private IQualityInspectionManagementService qualityInspectionManagementService;
    @Autowired
    private ICommonCompanyService commonCompanyService;
    @Autowired
    private IWarehouseBaseInfoService warehouseBaseInfoService;
    @Autowired
    private IWarehouseInOutInfoService warehouseInOutInfoService;
    @Autowired
    private IContractManagementInfoService contractManagementInfoService;
    @Autowired
    private ICommonStaffService staffService;
    @Autowired
    private QRCodeUtil qrCodeUtil;
    /**
     * 检斤管理列表
     * @param weighingManagement
     * @return
     */
    @Override
    public Page<WeighingManagement> selectWeighingManagement(WeighingManagement weighingManagement) {
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("startRecord", (weighingManagement.getCurrentPage() - 1)
                * weighingManagement.getPageSize());
        //公司id
        if (weighingManagement.getCompId() == null || weighingManagement.getCompId().isEmpty()) {
            weighingManagement.setCompId(AuthSecurityUtils.getStaffById(AuthSecurityUtils.getCurrentUserId()).getCompId());
        }
        pageView.put("compId", weighingManagement.getCompId());
        pageView.put("number", weighingManagement.getNumber());
        pageView.put("searchKeyWord", weighingManagement.getSearchKeyWord());
        pageView.put("serviceManagementType",weighingManagement.getServiceManagementType());
        pageView.put("startDate", weighingManagement.getStartDate());
        pageView.put("endDate", weighingManagement.getEndDate());
        pageView.put("statusType",weighingManagement.getStatusType());
        if(StringUtils.isEmpty(weighingManagement.getViewFlag())){
            pageView.put("pageSize", weighingManagement.getPageSize());
            pageView.put("currentPage", weighingManagement.getCurrentPage());
        }
        pageView.put("managementType", weighingManagement.getManagementType());
        pageView.put("warehouseName", weighingManagement.getWarehouseName());
        // 查询销售订单总数
        Integer dataCount = baseMapper.getCountByCondition(pageView);
        List<WeighingManagement> dataList = baseMapper.getListByCondition(pageView);
        if(StringUtils.isEmpty(weighingManagement.getViewFlag())){
        if (CollectionUtils.isNotEmpty(dataList)) {
            for (WeighingManagement weighingManagement1 : dataList) {
                CommonCompany commonCompany = commonCompanyService.selectOne(new EntityWrapper<CommonCompany>()
                        .eq("comp_id", weighingManagement1.getCompId()));
                //公司名
                if (commonCompany != null) {
                    weighingManagement1.setCompName(commonCompany.getCompName());
                }
                PaymentManagement paymentManagement = paymentManagementService.selectOne(new EntityWrapper<PaymentManagement>()
                        .eq("relation_id", weighingManagement1.getRelationId())
                        .eq("comp_id", weighingManagement1.getCompId()));
                if (paymentManagement != null) {
                    weighingManagement1.setPaymentManagement(paymentManagement);
                }
                QualityInspectionManagement qualityInspectionManagement = qualityInspectionManagementService.selectOne(new EntityWrapper<QualityInspectionManagement>()
                        .eq("relation_id", weighingManagement1.getRelationId())
                        .eq("comp_id", weighingManagement1.getCompId()));
                if (qualityInspectionManagement != null) {
                    weighingManagement1.setQualityInspectionManagement(qualityInspectionManagement);
                    WarehouseInOutInfo warehouseInOutInfo=warehouseInOutInfoService.selectById(qualityInspectionManagement.getWarehouseInOutId());
                    if (warehouseInOutInfo!=null){
                        weighingManagement1.setTranCarNo(warehouseInOutInfo.getTranCarNo());
                    }
                }
                WarehouseBaseInfo warehouseBaseInfo = warehouseBaseInfoService.selectOne(new EntityWrapper<WarehouseBaseInfo>()
                        .eq("comp_id", weighingManagement1.getCompId())
                        .eq("warehouse_name", weighingManagement1.getWarehouseName()));
                if (warehouseBaseInfo != null) {
                    //仓库负责人,电话
                    weighingManagement1.setPerson(warehouseBaseInfo.getPersonCharge());
                    weighingManagement1.setPersonPhone(warehouseBaseInfo.getPersonPhone());
                    weighingManagement1.setAutomaticWeightAcquisition(warehouseBaseInfo.getAutomaticWeightAcquisition());
                }
            }
        }
    }
        Page<WeighingManagement> page = new Page<>();
        page.setRecords(dataList == null ? Lists.newArrayList() : dataList);
        page.setTotal(dataCount == null ? 0 : dataCount);
        page.setCurrent(weighingManagement.getCurrentPage());
        page.setSize(weighingManagement.getPageSize());
        return page;
    }

    /**
     * 毛重检斤
     * @param weighingManagement
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String editGrossWeight(WeighingManagement weighingManagement) {
        //状态改为已称毛重
        weighingManagement.setStatus(StatusEnum.WEIGHED_GROSS_WEIGHT.getName());
        weighingManagement.setStatusFlag(StatusEnum.WEIGHED_GROSS_WEIGHT.getFlag());
        weighingManagement.setGrossDate(new Date());
        CommonStaff commonStaff = staffService.getInfo(AuthSecurityUtils.getCurrentUserId());
        weighingManagement.setSecretaryWeigher(commonStaff.getStaffName());
        //质检信息
        QualityInspectionManagement qualityInspectionManagement = qualityInspectionManagementService.selectOne(new EntityWrapper<QualityInspectionManagement>()
                .eq("relation_id", weighingManagement.getRelationId())
                .eq("comp_id", commonStaff.getCompId()));
        if (qualityInspectionManagement!=null){
            //状态改为已称毛重
//            qualityInspectionManagement.setStatus(StatusEnum.WEIGHED_GROSS_WEIGHT.getName());
//            qualityInspectionManagement.setStatusFlag(StatusEnum.WEIGHED_GROSS_WEIGHT.getFlag());
            qualityInspectionManagementService.updateById(qualityInspectionManagement);
        }
//        if ("3".equals(weighingManagement.getManagementType())){
//
//
//
//            WeighingManagement weighingManagement1=this.selectById(weighingManagement.getId());
//            //查关联的收款信息
//            PaymentManagement paymentManagement=paymentManagementService.selectOne(new EntityWrapper<PaymentManagement>()
//                    .eq("relation_id",weighingManagement1.getRelationId()));
//            if (paymentManagement!=null){
//                paymentManagement.setNetWeight(weighingManagement.getGrossWeight());
//                paymentManagementService.updateById(paymentManagement);
//            }
//            else {
//                //生成收款信息
//                PaymentManagement paymentManagement1=new PaymentManagement();
//                paymentManagement1.setId(IdGenerator.generateUUID());
//                paymentManagement1.setRelationId(weighingManagement1.getRelationId());
//                paymentManagement1.setCompId(weighingManagement1.getCompId());
//                paymentManagement1.setCarNo(weighingManagement1.getCarNumber());
//                paymentManagement1.setGoodsName(weighingManagement1.getGoodsName());
//                paymentManagement1.setContractNo(weighingManagement1.getContractNo());
//                paymentManagement1.setGrossWeight(weighingManagement.getGrossWeight());
//                paymentManagement1.setTare(weighingManagement1.getTare());
//                paymentManagement1.setNetWeight(weighingManagement.getNetWeight());
//                //计算应收
//                paymentManagement1.setCalculationCollectable(weighingManagement1.getContractPrice()*weighingManagement.getNetWeight());
//                //实际应收
//                paymentManagement1.setActualCollectionment(paymentManagement1.getCalculationCollectable());
//                //未收
//                paymentManagement1.setAmountNotCollectable(paymentManagement1.getCalculationCollectable());
//                //已收
//                paymentManagement1.setAmountEdCollectionable(0.0f);
//                paymentManagement1.setManagementType("3");
//                paymentManagement1.setWarehouseName(weighingManagement1.getWarehouseName());
//                paymentManagementService.insert(paymentManagement1);
//            }
//        }
//
        boolean one = this.updateById(weighingManagement);
        if (one) {
            return "OK";
        } else {
            return "NG";
        }
    }

    /**
     * 皮重检斤
     * @param weighingManagement
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String editTare(WeighingManagement weighingManagement) {
        WeighingManagement weighingManagement1=this.selectById(weighingManagement.getId());
        //状态改为已称皮重
        weighingManagement.setStatus(StatusEnum.TARED.getName());
        weighingManagement.setStatusFlag(StatusEnum.TARED.getFlag());
        weighingManagement.setTareDate(new Date());
        CommonStaff commonStaff = staffService.getInfo(AuthSecurityUtils.getCurrentUserId());
        weighingManagement.setSkinInspector(commonStaff.getStaffName());
        //质检信息
        QualityInspectionManagement qualityInspectionManagement1 = qualityInspectionManagementService.selectOne(new EntityWrapper<QualityInspectionManagement>()
                .eq("relation_id", weighingManagement1.getRelationId())
                .eq("comp_id", weighingManagement1.getCompId()));
        if (qualityInspectionManagement1!=null){
            //状态改为已称皮重
//            qualityInspectionManagement1.setStatus(StatusEnum.TARED.getName());
//            qualityInspectionManagement1.setStatusFlag(StatusEnum.TARED.getFlag());
            qualityInspectionManagementService.updateById(qualityInspectionManagement1);
        }
        //收购业务
        if("1".equals(weighingManagement1.getManagementType())&&"3".equals(weighingManagement1.getServiceManagementType())){
            //查关联的付款信息
            PaymentManagement paymentManagement=paymentManagementService.selectOne(new EntityWrapper<PaymentManagement>()
                    .eq("relation_id",weighingManagement1.getRelationId())
                    .eq("comp_id", weighingManagement1.getCompId()));
            if (paymentManagement!=null){
                paymentManagement.setNetWeight(weighingManagement.getNetWeight());
                paymentManagement.setGrossWeight(weighingManagement1.getGrossWeight());
                paymentManagement.setTare(weighingManagement.getTare());
                paymentManagementService.updateById(paymentManagement);
            }
            else {
                //生成付款信息
                PaymentManagement paymentManagement1=new PaymentManagement();
                paymentManagement1.setId(IdGenerator.generateUUID());
                paymentManagement1.setRelationId(weighingManagement1.getRelationId());
                paymentManagement1.setCompId(weighingManagement1.getCompId());
                paymentManagement1.setCustomerNumberCard(weighingManagement1.getCustomerNumberCard());
                paymentManagement1.setPaymentNo(weighingManagement1.getNumber());
                paymentManagement1.setContractNo(weighingManagement1.getContractNo());
                paymentManagement1.setCustomerName(weighingManagement1.getCustomer());
                paymentManagement1.setCustomerPhone(weighingManagement1.getCustomerPhone());
                paymentManagement1.setCarNo(weighingManagement1.getCarNumber());
                paymentManagement1.setType(weighingManagement1.getType());
                paymentManagement1.setGoodsName(weighingManagement1.getGoodsName());
//                if ("潮粮".equals(weighingManagement1.getType())){
//                    //查收购设置数据
//                    PurchasePrice purchasePrice=purchasePriceService.selectOne(new EntityWrapper<PurchasePrice>()
//                            .eq("warehouse_id",weighingManagement.getWarehouseId())
//                            .eq("goods_name",weighingManagement.getGoodsName()));
//                    Float pureWeight=weighingManagement.getNetWeight()* (100-(Float.valueOf(qualityInspectionManagement1.getWaterContent())-purchasePrice.getWaterMin())*purchasePrice.getDeductWeight())/100;
//                    paymentManagement1.setPureWeight(pureWeight);
//                }
                paymentManagement1.setStatus(StatusEnum.TO_BE_SETTLED.getName());
                paymentManagement1.setStatusFlag(StatusEnum.TO_BE_SETTLED.getFlag());
                paymentManagement1.setNetWeight(weighingManagement.getNetWeight());
                paymentManagement1.setManagementType("1");
                paymentManagement1.setGrossWeight(weighingManagement1.getGrossWeight());
                paymentManagement1.setTare(weighingManagement.getTare());
                paymentManagement1.setWarehouseName(weighingManagement1.getWarehouseName());
                //质检信息
                QualityInspectionManagement qualityInspectionManagement = qualityInspectionManagementService.selectOne(new EntityWrapper<QualityInspectionManagement>()
                        .eq("relation_id", weighingManagement1.getRelationId())
                        .eq("comp_id", weighingManagement1.getCompId()));
                if (qualityInspectionManagement!=null){
                    if ("潮粮".equals(weighingManagement1.getType())) {
                        paymentManagement1.setTidalGrainPrice(qualityInspectionManagement.getTidalGrainPrice());
                    }
                    else{
                        paymentManagement1.setTidalGrainPrice(qualityInspectionManagement.getDryGrainPrice());
                    }
                }
                paymentManagementService.insert(paymentManagement1);
            }
        }
        boolean one = this.updateById(weighingManagement);
        if (one) {
            return weighingManagement.getId();
        } else {
            return "NG";
        }
    }

    /**
     * 删除检斤管理信息
     *  @param id
     * @return
     */
    @Override
    public void deleteWeightcheck(String id) {
        //查询检斤管理信息
        WeighingManagement weighingManagement = this.selectById(id);
        if(weighingManagement != null){
            //无关联的付款信息时可删除
            PaymentManagement paymentManagement = paymentManagementService.selectOne(new EntityWrapper<PaymentManagement>()
                    .eq("relation_id", weighingManagement.getRelationId())
                    .eq("comp_id", weighingManagement.getCompId()));
            if (paymentManagement==null){
                //删除关联的质检信息
                QualityInspectionManagement qualityInspectionManagement = qualityInspectionManagementService.selectOne(new EntityWrapper<QualityInspectionManagement>()
                        .eq("relation_id", weighingManagement.getRelationId())
                        .eq("comp_id", weighingManagement.getCompId()));
                //删除检斤管理信息,质检管理信息
                this.deleteById(weighingManagement.getId());
                qualityInspectionManagementService.deleteById(qualityInspectionManagement.getId());
            }
            else{
                throw new YException(YExceptionEnum.PAYMENT_NOT_DELETED_ERROR);
            }
        }
    }

    /**
     * 查看检斤信息
     * @param id
     * @return
     */
    @Override
    public WeighingManagement getWeighingManagement(String id) {
        WeighingManagement weighingManagement = this.selectById(id);
        if (weighingManagement!=null){
            CommonCompany commonCompany=commonCompanyService.selectOne(new EntityWrapper<CommonCompany>()
                    .eq("comp_id",weighingManagement.getCompId()));
            //公司名
            if (commonCompany!=null){
                weighingManagement.setCompName(commonCompany.getCompName());
            }
            ContractManagementInfo contractManagementInfo=contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                    .eq("comp_id",weighingManagement.getCompId())
                    .eq("contract_no",weighingManagement.getContractNo()));
            if (contractManagementInfo!=null){
                weighingManagement.setContractManagement(contractManagementInfo);
            }
            WarehouseBaseInfo warehouseBaseInfo=warehouseBaseInfoService.selectOne(new EntityWrapper<WarehouseBaseInfo>()
                    .eq("comp_id",weighingManagement.getCompId())
                    .eq("warehouse_name",weighingManagement.getWarehouseName()));
            if (warehouseBaseInfo!=null){
                //仓库负责人,电话
                weighingManagement.setPerson(warehouseBaseInfo.getPersonCharge());
                weighingManagement.setPersonPhone(warehouseBaseInfo.getPersonPhone());
            }
            //质检信息
            QualityInspectionManagement qualityInspectionManagement = qualityInspectionManagementService.selectOne(new EntityWrapper<QualityInspectionManagement>()
                    .eq("relation_id", weighingManagement.getRelationId())
                    .eq("comp_id", weighingManagement.getCompId()));
            if (qualityInspectionManagement!=null) {
                weighingManagement.setQualityInspectionManagement(qualityInspectionManagement);
            }
            weighingManagement.setCodeUrl(qrCodeUtil.generateQRCodeImage(qualityInspectionManagement.getCompId()+"&"+qualityInspectionManagement.getQualityNo()+"&"+warehouseBaseInfo.getId(),800,800,"",qualityInspectionManagement.getId()));

        }
        return weighingManagement;
    }

    /**
     * 出库管理添加皮重检斤管理信息
     * @param weighingManagement
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addTare(WeighingManagement weighingManagement) {
        String relationId=IdGenerator.generateUUID();
        weighingManagement.setId(IdGenerator.generateUUID());
        //判断质检编号是否唯一
        List<WeighingManagement> weighingManagementList =
                this.selectList(new EntityWrapper<WeighingManagement>()
                        .eq("comp_id",weighingManagement.getCompId())
                        .eq("number", weighingManagement.getNumber()));
        if (weighingManagementList.size() > 0) {
            throw new YException(YExceptionEnum.QUALITY_NO_ERROR);
        }
        weighingManagement.setRelationId(relationId);
        weighingManagement.setTareDate(new Date());
        weighingManagement.setManagementType("3");
        //出库类型
        weighingManagement.setServiceManagementType("2");
        //状态改为已称皮重
        weighingManagement.setStatus(StatusEnum.TARED.getName());
        weighingManagement.setStatusFlag(StatusEnum.TARED.getFlag());
        //生成质检信息
        QualityInspectionManagement qualityInspectionManagement = new QualityInspectionManagement();
        qualityInspectionManagement.setId(IdGenerator.generateUUID());
        qualityInspectionManagement.setRelationId(weighingManagement.getRelationId());
        qualityInspectionManagement.setContractNo(weighingManagement.getContractNo());
        qualityInspectionManagement.setQualityNo(weighingManagement.getNumber());
        qualityInspectionManagement.setWarehouseInOutId(weighingManagement.getWarehouseInOutId());
        qualityInspectionManagement.setCarNumber(weighingManagement.getCarNumber());
        qualityInspectionManagement.setCompId(weighingManagement.getCompId());
        qualityInspectionManagement.setGoodsName(weighingManagement.getGoodsName());
        qualityInspectionManagement.setBinNumber(weighingManagement.getBinNumber());
        qualityInspectionManagement.setStatus(StatusEnum.TARED.getName());
        qualityInspectionManagement.setStatusFlag(StatusEnum.TARED.getFlag());
        qualityInspectionManagement.setManagementType("3");
        qualityInspectionManagement.setServiceManagementType("2");
        qualityInspectionManagement.setQualityDate(new Date());
        qualityInspectionManagement.setWarehouseName(weighingManagement.getWarehouseName());
        qualityInspectionManagement.setStorageTagNo(weighingManagement.getStorageNumber());
        boolean two=qualityInspectionManagementService.insert(qualityInspectionManagement);
        boolean one=this.insert(weighingManagement);
        //成功返回ok
        if (one &&two ) {
            return weighingManagement.getId();
        } else {
            return "NG";
        }
    }

    /**
     * 出库管理编辑皮重检斤管理信息
     * @param weighingManagement
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String editTareOut(WeighingManagement weighingManagement) {
        //状态改为已称皮重
        weighingManagement.setStatus(StatusEnum.TARED.getName());
        weighingManagement.setStatusFlag(StatusEnum.TARED.getFlag());
        //更新检斤信息
        boolean one = this.updateById(weighingManagement);
        //更新质检信息
        boolean two = qualityInspectionManagementService.updateById(weighingManagement.getQualityInspectionManagement());
        //成功返回ok
        if (one &&two ) {
            return weighingManagement.getId();
        } else {
            return "NG";
        }
    }

    /**
     * 扫描二维码
     * @param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public WeighingManagement getQRcode(WeighingManagement weighingManagement) {
        //查询检斤信息
        WeighingManagement weighingManagement1 = this.selectOne(new EntityWrapper<WeighingManagement>()
            .eq("comp_id",weighingManagement.getCompId())
            .eq("number",weighingManagement.getNumber())
            .eq("delete_flag","0"));
        //查询质检信息
        QualityInspectionManagement qualityInspectionManagement = qualityInspectionManagementService.selectOne(new EntityWrapper<QualityInspectionManagement>()
                .eq("comp_id",weighingManagement.getCompId())
                .eq("quality_no",weighingManagement.getNumber())
                .eq("delete_flag","0"));
        weighingManagement1.setQualityInspectionManagement(qualityInspectionManagement);
        //查询付款信息
        PaymentManagement paymentManagement = paymentManagementService.selectOne(new EntityWrapper<PaymentManagement>()
                .eq("comp_id",weighingManagement.getCompId())
                .eq("payment_no",weighingManagement.getNumber())
                .eq("delete_flag","0"));
        weighingManagement1.setPaymentManagement(paymentManagement);
        //查询仓库信息
        WarehouseBaseInfo warehouseBaseInfo = warehouseBaseInfoService.selectOne(new EntityWrapper<WarehouseBaseInfo>()
                .eq("id",weighingManagement.getWarehouseId())
                .eq("delete_flag","0"));
        weighingManagement1.setWarehouseBaseInfo(warehouseBaseInfo);
        return weighingManagement1;
    }
}
