package com.shinsoft.sto.service.impl.record;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shinsoft.sto.mapper.main.CustomerMapper;
import com.shinsoft.sto.mapper.main.MaterialMapper;
import com.shinsoft.sto.mapper.main.StackMapper;
import com.shinsoft.sto.mapper.main.WareMapper;
import com.shinsoft.sto.mapper.record.InrecordMapper;
import com.shinsoft.sto.mapper.ware.ChangeRecordMapper;
import com.shinsoft.sto.mapper.ware.ProdMasterMapper;
import com.shinsoft.sto.mapper.ware.StoreChangeMapper;
import com.shinsoft.sto.model.main.Customer;
import com.shinsoft.sto.model.main.Material;
import com.shinsoft.sto.model.main.Stack;
import com.shinsoft.sto.model.main.Ware;
import com.shinsoft.sto.model.record.ImportModel;
import com.shinsoft.sto.model.record.Inrecord;
import com.shinsoft.sto.model.system.ResponseCodeMsg;
import com.shinsoft.sto.model.system.ResultJSON;
import com.shinsoft.sto.model.ware.ChangeRecord;
import com.shinsoft.sto.model.ware.ProdMaster;
import com.shinsoft.sto.model.ware.StoreChange;
import com.shinsoft.sto.service.record.InrecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class InrecordServiceImpl extends ServiceImpl<InrecordMapper, Inrecord> implements InrecordService {

//    材料信息
    @Autowired
    private ProdMasterMapper prodMasterMapper;
//  入库记录
    @Autowired
    private InrecordMapper inrecordMapper;
//    库存
    @Autowired
    private StoreChangeMapper storeChangeMapper;
//    材料操作记录
    @Autowired
    private ChangeRecordMapper changeRecordMapper;
//    客户信息
    @Autowired
    private CustomerMapper customerMapper;
//    物料
    @Autowired
    private MaterialMapper MaterialMapper;
//    仓库
    @Autowired
    private WareMapper wareMapper;
//    垛位
    @Autowired
    private StackMapper stackMapper;

    @Override
    public ResultJSON query(int page, int rows, Map<String,Object> map) {
        try {
            Page<Inrecord> pageParam = new Page<>(page, rows);
            IPage<Inrecord> result = baseMapper.selectInrecordPage(pageParam, map);
            return ResultJSON.success(result);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultJSON.error(ResponseCodeMsg.CODE_EX, ex.getMessage());
        }
    }

    @Override
    public ResultJSON statistics(Map<String, Object> map) {
        try {
            Map<String, Object> stats = baseMapper.selectStatistics(map);
            return ResultJSON.success(stats);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultJSON.error(ResponseCodeMsg.CODE_EX, ex.getMessage());
        }
    }

    @Override
    @Transactional
    public ResultJSON batchInStore(String userId, List<ImportModel> dataList, String belongId,String userName) {
        try {
            if(ObjectUtils.isEmpty(dataList)){
                return ResultJSON.error(ResponseCodeMsg.CODE_EX, "数据为空");
            }
            for (ImportModel model : dataList){
                /**
                 * 数据校验
                 */
//          1.材料号不能为空且不能和库内信息重复(根据材料号查询材料表中是否具有重复数据)
                if(StringUtils.isEmpty(model.getProdNo())){
                    return ResultJSON.error(ResponseCodeMsg.CODE_EX, "材料号不能为空");
                }
//              查询重复数据 未取消入库 , 未出库 , 材料号相同的数据
                ProdMaster prodMasters = prodMasterMapper.selectOne(
                        new QueryWrapper<ProdMaster>().
                        eq("prod_no", model.getProdNo()).
                        eq("cancel_flag", "0").
                        eq("in_flag", "0").
                        eq("out_flag", "0").
                        eq("belong_id", belongId));
                if (prodMasters!= null) {
                    return ResultJSON.error(ResponseCodeMsg.CODE_EX, model.getProdNo()+"材料已入库");
                }

//          2.货权公司、收货公司、客户公司不能为空且该客户要在系统中维护了
                if(StringUtils.isEmpty(model.getOwnerCompany()) || StringUtils.isEmpty(model.getReceivingCompany())){
                    return ResultJSON.error(ResponseCodeMsg.CODE_EX, "货权公司、收货公司不能为空");
                }
//                根据客户名称查询客户信息
                Customer customer = customerMapper.selectOne(
                        new QueryWrapper<Customer>()
                        .eq("CUSTOMER_NM", model.getOwnerCompany())
                        .eq("cancel_flag", "0")
                        .eq("belong_id", belongId));
                if (customer == null){
                    return ResultJSON.error(ResponseCodeMsg.CODE_EX, "["+model.getOwnerCompany()+"],暂未维护");
                }
                Customer customer1 = customerMapper.selectOne(
                        new QueryWrapper<Customer>()
                                .eq("CUSTOMER_NM", model.getReceivingCompany())
                                .eq("cancel_flag", "0")
                                .eq("belong_id", belongId));
                if (customer1 == null){
                    return ResultJSON.error(ResponseCodeMsg.CODE_EX, "["+model.getReceivingCompany()+"],暂未维护");
                }
//          3.物料品种要进行维护，此处跟钢种信息有关系;
                Material material = MaterialMapper.selectOne(
                        new QueryWrapper<Material>().
                                eq("material_name", model.getMaterialName()).
                                eq("MATERIAL_STANDARD", model.getStGrade()).
                                eq("cancel_flag", "0").
                                eq("belong_id", belongId));
                if (material == null){
                    return ResultJSON.error(ResponseCodeMsg.CODE_EX, "["+model.getMaterialName()+"]物料信息,暂未维护");
                }
//          4.入库数量和入库重量必须有且要大于0，这部分关系到所有统计相关的内容;
                if ((model.getQuantity() != null && model.getQuantity().compareTo(BigDecimal.ZERO) <= 0) ||
                    (model.getWeight()!=null && model.getWeight().compareTo(BigDecimal.ZERO) <= 0)) {
                    return ResultJSON.error(ResponseCodeMsg.CODE_EX, "数量和重量必须大于0");
                }



//                拼接材料信息
                ProdMaster prodMaster = prodSplice(model,userId,belongId,material,customer,customer1,userName);
                int insert = prodMasterMapper.insert(prodMaster);
                if (insert <= 0) {
                    return ResultJSON.error(ResponseCodeMsg.CODE_EX, "入库失败");
                }
//                拼接入库记录
                Inrecord inrecord = inRecordSplice(model, userId, belongId,material,customer,customer1,userName);
                int insert1 = inrecordMapper.insert(inrecord);
                if (insert1 <= 0) {
                    return ResultJSON.error(ResponseCodeMsg.CODE_EX, "入库失败");
                }
//                拼接库存信息
                StoreChange storeChange = storeChangeSplice(model, userId, belongId,prodMaster,userName);
                int insert2 = storeChangeMapper.insert(storeChange);
                if (insert2 <= 0) {
                    return ResultJSON.error(ResponseCodeMsg.CODE_EX, "入库失败");
                }
//                拼接操作记录
                ChangeRecord changeRecord = changeRecordSplice(model, userId, belongId,customer,customer1,userName, material,prodMaster);
                int insert3 = changeRecordMapper.insert(changeRecord);
                if (insert3 <= 0){
                    return ResultJSON.error(ResponseCodeMsg.CODE_EX, "入库失败");
                }
                return ResultJSON.success(ResponseCodeMsg.CODE_SUCCESS, "入库成功");

            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }


    /**
     * 拼接材料信息
     */
    public ProdMaster prodSplice(ImportModel importModel,String userId,String belongId,Material material,Customer customer,Customer customer1,String userName){
        ProdMaster prodMaster = new ProdMaster();
        prodMaster.setId(UUID.randomUUID().toString().replace("-", ""));
        prodMaster.setProdNo(importModel.getProdNo());
        prodMaster.setMaterialId(material.getId());
        prodMaster.setStGrade(material.getMaterialStandard());
        prodMaster.setOwnerCompany(customer.getId());
        prodMaster.setReceivingCompany(customer1.getId());
        prodMaster.setCustomerCompany(customer1.getId());
        if(importModel.getDeliveryAddress()!=null){
            prodMaster.setDeliveryAddress(importModel.getDeliveryAddress());
        }else{
            prodMaster.setDeliveryAddress(customer1.getDefaultAddress());
        }
        prodMaster.setWeight(importModel.getWeight());
        prodMaster.setQuantity(importModel.getQuantity());
        prodMaster.setAttrib_01(importModel.getAttrib01());
        prodMaster.setAttrib_02(importModel.getAttrib02());
        prodMaster.setAttrib_03(importModel.getAttrib03());
        prodMaster.setAttrib_04(importModel.getAttrib04());
        prodMaster.setAttrib_05(importModel.getAttrib05());
        if(importModel.getInUser()!=null){
            prodMaster.setInUserName(importModel.getInUser());
        }else{
            prodMaster.setInUserName(userName);
        }
        prodMaster.setInTruckNo(importModel.getInTruckNo());
        prodMaster.setInFlag("0");
        prodMaster.setLockFlag("0");
        prodMaster.setOutFlag("0");
        prodMaster.setCancelFlag("0");
        prodMaster.setBelongId(belongId);
        prodMaster.setInDtm(new Date());
//        prodMaster.setProcessInstanceStatus("00");
        prodMaster.setAddId(userId);
        prodMaster.setRemark_1(importModel.getRemark1());

        return prodMaster;
    }
    /**
     * 拼接入库记录
     */
    public Inrecord inRecordSplice(ImportModel importModel,String userId,String belongId,Material material,Customer customer,Customer customer1,String userName){
        Inrecord inrecord = new Inrecord();
        inrecord.setAddId(userId);
        inrecord.setId(UUID.randomUUID().toString().replace("-", ""));
        inrecord.setInTruckNo(importModel.getInTruckNo());
        inrecord.setBelongId(belongId);
        inrecord.setInWareName(importModel.getWareName());
        inrecord.setInStackName(importModel.getStackName());
        inrecord.setInLayerNo(importModel.getLayerNo());
        inrecord.setProdNo(importModel.getProdNo());
        inrecord.setOwnerCompany(customer.getId());
        inrecord.setReceivingCompany(customer1.getId());
        inrecord.setCustomerCompany(customer1.getId());
        inrecord.setMaterialId(material.getId());
        inrecord.setStGrade(material.getMaterialStandard());
        inrecord.setInWeight(importModel.getWeight());
        inrecord.setInQuantity(importModel.getQuantity());
        inrecord.setInFlag("0");
        inrecord.setDeliveryAddress(importModel.getDeliveryAddress());
        inrecord.setRemark1(importModel.getRemark1());
        inrecord.setAddTime(new Date());
        inrecord.setInDtm(new Date());
        if(importModel.getInUser()!=null){
            inrecord.setTallyPeople(importModel.getInUser());
        }else{
            inrecord.setTallyPeople(userName);
        }
        return inrecord;
    }

    /**
     * 拼接库存信息
     */
    public StoreChange storeChangeSplice(ImportModel importModel,String userId,String belongId,ProdMaster prodMaster,String userName){
        StoreChange storeChange = new StoreChange();
        storeChange.setId(UUID.randomUUID().toString().replace("-", ""));
        storeChange.setStoreId(prodMaster.getId());
//        查询仓库id
        Ware ware = wareMapper.selectOne(new QueryWrapper<>(Ware.class).eq("ware_nm", importModel.getWareName()).eq("cancel_flag", "0").eq("belong_id", belongId));
        storeChange.setWareId(ware.getId());
//        查询垛位id
        Stack stack = stackMapper.selectOne(new QueryWrapper<>(Stack.class).eq("ware_id", ware.getId()).eq("name", importModel.getStackName()).eq("cancel_flag", "0").eq("belong_id", belongId));
        storeChange.setStackId(stack.getId());
        storeChange.setAddId(userId);
        storeChange.setAddTime(new Date());
        storeChange.setBelongId(belongId);
        storeChange.setCancelFlag("0");
        if(importModel.getInUser()!=null){
            storeChange.setAddName(importModel.getInUser());
        }else{
            storeChange.setAddName(userName);
        }
        return storeChange;
    }

    /**
     * 拼接操作记录
     */
    public ChangeRecord changeRecordSplice(ImportModel importModel,String userId,String belongId,Customer customer,Customer customer1,String userName,Material material,ProdMaster prodMaster){
        ChangeRecord changeRecord = new ChangeRecord();
        changeRecord.setId(UUID.randomUUID().toString().replace("-", ""));
        changeRecord.setAddId(userId);
        changeRecord.setAddTime(new Date());
        changeRecord.setBelongId(belongId);
        changeRecord.setChangeFlag("01");
        changeRecord.setChangeNote("入库");
        changeRecord.setCancelFlag("0");
        changeRecord.setCntNum(1);
        changeRecord.setProdNo(importModel.getProdNo());
        changeRecord.setNewWareName(importModel.getWareName());
        changeRecord.setNewStackName(importModel.getStackName());
        changeRecord.setNewLayerNo(importModel.getLayerNo());
        changeRecord.setOwnerCompany(customer.getId());
        changeRecord.setReceivingCompany(customer1.getId());
        changeRecord.setCustomerCompany(customer1.getId());
        changeRecord.setMaterialId(material.getId());
        changeRecord.setStGrade(material.getMaterialStandard());
        changeRecord.setWeight(importModel.getWeight());
        changeRecord.setQuantity(importModel.getQuantity());
        changeRecord.setDeliveryAddress(importModel.getDeliveryAddress());
        if(importModel.getInUser()!=null){
            changeRecord.setAddName(importModel.getInUser());
        }else{
            changeRecord.setAddName(userName);
        }
        changeRecord.setProdId(prodMaster.getId());
        return changeRecord;
    }

    @Override
    public ResultJSON cancelInStore(Map<String, Object> map, String userId, String belongId) {
//        入库记录id
        Object id = map.get("id");
//        材料id
        Object id1 = map.get("prodId");
//        根据材料id修改材料库中cancel_flag为1
        ProdMaster prodMaster = new ProdMaster();
        prodMaster.setCancelFlag("1");
        prodMasterMapper.update(prodMaster,new QueryWrapper<>(ProdMaster.class)
                .eq("id",id1.toString())
                .eq("cancel_flag","0")
                .eq("belong_id",belongId));
//        根据材料id删除库存表中数据
        StoreChange storeChange = new StoreChange();
        storeChange.setCancelFlag("1");
        storeChangeMapper.update(storeChange,new QueryWrapper<>(StoreChange.class)
                .eq("prod_id",id1.toString())
                .eq("cancel_flag","0")
                .eq("belong_id",belongId));
//        根据材料id修改入库表中数据
        Inrecord inrecord = new Inrecord();
        inrecord.setCancelFlag("1");
        inrecordMapper.update(inrecord,new QueryWrapper<>(Inrecord.class)
                .eq("prod_id",id1.toString())
                .eq("cancel_flag","0")
                .eq("belong_id",belongId));
//        添加操作记录表中数据
        ChangeRecord changeRecord = new ChangeRecord();
        changeRecord.setId(UUID.randomUUID().toString().replace("-", ""));
        changeRecord.setAddId(userId);
        changeRecord.setAddTime(new Date());
        changeRecord.setBelongId(belongId);
        changeRecord.setChangeFlag("02");
        changeRecord.setChangeNote("取消入库");
        changeRecord.setCancelFlag("0");
        changeRecord.setCntNum(1);
        changeRecord.setProdId(id1.toString());
        changeRecordMapper.insert(changeRecord);
        return ResultJSON.success();
    }
}

