package com.steerinfo.pretrack.pretracknotice.service.impl;

import com.steerinfo.baseinfo.combaseinfo.mapper.ComBaseInfoMapper;
import com.steerinfo.baseinfo.combaseinfo.model.ComBaseInfo;
import com.steerinfo.baseinfo.meterbasecarrierunit.mapper.MeterBaseCarrierUnitMapper;
import com.steerinfo.baseinfo.meterbasecarrierunit.model.MeterBaseCarrierUnit;
import com.steerinfo.baseinfo.meterbasecustomersupplier.mapper.MeterBaseCustomerSupplierMapper;
import com.steerinfo.baseinfo.meterbasecustomersupplier.model.MeterBaseCustomerSupplier;
import com.steerinfo.baseinfo.meterbaseloadpoint.mapper.MeterBaseLoadPointMapper;
import com.steerinfo.baseinfo.meterbaseloadpoint.model.MeterBaseLoadPoint;
import com.steerinfo.baseinfo.meterbasematterinfo.mapper.MeterBaseMatterInfoMapper;
import com.steerinfo.baseinfo.meterbasematterinfo.model.MeterBaseMatterInfo;
import com.steerinfo.framework.mapper.IBaseMapper;
import com.steerinfo.framework.service.impl.BaseServiceImpl;
import com.steerinfo.framework.service.pagehelper.PageHelper;
import com.steerinfo.framework.service.pagehelper.PageList;
import com.steerinfo.framework.user.UserPayload;
import com.steerinfo.meterwork.except.MarkerMetException;
import com.steerinfo.meterwork.meterworkcaractual.mapper.MeterWorkCarActualMapper;
import com.steerinfo.meterwork.meterworkcaractual.model.MeterWorkCarActual;
import com.steerinfo.meterwork.meterworkcaractualfirst.mapper.MeterWorkCarActualFirstMapper;
import com.steerinfo.meterwork.meterworkcaractualfirst.model.MeterWorkCarActualFirst;
import com.steerinfo.meterwork.meterworkcaractualfirst.service.IMeterWorkCarActualFirstService;
import com.steerinfo.pretrack.pretracknotice.mapper.PreTrackNoticeMapper;
import com.steerinfo.pretrack.pretracknotice.model.PreTrackNotice;
import com.steerinfo.pretrack.pretracknotice.service.IPreTrackNoticeService;
import com.steerinfo.pretrack.pretrackscale.mapper.PreTrackScaleMapper;
import com.steerinfo.pretrack.pretrackscale.model.PreTrackScale;
import com.steerinfo.util.CommonPage;
import com.steerinfo.util.FieldsCollector;
import com.steerinfo.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * PreTrackNotice服务实现：
 *
 * @author generator
 * @version 1.0-SNAPSHORT 2020-11-13 03:42
 * 类描述
 * 修订历史：
 * 日期：2020-11-13
 * 作者：generator
 * 参考：
 * 描述：PreTrackNotice服务实现
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 * @see null
 */
@Service(value = "preTrackNoticeService")
public class PreTrackNoticeServiceImpl extends BaseServiceImpl<PreTrackNotice, String> implements IPreTrackNoticeService {

    @Autowired
    private PreTrackNoticeMapper preTrackNoticeMapper;

    @Autowired
    IMeterWorkCarActualFirstService meterWorkCarActualFirstService;

    @Override
    protected IBaseMapper<PreTrackNotice, String> getMapper() {
        return preTrackNoticeMapper;
    }

    /**
     * 预报表
     */
    @Resource
    private PreTrackScaleMapper preTrackScaleMapper;

    /**
     * 一次计量表
     */
    @Resource
    private MeterWorkCarActualFirstMapper meterWorkCarActualFirstMapper;

    /**
     * 二次计量表
     */
    @Resource
    private MeterWorkCarActualMapper meterWorkCarActualMapper;

    /**
     * 物料表
     */
    @Resource
    private MeterBaseMatterInfoMapper meterBaseMatterInfoMapper;

    /**
     * 供应商客户
     */
    @Resource
    private MeterBaseCustomerSupplierMapper meterBaseCustomerSupplierMapper;

    /**
     * 卸货地点
     */
    @Resource
    private MeterBaseLoadPointMapper meterBaseLoadPointMapper;

    /**
     * 承运单位
     */
    @Resource
    private MeterBaseCarrierUnitMapper meterBaseCarrierUnitMapper;

