package com.th.demo.service.impl.ware;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.th.demo.mapping.maint.StackMapper;
import com.th.demo.mapping.ware.CombineRecordMapper;
import com.th.demo.mapping.ware.StoreMapper;
import com.th.demo.model.maint.Stack;
import com.th.demo.model.system.ResponseCodeMsg;
import com.th.demo.model.system.SysUser;
import com.th.demo.model.system.Type;
import com.th.demo.model.ware.CombineRecord;
import com.th.demo.model.ware.Store;
import com.th.demo.service.ware.CombineService;
import com.th.demo.tools.JSONTools;
import com.th.demo.tools.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service("CombineService")
public class CombineServiceImpl implements CombineService {
    @Autowired
    public StoreMapper storeMapper;
    @Autowired
    public StackMapper stackMapper;
    @Autowired
    public CombineRecordMapper combineRecordMapper;
    int num = 0;
    String result = Type.FAIL;

    @Transactional
    @Override
    public String combine(String json, String userId, String belongId) {
        num = 0;
        Double d_combineCount = 0.0;
        Double d_combineWeight = 0.0;
        List<Store> listStore = JSON.parseObject(json, new TypeReference<List<Store>>() {
        });
        int combineCount = listStore.size();
        Store store = listStore.get(0);
        String materialName = listStore.get(0).getMaterial().getName();
        String customerName = listStore.get(0).getCustomer().getName();
        String standard = listStore.get(0).getMaterial().getStandard();
        String model = listStore.get(0).getModel();
        Date addTime = listStore.get(0).getAddTime();
        for (int i = 0; i < listStore.size(); i++) {
            if (!materialName.equals(listStore.get(i).getMaterial().getName())) {
                return JSONTools.toString(ResponseCodeMsg.CODE_EX, "物料不一致，不允许合并");
            }
            if (!customerName.equals(listStore.get(i).getCustomer().getName())) {
                return JSONTools.toString(ResponseCodeMsg.CODE_EX, "客户不一致，不允许合并");
            }
            if (!standard.equals(listStore.get(i).getMaterial().getStandard())) {
                return JSONTools.toString(ResponseCodeMsg.CODE_EX, "钢种不一致，不允许合并");
            }
            if (!model.equals(listStore.get(i).getModel())) {
                return JSONTools.toString(ResponseCodeMsg.CODE_EX, "规格不一致，不允许合并");
            }
            if (addTime != listStore.get(0).getAddTime()) {
                return JSONTools.toString(ResponseCodeMsg.CODE_EX, "入库时间不一致，不允许合并");
            }
            d_combineCount += listStore.get(i).getCount();
            d_combineWeight += listStore.get(i).getWeight();
        }
        Collections.sort(listStore);
        int currentLayer = Integer.parseInt(storeMapper.selectLayerByStackId(store.getStack().getId(),  belongId));
        int min = listStore.get(0).getLayer();
        int max = listStore.get(listStore.size() - 1).getLayer();


        Stack stack = store.getStack();// stackMapper.selectByWareNameStackName(store.getWareName(), store.getStackName(), userId, belongId);
        if (stack.getIsLayer().equals("0")) {
            store.setLayer(0);
        } else if (stack.getIsLayer().equals("1")) {
//            List<Store> listDown = storeMapper.selectForUpDown(store.getWare().getId(),store.getStack().getId(), userId, belongId, max+1 , currentLayer);
//            for (int i = 0; i < listDown.size(); i++) {
//                listDown.get(i).setLayer(listDown.get(i).getLayer() -combineCount+1);
//                num += storeMapper.updateByPrimaryKey(listDown.get(i));
//            }
            storeMapper.updateForUpDownByStep(store.getWare().getId(),store.getStack().getId(), userId, belongId, max+1 , currentLayer,-1*(combineCount-1));
        } else if (stack.getIsLayer().equals("2")) {
            //  store.setLayer(0);
        }

        Store combineStore = getStore(listStore.get(0), d_combineCount, d_combineWeight);
        int combineLayer = combineStore.getLayer();
        num += storeMapper.insert(combineStore);
        for (int i = 0; i < listStore.size(); i++) {
            Store storeTemp = listStore.get(i);
            CombineRecord combineRecord = getCombineRecord(storeTemp, d_combineCount, d_combineWeight, combineLayer,combineStore.getId(), userId);
            combineRecordMapper.insert(combineRecord);
            storeTemp.setCancelFlag("8");
            storeMapper.updateByPrimaryKey(storeTemp);
        }
        result = Tools.moreThanZeroResultJSON(num);
        return result;

    }

    private Store getStore(Store store, Double combineCount, Double combineWeight) {
        Store combineStore = new Store();
        combineStore.setWare(store.getWare());
        combineStore.setStack(store.getStack());
        combineStore.setLayer(store.getLayer());
        combineStore.setMaterial(store.getMaterial());
     //   combineStore.setMaterialNo(store.getMaterialNo());
     //   combineStore.setStandard(store.getStandard());
        combineStore.setModel(store.getModel());
        combineStore.setCustomer(store.getCustomer());
       // combineStore.setCustomerNo(store.getCustomerNo());
        combineStore.setCount(combineCount);
        combineStore.setWeight(combineWeight);
        combineStore.setRemark(store.getRemark());
        combineStore.setBelongId(store.getBelongId());
        combineStore.setPlateNo(store.getPlateNo());
        combineStore.setAddId(store.getAddId());
        combineStore.setAddTime(new Date());
        combineStore.setInId(store.getInId());
        combineStore.setCancelFlag("0");
        combineStore.setOutFlag("0");
        combineStore.setReceiveAddress(store.getReceiveAddress());
        return combineStore;
    }


    private CombineRecord getCombineRecord(Store store, Double combineCount, Double combineWeight, int combineLayer,String storeIdNew, String userId) {

        CombineRecord record = new CombineRecord();
        record.setWareName(store.getWare().getName());
        record.setStackName(store.getStack().getName());
        record.setOrignalLayerOne(store.getLayer());
        record.setCombineLayer(combineLayer);
        record.setMaterialName(store.getMaterial().getName());
        //record.setMaterialNo(store.getMaterialNo());
        record.setStandard(store.getMaterial().getStandard());
        record.setModel(store.getModel());
        record.setCustomerName(store.getCustomer().getName());
      //  record.setCustomerNo(store.getCustomerNo());
        record.setOrignalCountOne(store.getCount());
        record.setOrignalWeightOne(store.getWeight());
        record.setCombineCount(combineCount);
        record.setCombineWeight(combineWeight);
        record.setRemark(store.getRemark());
        record.setBelongId(store.getBelongId());
        record.setPlateNo(store.getPlateNo());
        record.setAddUser(new SysUser(userId));
        record.setAddTime(new Date());
        record.setInId(store.getInId());
        record.setOrignalStoreIdOne(store.getId());
        record.setCombineStoreId(storeIdNew);
        record.setCancelFlag("0");
        record.setWgtDcnMtcCd(store.getWgtDcnMtcCd());
        record.setEdgeTy(store.getEdgeTy());
        record.setProductionPlace(store.getProductionPlace());
        return record;
    }


}
