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.plugin.yiliangyiyun.constant.NumberConstant;
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.QualityInspectionManagementMapper;
import com.yh.saas.plugin.yiliangyiyun.service.*;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yh.saas.plugin.yiliangyiyun.util.Const;
import com.yh.saas.plugin.yiliangyiyun.util.QRCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 记录质检管理数据信息 服务实现类
 * </p>
 *
 * @author Gdc
 * @since 2021-09-06
 */
@Service
public class QualityInspectionManagementServiceImpl extends ServiceImpl<QualityInspectionManagementMapper, QualityInspectionManagement> implements IQualityInspectionManagementService {
    @Autowired
    private IWeighingManagementService weighingManagementService;
    @Autowired
    private IPurchasePriceService purchasePriceService;
    @Autowired
    private ICommonCompanyService commonCompanyService;
    @Autowired
    private IWarehouseBaseInfoService warehouseBaseInfoService;
    @Autowired
    private IWarehouseInOutInfoService warehouseInOutInfoService;
    @Autowired
    private IWarehousePositionInfoService warehousePositionInfoService;
    @Autowired
    private IPaymentManagementService paymentManagementService;
    @Autowired
    private IShippingInformationService shippingInformationService;
    @Autowired
    private IContractManagementInfoService contractManagementInfoService;
    @Autowired
    private IIdentityAuthenticationInfoService identityAuthenticationInfoService;
    @Autowired
    private ICommonStaffService staffService;
    @Autowired
    private ICommonSysParameterService iCommonSysParameterService;
    @Autowired
    private QRCodeUtil qrCodeUtil ;

    @Autowired
    private CacheComponent cacheComponent;