    /**
     * 基础信息表
     */
    @Resource
    private ComBaseInfoMapper comBaseInfoMapper;

    @Override
    @Transactional
    public String checkAndAdd(PreTrackNotice model) {
        if (model == null) {
            throw new MarkerMetException(500, "参数不允许为空!!");
        }
        model.setValueFlag("0");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String no = preTrackNoticeMapper.getNewID(sdf.format(new Date()));
        model.setNoticeNo(sdf.format(new Date()) + no);
        model.setCreateTime(new Date());
        preTrackNoticeMapper.insertSelective(model);
        return model.getNoticeNo();
    }

    @Override
    @Transactional
    public String checkAndUpdate(PreTrackNotice model) {
        model = check(model);
        //按照主键查询原始的合同号及物资信息
        PreTrackNotice oldNotice = preTrackNoticeMapper.selectByPrimaryKey(model.getNoticeNo());
        if (oldNotice != null && oldNotice.getNoticeNo() != null && oldNotice.getContractNo() != null) {
            //按照合同号及物料名称；查询预报信息；并修改；
            Map<String, Object> ContractMap = new HashMap<>();
            ContractMap.put("contractNo", oldNotice.getContractNo());
            ContractMap.put("matterName", oldNotice.getMatterName());
            List<PreTrackScale> scaleList = preTrackScaleMapper.selectBy(ContractMap);
            if (scaleList != null && scaleList.size() > 0) {
                for (PreTrackScale scale : scaleList) {
                    scale.setContractNo(model.getContractNo());
                    scale.setMatterName(model.getMatterName());
                    scale.setMatterNo(model.getMatterNo());
                    scale.setUpdateTime(new Date());
                    scale.setUpdateManName(model.getCreateManName());
                    scale.setUpdateManNo(model.getCreateManNo());
                    scale.setMemo(scale.getMemo() + "修改合同数据自动修改");
                    preTrackScaleMapper.updateByPrimaryKeySelective(scale);
                }
            }
            //按照合同号及物料名称；查询一次计量；并修改；
            List<MeterWorkCarActualFirst> firstList = meterWorkCarActualFirstMapper.selectByParameters(ContractMap);
            if (firstList != null && firstList.size() > 0) {
                for (MeterWorkCarActualFirst first : firstList) {
                    first.setContractNo(model.getContractNo());
                    first.setMatterName(model.getMatterName());
                    first.setMatterNo(model.getMatterNo());
                    first.setUpdateTime(new Date());
                    first.setUpdateManName(model.getCreateManName());
                    first.setUpdateManNo(model.getCreateManNo());
                    first.setMemo(first.getMemo() + "修改合同数据自动修改");
                    meterWorkCarActualFirstMapper.updateByPrimaryKeySelective(first);
                }
            }

            //按照合同号及物料名称；查询二次计量；并修改;
            List<MeterWorkCarActual> actualList = meterWorkCarActualMapper.selectByParameters(ContractMap);
            if (actualList != null && actualList.size() > 0) {
                for (MeterWorkCarActual actual : actualList) {
                    actual.setContractNo(model.getContractNo());
                    actual.setMatterName(model.getMatterName());
                    actual.setMatterNo(model.getMatterNo());
                    meterWorkCarActualMapper.updateByPrimaryKeySelective(actual);
                }
            }
        }
        preTrackNoticeMapper.updateByPrimaryKeySelective(model);
        return model.getNoticeNo();
    }

    @Transactional
    @Override
    public int abolish(List<PreTrackNotice> models) {
        if (models == null) {
            throw new MarkerMetException(500, "参数不允许为空!!");
        }
        int num = preTrackNoticeMapper.batchUpdateAbolish(models);
        return num;
    }

    @Transactional
    @Override
    public int recover(List<PreTrackNotice> models) {
        if (models == null) {
            throw new MarkerMetException(500, "参数不允许为空!!");
        }
        int num = preTrackNoticeMapper.batchUpdateRecover(models);
        return num;
    }

    /**
     * 合同批量导入
     *
     * @param models
     * @return
     */
    @Override
    @Transactional
    public int checkAndAddList(List<PreTrackNotice> models) {
        if (models.size() <= 0 || models == null) {
            throw new MarkerMetException(500, "参数不允许为空!!");
        }
        int num = 0;
        for (PreTrackNotice model : models) {
            check(model); //批量新增，关键字段判断
        }
        //转换前端传来的数据；从名称转换为编码；
        for (PreTrackNotice model : models) {
            setCodeInfo(model);
        }
        for (PreTrackNotice model : models) {
            checkAndAdd(model);
            num++;
        }
        return num;
    }

    @Override
    public PageList<PreTrackNotice> listLike(CommonPage<PreTrackNotice> model) {
/*        HashMap<String, Object> obj = new HashMap<>();
        obj.put("noticeNo", model.getParam().getNoticeNo());
        obj.put("contractNo", model.getParam().getContractNo());
        obj.put("batchNo", model.getParam().getBatchNo());
        obj.put("matterName", model.getParam().getMatterName());
        obj.put("valueFlag", model.getParam().getValueFlag());
        obj.put("customerSupplierName", model.getParam().getCustomerSupplierName());
        obj.put("receivingUintName", model.getParam().getReceivingUintName());
        obj.put("meterTypeName", model.getParam().getMeterTypeName());
        obj.put("specName", model.getParam().getMeterTypeName());*/
        Map<String,Object> map= FieldsCollector.beanToMap(model.getParam());
        PageHelper.startPage(model.getPageNum(), model.getPageSize());
        List<PreTrackNotice> list = preTrackNoticeMapper.selectLikeByParameters(map);
        PageList pageInfo = new PageList(list);
        return (pageInfo);
    }


    /**
     * 检查关键参数是否为空
     *
     * @param model
     * @return
     */
    private PreTrackNotice check(PreTrackNotice model) {
        if (StringUtils.isEmpty(model.getMatterName())) {
            throw new MarkerMetException(500, "物料名称不允许为空!!");
        }
        if (StringUtils.isEmpty(model.getContractNo())) {
            throw new MarkerMetException(500, "合同号不允许为空!!");
        }
        if (StringUtils.isEmpty(model.getCustomerSupplierName())) {
            throw new MarkerMetException(500, "供应商名称不允许为空!!");
        }
        if (StringUtils.isEmpty(model.getMeterTypeNo())) {
            throw new MarkerMetException(500, "业务类型编号不允许为空!!");
        }
        if (StringUtils.isEmpty(model.getMeterTypeName())) {
            throw new MarkerMetException(500, "业务类型名称不允许为空!!");
        }
        UserPayload payload = UserPayload.getCurrUser();
        String userId = payload.getUserCode();
        String userName = payload.getUserName();
        if (StringUtils.isEmpty(model.getNoticeNo())) {
            model.setCreateTime(new Date());
            model.setCreateManNo(userId);
            model.setCreateManName(userName);
        }
        return model;
    }