    /**
     * 质检管理列表
     * @param qualityInspectionManagement
     * @return
     */
    @Override
        public Page<QualityInspectionManagement> selectQualityInspection(QualityInspectionManagement qualityInspectionManagement) {
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("startRecord", (qualityInspectionManagement.getCurrentPage() - 1)
                * qualityInspectionManagement.getPageSize());
        //公司id
        if(qualityInspectionManagement.getCompId() == null || qualityInspectionManagement.getCompId().isEmpty()){
            qualityInspectionManagement.setCompId(AuthSecurityUtils.getStaffById(AuthSecurityUtils.getCurrentUserId()).getCompId());
        }
        pageView.put("compId",qualityInspectionManagement.getCompId());
        pageView.put("searchKeyWord",qualityInspectionManagement.getSearchKeyWord());
        pageView.put("pageSize",qualityInspectionManagement.getPageSize());
        pageView.put("currentPage",qualityInspectionManagement.getCurrentPage());
        pageView.put("warehouseName",qualityInspectionManagement.getWarehouseName());
        pageView.put("managementType",qualityInspectionManagement.getManagementType());
        pageView.put("serviceManagementType",qualityInspectionManagement.getServiceManagementType());
        pageView.put("statusType",qualityInspectionManagement.getStatusType());
        pageView.put("qualityType",qualityInspectionManagement.getQualityType());

        // 查询销售订单总数
        Integer dataCount = baseMapper.getCountByCondition(pageView);
        List<QualityInspectionManagement> dataList = baseMapper.getListByCondition(pageView);
        for (QualityInspectionManagement qualityInspectionManagement1:dataList) {
            WeighingManagement weighingManagement = weighingManagementService.selectOne(new EntityWrapper<WeighingManagement>()
                    .eq("relation_id", qualityInspectionManagement1.getRelationId())
                    .eq("comp_id", qualityInspectionManagement.getCompId()));
            if (weighingManagement != null) {
                qualityInspectionManagement1.setWeighingManagement(weighingManagement);
            }
            ContractManagementInfo contractManagementInfo=contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                    .eq("comp_id",qualityInspectionManagement.getCompId())
                    .eq("contract_no",qualityInspectionManagement1.getContractNo()));
            if (contractManagementInfo!=null){
                qualityInspectionManagement1.setContractManagement(contractManagementInfo);
            }
        }
        Page<QualityInspectionManagement> page = new Page<>();
        page.setRecords(dataList == null ? Lists.newArrayList() : dataList);
        page.setTotal(dataCount == null ? 0 : dataCount);
        page.setCurrent(qualityInspectionManagement.getCurrentPage());
        page.setSize(qualityInspectionManagement.getPageSize());
        return page;
    }


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


    /**
     * 查看质检管理信息
     *  @param id
     * @return
     */
    @Override
    public QualityInspectionManagement getQualityInspection(String id) {
        //查询质检管理信息
        QualityInspectionManagement qualityInspectionManagement = this.selectById(id);
        if (qualityInspectionManagement!=null){
            CommonCompany commonCompany=commonCompanyService.selectOne(new EntityWrapper<CommonCompany>()
            .eq("comp_id",qualityInspectionManagement.getCompId()));
            //公司名
            if (commonCompany!=null){
                qualityInspectionManagement.setCompName(commonCompany.getCompName());
            }
            WarehouseBaseInfo warehouseBaseInfo=warehouseBaseInfoService.selectOne(new EntityWrapper<WarehouseBaseInfo>()
                    .eq("comp_id",qualityInspectionManagement.getCompId())
            .eq("warehouse_name",qualityInspectionManagement.getWarehouseName()));
            if (warehouseBaseInfo!=null){
                //仓库负责人,电话
                qualityInspectionManagement.setPerson(warehouseBaseInfo.getPersonCharge());
                qualityInspectionManagement.setPersonPhone(warehouseBaseInfo.getPersonPhone());
            }
            WarehouseInOutInfo warehouseInOutInfo=warehouseInOutInfoService.selectById(qualityInspectionManagement.getWarehouseInOutId());
            if (warehouseInOutInfo!=null){
                qualityInspectionManagement.setPositionId(warehouseInOutInfo.getPositionId());
            }
            //客户信息
            IdentityAuthenticationInfo identityAuthenticationInfo = identityAuthenticationInfoService.selectOne(new EntityWrapper<IdentityAuthenticationInfo>()
                    .eq("comp_id", qualityInspectionManagement.getCompId())
                    .eq("customer_name",qualityInspectionManagement.getCustomerName())
                    .eq("customer_phone",qualityInspectionManagement.getCustomerPhone()));
            if(identityAuthenticationInfo != null){
                //客户身份证号
                qualityInspectionManagement.setCustomerNumberCard(identityAuthenticationInfo.getCustomerNumberCard());
            }
            //检斤信息
            WeighingManagement weighingManagement = weighingManagementService.selectOne(new EntityWrapper<WeighingManagement>()
                    .eq("relation_id", qualityInspectionManagement.getRelationId())
                    .eq("comp_id", qualityInspectionManagement.getCompId()));
            if (weighingManagement!=null) {
                qualityInspectionManagement.setWeighingManagement(weighingManagement);
            }
            qualityInspectionManagement.setCodeUrl(qrCodeUtil.generateQRCodeImage(qualityInspectionManagement.getCompId()+"&"+qualityInspectionManagement.getQualityNo()+"&"+warehouseBaseInfo.getId(),800,800,"",qualityInspectionManagement.getId()));
        }
        return qualityInspectionManagement;
    }


    /**
     * 编辑质检管理信息
     * @param qualityInspectionManagement
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String editQualityInspection(QualityInspectionManagement qualityInspectionManagement) {
        CommonStaff commonStaff = staffService.getInfo(AuthSecurityUtils.getCurrentUserId());
        //复检
        if ("1".equals(qualityInspectionManagement.getFlag())){
            qualityInspectionManagement.setReInspector(commonStaff.getStaffName());
            //状态为已复检
            qualityInspectionManagement.setStatus(StatusEnum.COMPLEX_INSPECTED.getName());
            qualityInspectionManagement.setStatusFlag(StatusEnum.COMPLEX_INSPECTED.getFlag());
        }
        //确认
        else if ("2".equals(qualityInspectionManagement.getFlag())){
            qualityInspectionManagement.setConfirm("1");
            WeighingManagement weighingManagement = weighingManagementService.selectOne(new EntityWrapper<WeighingManagement>()
                    .eq("comp_id",qualityInspectionManagement.getCompId())
                    .eq("delete_flag","0")
                    .eq("relation_id", qualityInspectionManagement.getRelationId()));
            if(weighingManagement!=null){
                weighingManagement.setStorageNumber(qualityInspectionManagement.getStorageTagNo());
                weighingManagement.setBinNumber(qualityInspectionManagement.getBinNumber());
                weighingManagementService.updateById(weighingManagement);
            }
        }
        //钎样
        else if ("3".equals(qualityInspectionManagement.getFlag())){
            this.updateById(qualityInspectionManagement);
        }
        else if("0".equals(qualityInspectionManagement.getBrazer()) && qualityInspectionManagement.getBrazer()!= null){
            //质检员初检，状态改为已初检
            qualityInspectionManagement.setStatus(StatusEnum.FIRST_INSPECTED.getName());
            qualityInspectionManagement.setStatusFlag(StatusEnum.FIRST_INSPECTED.getFlag());
        }
        if(qualityInspectionManagement.getCost() == null){
            qualityInspectionManagement.setCost(Float.parseFloat((qualityInspectionManagement.getDryGrainPrice()==null?0:qualityInspectionManagement.getDryGrainPrice())*1000 + ""));
        }
        boolean one=this.updateById(qualityInspectionManagement);
        QualityInspectionManagement qualityInspectionManagement1=this.selectById(qualityInspectionManagement.getId());
        PaymentManagement paymentManagement=paymentManagementService.selectOne(new EntityWrapper<PaymentManagement>()
                .eq("relation_id",qualityInspectionManagement1.getRelationId())
                .eq("status","待结算")
                .isNull("approve_status")
                .eq("comp_id", qualityInspectionManagement1.getCompId()));
        if (paymentManagement!=null){
            if (qualityInspectionManagement1.getGoodsName().contains("潮粮")){
                paymentManagement.setTidalGrainPrice(qualityInspectionManagement1.getTidalGrainPrice());
            }
            else {
                paymentManagement.setSolidGrainPrice(qualityInspectionManagement1.getDryGrainPrice());
            }
            paymentManagement.setCustomerName(qualityInspectionManagement1.getCustomerName());
            paymentManagement.setCustomerPhone(qualityInspectionManagement1.getCustomerPhone());
            paymentManagement.setCustomerNumberCard(qualityInspectionManagement.getCustomerNumberCard());
            paymentManagementService.updateById(paymentManagement);
        }
        WeighingManagement weighingManagement = weighingManagementService.selectOne(new EntityWrapper<WeighingManagement>()
                .eq("comp_id",qualityInspectionManagement1.getCompId())
                .eq("delete_flag","0")
                .eq("relation_id", qualityInspectionManagement1.getRelationId()));
        if(weighingManagement!=null){
            weighingManagement.setStorageNumber(qualityInspectionManagement1.getStorageTagNo());
            weighingManagement.setBinNumber(qualityInspectionManagement1.getBinNumber());
            weighingManagement.setCarNumber(qualityInspectionManagement1.getCarNumber());
            weighingManagement.setCustomer(qualityInspectionManagement1.getCustomerName());
            weighingManagement.setCustomerPhone(qualityInspectionManagement1.getCustomerPhone());
            weighingManagement.setCustomerNumberCard(qualityInspectionManagement.getCustomerNumberCard());
            weighingManagementService.updateById(weighingManagement);
        }
        WarehouseInOutInfo warehouseInOutInfo = warehouseInOutInfoService.selectById(qualityInspectionManagement.getWarehouseInOutId());
        if(warehouseInOutInfo != null){
            WarehousePositionInfo warehousePositionInfo = warehousePositionInfoService.selectOne(new EntityWrapper<WarehousePositionInfo>()
                    .eq("bin_number",qualityInspectionManagement1.getBinNumber())
                    .eq("delete_flag","0")
                    .eq("base_id", warehouseInOutInfo.getBaseId()));
            if (warehousePositionInfo!=null){
                warehouseInOutInfo.setPositionId(warehousePositionInfo.getId());
            }
            warehouseInOutInfo.setBinNumber(qualityInspectionManagement1.getBinNumber());
            warehouseInOutInfo.setCost(qualityInspectionManagement1.getCost());
            warehouseInOutInfoService.updateById(warehouseInOutInfo);
        }

        cacheComponent.delPrefixKey(Const.ADMIN_WEIGHINGINFO);
        cacheComponent.delPrefixKey(Const.ADMIN_WEIGHINGINFO_NUM);
        //成功返回ok
        if (one ) {
            return "OK";
        } else {
            return "NG";
        }
    }

    /**
     * 查货名下拉列表
     * @param warehouseId
     * @return
     */
    @Override
    public List<PurchasePrice> goodsName(String warehouseId) {
        //查潮粮单价已审核的数据
        List<PurchasePrice> purchasePriceList=purchasePriceService.selectList(new EntityWrapper<PurchasePrice>()
            .eq("warehouse_id",warehouseId)
            .eq("status","已通过"));
        return purchasePriceList;
    }

    /**
     * 查询业务编号
     * @param
     * @return
     */
    @Override
    public List<QualityInspectionManagement> selectQualityInspectionManagementList(QualityInspectionManagement qualityInspectionManagement) {
        SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");//设置日期格式
        String date = f.format(new Date(System.currentTimeMillis()));
        Map<String, Object> pageView = new HashMap<>(7);
        pageView.put("date", date);
        pageView.put("warehouseNo", qualityInspectionManagement.getWarehouseNo());
        pageView.put("numberLetter", qualityInspectionManagement.getNumberLetter());
        pageView.put("compId", qualityInspectionManagement.getCompId());
        List<QualityInspectionManagement> dataList = baseMapper.getListByConditions(pageView);
        return dataList;
    }


    /**
     * 添加质检管理信息
     * @param qualityInspectionManagement
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addQualityInspection(QualityInspectionManagement qualityInspectionManagement) {
        String relationId=IdGenerator.generateUUID();
        qualityInspectionManagement.setId(IdGenerator.generateUUID());
        if(qualityInspectionManagement.getCompId() == null || qualityInspectionManagement.getCompId().isEmpty()){
            qualityInspectionManagement.setCompId(AuthSecurityUtils.getStaffById(AuthSecurityUtils.getCurrentUserId()).getCompId());
        }
        //获取当前年月日
        SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");//设置日期格式
        String date = f.format(new Date(System.currentTimeMillis()));
        //查询质检信息数量包括已删除的集合
        List<QualityInspectionManagement> qualityInspectionManagementList = this.selectQualityInspectionManagementList(qualityInspectionManagement);//调用Service中的方法
        //生成业务编号
        if (qualityInspectionManagementList.size() > 0) {
            //取第一条数据的编号
            String n = qualityInspectionManagementList.get(0).getQualityNo();
            //截取编号后4位
            int intNumber = Integer.parseInt(n.substring(15));
            intNumber++;
            String Number = String.valueOf(intNumber);
            for (int i = 0; i < 4; i++) {
                Number = Number.length() < 4 ? "0" + Number : Number;
            }
            //编号自增
            Number = qualityInspectionManagement.getNumberLetter() + date + qualityInspectionManagement.getWarehouseNo() + Number;
            qualityInspectionManagement.setQualityNo(Number);
        } else {
            //如果当天数据为空，生成第一条数据
            String Number = qualityInspectionManagement.getNumberLetter() + date + qualityInspectionManagement.getWarehouseNo() + "0001";
            qualityInspectionManagement.setQualityNo(Number);
        }
        if(qualityInspectionManagement.getQualityNo().contains("null")){
            throw new YException(YExceptionEnum.QUALITY_HAVE_ERROR);
        }
        //判断质检编号是否唯一
        List<QualityInspectionManagement> qualityInspectionManagements =
                this.selectList(new EntityWrapper<QualityInspectionManagement>()
                        .eq("comp_id",qualityInspectionManagement.getCompId())
                        .eq("quality_no", qualityInspectionManagement.getQualityNo()));
        if (qualityInspectionManagements.size() > 0) {
//            throw new YException(YExceptionEnum.QUALITY_NO_ERROR);
        }

        qualityInspectionManagement.setRelationId(relationId);
        qualityInspectionManagement.setManagementType("1");
        qualityInspectionManagement.setQualityDate(new Date());
        CommonStaff commonStaff = staffService.getInfo(AuthSecurityUtils.getCurrentUserId());
        qualityInspectionManagement.setQualityInspector(commonStaff.getStaffName());
        //钎样员提交，状态为待初检
        if ("1".equals(qualityInspectionManagement.getBrazer())) {
            qualityInspectionManagement.setStatus(StatusEnum.TO_BE_INSPECTED.getName());
            qualityInspectionManagement.setStatusFlag(StatusEnum.TO_BE_INSPECTED.getFlag());
        }
        //质检员或双重身份提交，状态为已初检
        else {
            qualityInspectionManagement.setStatus(StatusEnum.FIRST_INSPECTED.getName());
            qualityInspectionManagement.setStatusFlag(StatusEnum.FIRST_INSPECTED.getFlag());
        }
        qualityInspectionManagement.setAgentKey(AuthSecurityUtils.getCurrentUserId());
        qualityInspectionManagement.setAgent(AuthSecurityUtils.getStaffById(AuthSecurityUtils.getCurrentUserId()).getStaffName());
        CommonSysParameter commonSysParameter = iCommonSysParameterService.selectOne(new EntityWrapper<CommonSysParameter>().eq("const_id", "CON2").eq("const_value", qualityInspectionManagement.getGoodsName()));
        qualityInspectionManagement.setGoodsNameKey(commonSysParameter.getConstKey());
        //生成检斤信息
        WeighingManagement weighingManagement=new WeighingManagement();
        weighingManagement.setId(IdGenerator.generateUUID());
        weighingManagement.setWarehouseInOutId(qualityInspectionManagement.getWarehouseInOutId());
        weighingManagement.setRelationId(qualityInspectionManagement.getRelationId());
        weighingManagement.setContractNo(qualityInspectionManagement.getContractNo());
        weighingManagement.setOutType(qualityInspectionManagement.getOutType());
        weighingManagement.setNumber(qualityInspectionManagement.getQualityNo());
        weighingManagement.setCustomer(qualityInspectionManagement.getCustomerName());
        weighingManagement.setCustomerPhone(qualityInspectionManagement.getCustomerPhone());
        weighingManagement.setCustomerNumberCard(qualityInspectionManagement.getCustomerNumberCard());
        weighingManagement.setCarNumber(qualityInspectionManagement.getCarNumber());
        weighingManagement.setCompId(qualityInspectionManagement.getCompId());
        weighingManagement.setServiceManagementType(qualityInspectionManagement.getServiceManagementType());
        weighingManagement.setGoodsNameKey(qualityInspectionManagement.getGoodsNameKey());
        weighingManagement.setGoodsName(qualityInspectionManagement.getGoodsName());
        weighingManagement.setBinNumber(qualityInspectionManagement.getBinNumber());
        weighingManagement.setType(qualityInspectionManagement.getType());
        weighingManagement.setManagementType("1");
        weighingManagement.setInOutType(qualityInspectionManagement.getInOutType());
        weighingManagement.setInOutTypeKey(qualityInspectionManagement.getInOutTypeKey());
        weighingManagement.setWarehouseName(qualityInspectionManagement.getWarehouseName());
        //状态为已质检
        weighingManagement.setStatus(StatusEnum.INSPECTED.getName());
        weighingManagement.setStatusFlag(StatusEnum.INSPECTED.getFlag());
        weighingManagement.setStorageNumber(qualityInspectionManagement.getStorageTagNo());
        //送粮登记的id
        if(qualityInspectionManagement.getIdentityId()!=null){
            ShippingInformation shippingInformation=shippingInformationService.selectById(qualityInspectionManagement.getIdentityId());
            if (shippingInformation!=null){
                if (shippingInformation.getNotCarNo().contains(qualityInspectionManagement.getCarNumber())) {
                    String newStr = "";
                    String[] arr = shippingInformation.getNotCarNo().split(",");
                    List<String> list = Arrays.asList(arr);
                    List<String> arrList = new ArrayList<>(list);
                    arrList.remove(qualityInspectionManagement.getCarNumber());
                    String[] strings = new String[arrList.size()];
                    String[] newArray = arrList.toArray(strings);
                    for (int i = 0; i < newArray.length; i++) {
                        newStr += newArray[i] + ",";
                    }
                    if (!"".equals(newStr)) {
                        newStr = newStr.substring(0, newStr.length() - 1);
                    }
                    shippingInformation.setNotCarNo(newStr);
                    shippingInformationService.updateById(shippingInformation);
                }
            }
        }
        if(qualityInspectionManagement.getCost() == null){
            qualityInspectionManagement.setCost(Float.parseFloat((qualityInspectionManagement.getDryGrainPrice()==null?0:qualityInspectionManagement.getDryGrainPrice())*1000 + ""));
        }
        boolean two=weighingManagementService.insert(weighingManagement);
        boolean one=this.insert(qualityInspectionManagement);

        cacheComponent.delPrefixKey(Const.ADMIN_WEIGHINGINFO);
        cacheComponent.delPrefixKey(Const.ADMIN_WEIGHINGINFO_NUM);
        //成功返回ok
        if (one &&two ) {
            return qualityInspectionManagement.getId();
        } else {
            return "NG";
        }
    }
    /**
     * 编辑质检管理信息
     * @param qualityInspectionManagement
     * @return
     */
    @Override
    public String addQualityInspectionOut(QualityInspectionManagement qualityInspectionManagement) {
        //状态改为已质检
        qualityInspectionManagement.setStatus(StatusEnum.INSPECTED.getName());
        qualityInspectionManagement.setStatusFlag(StatusEnum.INSPECTED.getFlag());
        boolean one=this.updateById(qualityInspectionManagement);
        //成功返回ok
        if (one ) {
            return qualityInspectionManagement.getId();
        } else {
            return "NG";
        }
    }

    /**
     * 查客户待结算的数量
     * @param qualityInspectionManagement
     * @return
     */
    @Override
    public Integer settledCount(QualityInspectionManagement qualityInspectionManagement) {
        if(qualityInspectionManagement.getCompId() == null || qualityInspectionManagement.getCompId().isEmpty()){
            qualityInspectionManagement.setCompId(AuthSecurityUtils.getStaffById(AuthSecurityUtils.getCurrentUserId()).getCompId());
        }
        Integer count=paymentManagementService.selectCount(new EntityWrapper<PaymentManagement>()
                .eq("comp_id",qualityInspectionManagement.getCompId())
                .eq("customer_number_card",qualityInspectionManagement.getCustomerNumberCard())
                .eq("goods_name",qualityInspectionManagement.getGoodsName())
                .eq("status_flag","1"));
        return count;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importQuality(QualityInspectionManagement qualityInspectionManagement) {
        List<QualityInspectionManagement> qualityInspectionManagementList=qualityInspectionManagement.getQualityInspectionManagementList();
        for (QualityInspectionManagement qualityInspectionManagement1:qualityInspectionManagementList) {
            String relationId = IdGenerator.generateUUID();
            qualityInspectionManagement1.setId(IdGenerator.generateUUID());
            qualityInspectionManagement1.setCompId(AuthSecurityUtils.getStaffById(AuthSecurityUtils.getCurrentUserId()).getCompId());
            qualityInspectionManagement1.setRelationId(relationId);
            qualityInspectionManagement1.setGoodsName("玉米");
            qualityInspectionManagement1.setNatureOfGrainPurchase("贸易粮");
            qualityInspectionManagement1.setServiceManagementType("3");
            qualityInspectionManagement1.setQualityNo(qualityInspectionManagement1.getQualityNo());
            qualityInspectionManagement1.setCustomerName(qualityInspectionManagement1.getCustomerName());
            qualityInspectionManagement1.setCustomerPhone(qualityInspectionManagement1.getCustomerPhone());
            qualityInspectionManagement1.setCarNumber(qualityInspectionManagement1.getCarNumber());
            qualityInspectionManagement1.setWarehouseName(qualityInspectionManagement.getWarehouseName());
            qualityInspectionManagement1.setDryGrainPrice(qualityInspectionManagement1.getDryGrainPrice());
            qualityInspectionManagement1.setQualityDate(qualityInspectionManagement1.getQualityDate());
            qualityInspectionManagement1.setManagementType("1");
            qualityInspectionManagement1.setType("干粮");
            qualityInspectionManagement1.setBuckleWeightRatio(1.3f);
            qualityInspectionManagement1.setBinNumber("1");
            qualityInspectionManagement1.setConfirm("1");
            CommonStaff commonStaff = staffService.getInfo(AuthSecurityUtils.getCurrentUserId());
            qualityInspectionManagement1.setQualityInspector(commonStaff.getStaffName());
            qualityInspectionManagement1.setReInspector(commonStaff.getStaffName());
            //状态为已复检
            qualityInspectionManagement1.setStatus(StatusEnum.COMPLEX_INSPECTED.getName());
            qualityInspectionManagement1.setStatusFlag(StatusEnum.COMPLEX_INSPECTED.getFlag());
            qualityInspectionManagement1.setAgentKey(AuthSecurityUtils.getCurrentUserId());
            qualityInspectionManagement1.setAgent(AuthSecurityUtils.getStaffById(AuthSecurityUtils.getCurrentUserId()).getStaffName());
            //生成检斤信息
            WeighingManagement weighingManagement = new WeighingManagement();
            weighingManagement.setId(IdGenerator.generateUUID());
            weighingManagement.setRelationId(relationId);
            weighingManagement.setNumber(qualityInspectionManagement1.getQualityNo());
            weighingManagement.setCustomer(qualityInspectionManagement1.getCustomerName());
            weighingManagement.setCustomerPhone(qualityInspectionManagement1.getCustomerPhone());
            weighingManagement.setCustomerNumberCard(qualityInspectionManagement1.getCustomerNumberCard());
            weighingManagement.setCarNumber(qualityInspectionManagement1.getCarNumber());
            weighingManagement.setCompId(AuthSecurityUtils.getStaffById(AuthSecurityUtils.getCurrentUserId()).getCompId());
            weighingManagement.setServiceManagementType("3");
            weighingManagement.setGoodsName("玉米");
            weighingManagement.setType("干粮");
            weighingManagement.setBinNumber("1");
            weighingManagement.setSecretaryWeigher(commonStaff.getStaffName());
            weighingManagement.setSkinInspector(commonStaff.getStaffName());
            weighingManagement.setGrossWeight(qualityInspectionManagement1.getGrossWeight());
            weighingManagement.setTare(qualityInspectionManagement1.getTare());
            weighingManagement.setNetWeight(qualityInspectionManagement1.getNetWeight());
            weighingManagement.setManagementType("1");
            weighingManagement.setWarehouseName(qualityInspectionManagement.getWarehouseName());
            weighingManagement.setGrossDate(qualityInspectionManagement1.getQualityDate());
            weighingManagement.setTareDate(qualityInspectionManagement1.getQualityDate());
            //状态为已称皮重
            weighingManagement.setStatus(StatusEnum.TARED.getName());
            weighingManagement.setStatusFlag(StatusEnum.TARED.getFlag());
            PaymentManagement paymentManagement=new PaymentManagement();
            paymentManagement.setId(IdGenerator.generateUUID());
            paymentManagement.setRelationId(relationId);
            paymentManagement.setCompId(AuthSecurityUtils.getStaffById(AuthSecurityUtils.getCurrentUserId()).getCompId());
            paymentManagement.setCustomerNumberCard(qualityInspectionManagement1.getCustomerNumberCard());
            paymentManagement.setPaymentNo(qualityInspectionManagement1.getQualityNo());
            paymentManagement.setCustomerName(qualityInspectionManagement1.getCustomerName());
            paymentManagement.setCustomerPhone(qualityInspectionManagement1.getCustomerPhone());
            paymentManagement.setCarNo(qualityInspectionManagement1.getCarNumber());
            paymentManagement.setGoodsName("玉米");
            paymentManagement.setType("干粮");
            paymentManagement.setTidalGrainPrice(qualityInspectionManagement1.getDryGrainPrice());
            paymentManagement.setTidalGrainPrice(qualityInspectionManagement1.getDryGrainPrice());
            paymentManagement.setStatus("全部付款");
            paymentManagement.setStatusFlag("5");
            paymentManagement.setNetWeight(qualityInspectionManagement1.getNetWeight());
            paymentManagement.setPureWeight(qualityInspectionManagement1.getNetWeight());
            paymentManagement.setManagementType("1");
            paymentManagement.setGrossWeight(qualityInspectionManagement1.getGrossWeight());
            paymentManagement.setTare(weighingManagement.getTare());
            paymentManagement.setSettlementDate(qualityInspectionManagement1.getQualityDate());
            paymentManagement.setWarehouseName(qualityInspectionManagement.getWarehouseName());
            paymentManagement.setUnitDeduction(qualityInspectionManagement1.getDeductionAmount()==null?0:qualityInspectionManagement1.getDeductionAmount());
            Double money = (qualityInspectionManagement1.getDryGrainPrice()-paymentManagement.getUnitDeduction()) * qualityInspectionManagement1.getNetWeight();
//            BigDecimal money1 = new BigDecimal(money);
//            Double money2 = money1.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
            paymentManagement.setAmountIngPayable(money);
            paymentManagement.setAmountEdPayable(money);
            paymentManagement.setGrainMoney(Float.valueOf(String.valueOf(money)));
            paymentManagement.setCalculationPayable(money);
            paymentManagement.setActualPayment(money);

            paymentManagement.setSettlementClerk(commonStaff.getStaffName());
            paymentManagementService.insert(paymentManagement);
            this.insert(qualityInspectionManagement1);
            weighingManagementService.insert(weighingManagement);
            cacheComponent.delPrefixKey(Const.ADMIN_WEIGHINGINFO);
            cacheComponent.delPrefixKey(Const.ADMIN_WEIGHINGINFO_NUM);
        }
        return "ok";
    }
}