    /**
     * 通过名称获取编码信息
     *
     * @param model
     * @return
     */
    private PreTrackNotice setCodeInfo(PreTrackNotice model) {
        //物料名称获取物料编码
        if (StringUtils.isNotEmpty(model.getMatterName())) {
            Map<String, Object> map1 = new HashMap<>();
            map1.put("matterName", model.getMatterName());
            List<MeterBaseMatterInfo> matterList = meterBaseMatterInfoMapper.selectByParameters(map1);
            if (matterList == null || matterList.size() == 0) {
                throw new MarkerMetException(500, "物料[" + model.getMatterName() + "]对应的物料编码为空，请联系系统管理员维护!");
            }
            if (matterList != null && matterList.size() > 0) {
                model.setMatterNo(matterList.get(0).getMatterNo());
            }
        }
        //供应商名称获取编码信息
        if (StringUtils.isNotEmpty(model.getCustomerSupplierName())) {
            Map<String, Object> map2 = new HashMap<>();
            map2.put("customerSupplierName", model.getCustomerSupplierName());
            List<MeterBaseCustomerSupplier> supplierList = meterBaseCustomerSupplierMapper.selectByParameters(map2);
            if (supplierList == null || supplierList.size() == 0) {
                throw new MarkerMetException(500, "客商[" + model.getMatterName() + "]对应的编码为空，请联系系统管理员维护!");
            }
            if (supplierList != null && supplierList.size() > 0) {
                model.setCustomerSupplierNo(supplierList.get(0).getCustomerSupplierNo());
            }
        }
        //发货单位转换;
        if (StringUtils.isNotEmpty(model.getForwardingUnitName())) {
            //若发货单位等于供应商，则直接赋值；若不相等则说明是厂内单位，到卸货表里面去查询
            if (model.getForwardingUnitName().equals(model.getCustomerSupplierName())) {
                model.setForwardingUnitNo(model.getCustomerSupplierNo());
            } else {
                Map<String, Object> map3 = new HashMap<>();
                map3.put("loadPointName", model.getForwardingUnitName());
                List<MeterBaseLoadPoint> loadPointList = meterBaseLoadPointMapper.selectByParameters(map3);
                if (loadPointList == null || loadPointList.size() == 0) {
                    throw new MarkerMetException(500, "发货单位[" + model.getForwardingUnitName() + "]对应的编码为空，请联系系统管理员维护!");
                }
                if (loadPointList != null && loadPointList.size() > 0) {
                    model.setForwardingUnitNo(loadPointList.get(0).getLoadPointNo());
                }
            }
        }
        //收货单位转换
        if (StringUtils.isNotEmpty(model.getReceivingUintName())) {
            //若收货单位等于供应商，则直接赋值；若不相等则说明是厂内单位，到卸货表里面去查询
            if (model.getReceivingUintName().equals(model.getCustomerSupplierName())) {
                model.setReceivingUintNo(model.getCustomerSupplierNo());
            } else {
                Map<String, Object> map4 = new HashMap<>();
                map4.put("loadPointName", model.getReceivingUintName());
                List<MeterBaseLoadPoint> loadPointList = meterBaseLoadPointMapper.selectByParameters(map4);
                if (loadPointList == null || loadPointList.size() == 0) {
                    throw new MarkerMetException(500, "收货单位[" + model.getReceivingUintName() + "]对应的编码为空，请联系系统管理员维护!");
                }
                if (loadPointList != null && loadPointList.size() > 0) {
                    model.setReceivingUintNo(loadPointList.get(0).getLoadPointNo());
                }
            }
        }
        //卸货地点转换
        if (StringUtils.isNotEmpty(model.getLoadPointName())) {
            Map<String, Object> map5 = new HashMap<>();
            map5.put("loadPointName", model.getReceivingUintName());
            List<MeterBaseLoadPoint> loadPointList2 = meterBaseLoadPointMapper.selectByParameters(map5);
            if (loadPointList2 == null || loadPointList2.size() == 0) {
                throw new MarkerMetException(500, "卸货点[" + model.getReceivingUintName() + "]对应的编码为空，请联系系统管理员维护!");
            }
            if (loadPointList2 != null && loadPointList2.size() > 0) {
                model.setForwardingUnitNo(loadPointList2.get(0).getLoadPointNo());
            }
        }

        //承运单位转换
        if (StringUtils.isNotEmpty(model.getCarrierUnitName())) {
            Map<String, Object> map6 = new HashMap<>();
            map6.put("carrierUnitName", model.getCarrierUnitName());
            List<MeterBaseCarrierUnit> unitList2 = meterBaseCarrierUnitMapper.selectByParameters(map6);
            if (unitList2 == null || unitList2.size() == 0) {
                throw new MarkerMetException(500, "承运单位[" + model.getCarrierUnitName() + "]对应的编码为空，请联系系统管理员维护!");
            }
            if (unitList2 != null && unitList2.size() > 0) {
                model.setCarrierUnitNo(unitList2.get(0).getCarrierUnitNo());
            }
        }

        //材质名称转换
        if (StringUtils.isNotEmpty(model.getMaterialName())) {
            Map<String, Object> map7 = new HashMap<>();
            map7.put("baseName", model.getCarrierUnitName());
            List<ComBaseInfo> baseInfoList = comBaseInfoMapper.selectByParameters(map7);
            if (baseInfoList == null || baseInfoList.size() == 0) {
                throw new MarkerMetException(500, "材质[" + model.getReceivingUintName() + "]对应的编码为空，请联系系统管理员维护!");
            }
            if (baseInfoList != null && baseInfoList.size() > 0) {
                model.setMaterialNo(baseInfoList.get(0).getBaseCode());
            }
        }

        //规格名称转换
        if (StringUtils.isNotEmpty(model.getSpecName())) {
            Map<String, Object> map8 = new HashMap<>();
            map8.put("baseName", model.getSpecName());
            List<ComBaseInfo> baseInfoList1 = comBaseInfoMapper.selectByParameters(map8);
            if (baseInfoList1 == null || baseInfoList1.size() == 0) {
                throw new MarkerMetException(500, "材质[" + model.getReceivingUintName() + "]对应的编码为空，请联系系统管理员维护!");
            }
            if (baseInfoList1 != null && baseInfoList1.size() > 0) {
                model.setSpecNo(baseInfoList1.get(0).getBaseCode());
            }
        }
        return model;
    }
}
