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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.th.demo.mapping.maint.CustomerMapper;
import com.th.demo.mapping.maint.MaterialMapper;
import com.th.demo.mapping.maint.StackMapper;
import com.th.demo.mapping.maint.WareMapper;
import com.th.demo.mapping.ware.InRecordMapper;
import com.th.demo.mapping.ware.MoveRecordMapper;
import com.th.demo.mapping.ware.SplitRecordMapper;
import com.th.demo.mapping.ware.StoreMapper;
import com.th.demo.model.maint.Stack;
import com.th.demo.model.maint.Ware;
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.InRecord;
import com.th.demo.model.ware.MoveRecord;
import com.th.demo.model.ware.SplitRecord;
import com.th.demo.model.ware.Store;
import com.th.demo.service.ware.InService;
import com.th.demo.service.ware.MoveService;
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("MoveService")
public class MoveServiceImpl implements MoveService {


    @Autowired
    public StoreMapper storeMapper;
    @Autowired
    public WareMapper wareMapper;
    @Autowired
    public StackMapper stackMapper;
    @Autowired
    public CustomerMapper customerMapper;
    @Autowired
    public MaterialMapper materialMapper;
    @Autowired
    public MoveRecordMapper moveRecordMapper;


    String result = Type.FAIL;
    int num = 0;


    @Transactional
    @Override
    public String top(String json, String userId, String belongId) {

        List<Store> listStore = JSON.parseObject(json, new TypeReference<List<Store>>() {
        });
        Collections.sort(listStore);
        int currentLayer = Integer.parseInt(storeMapper.selectLayerByStackId(listStore.get(0).getStack().getId(), belongId));
        int min = listStore.get(0).getLayer();
        int max = listStore.get(listStore.size() - 1).getLayer();

        List<Store> listUp = new ArrayList<>();
        //List<Store> listDown = new ArrayList<>();
        if (currentLayer == max) {
            result = JSONTools.toString(ResponseCodeMsg.CODE_EX, "已选中最高层，无法上移！");
        } else if (!WareTools.checkOrder(listStore)) {
            result = JSONTools.toString(ResponseCodeMsg.CODE_EX, "请选中连续数据移动！");
        } else {
            num += storeMapper.updateForUpDownByStep(listStore.get(0).getWare().getId(), listStore.get(0).getStack().getId(), userId, belongId, max + 1, currentLayer, currentLayer - max);
            num += storeMapper.updateForUpDownByStep(listStore.get(0).getWare().getId(), listStore.get(0).getStack().getId(), userId, belongId, min, max, currentLayer - max);
            num += storeMapper.updateForUpDownByStep(listStore.get(0).getWare().getId(), listStore.get(0).getStack().getId(), userId, belongId, currentLayer + 1, currentLayer + currentLayer - max, min - currentLayer - 1);
            listUp = storeMapper.selectForUpDown(listStore.get(0).getWare().getId(), listStore.get(0).getStack().getId(), userId, belongId, min + currentLayer - max, max + currentLayer - max);
            result = JSONTools.toString(listUp);
        }

        return result;
    }


    @Transactional
    @Override
    public String up(String json, int step, String userId, String belongId) throws Exception {

        List<Store> listStore = JSON.parseObject(json, new TypeReference<List<Store>>() {
        });
        Collections.sort(listStore);
        int currentLayer = Integer.parseInt(storeMapper.selectLayerByStackId(listStore.get(0).getStack().getId(), belongId));
        int min = listStore.get(0).getLayer();
        int max = listStore.get(listStore.size() - 1).getLayer();

        List<Store> listUp = new ArrayList<>();


        if (currentLayer - max < step) {
            step = currentLayer - max;
        }
        if (currentLayer == max) {
            result = JSONTools.toString(ResponseCodeMsg.CODE_EX, "已选中最高层，无法上移！");
        } else if (!WareTools.checkOrder(listStore)) {
            result = JSONTools.toString(ResponseCodeMsg.CODE_EX, "请选中连续数据移动！");
        } else {

            num += storeMapper.updateForUpDownByStep(listStore.get(0).getWare().getId(), listStore.get(0).getStack().getId(), userId, belongId, max + 1, max + step, currentLayer - max);
            num += storeMapper.updateForUpDownByStep(listStore.get(0).getWare().getId(), listStore.get(0).getStack().getId(), userId, belongId, min, max, step);
            num += storeMapper.updateForUpDownByStep(listStore.get(0).getWare().getId(), listStore.get(0).getStack().getId(), userId, belongId, currentLayer + 1, currentLayer + step, -1 * (currentLayer - min + 1));
            listUp = storeMapper.selectForUpDown(listStore.get(0).getWare().getId(), listStore.get(0).getStack().getId(), userId, belongId, min + step, max + step);

            result = JSONTools.toString(listUp);
        }

        return result;
    }

    @Override
    public String down(String json, int step, String userId, String belongId) {

        List<Store> listStore = JSON.parseObject(json, new TypeReference<List<Store>>() {
        });
        Collections.sort(listStore);
        int currentLayer = Integer.parseInt(storeMapper.selectLayerByStackId(listStore.get(0).getStack().getId(), belongId));
        int min = listStore.get(0).getLayer();
        int max = listStore.get(listStore.size() - 1).getLayer();

        List<Store> listUp = new ArrayList<>();
        List<Store> listDown = new ArrayList<>();

        if (min - 1 < step) {
            step = min - 1;
        }


        if (1 == min) {
            result = JSONTools.toString(ResponseCodeMsg.CODE_EX, "已选中最低层，无法下移！");
        } else if (!WareTools.checkOrder(listStore)) {
            result = JSONTools.toString(ResponseCodeMsg.CODE_EX, "请选中连续数据移动！");
        } else {

            num += storeMapper.updateForUpDownByStep(listStore.get(0).getWare().getId(), listStore.get(0).getStack().getId(), userId, belongId, min - step, min - 1, -1 * (min - 1));
            num += storeMapper.updateForUpDownByStep(listStore.get(0).getWare().getId(), listStore.get(0).getStack().getId(), userId, belongId, min, max, -1 * step);
            num += storeMapper.updateForUpDownByStep(listStore.get(0).getWare().getId(), listStore.get(0).getStack().getId(), userId, belongId, 0 - step, 0, max);
            listDown = storeMapper.selectForUpDown(listStore.get(0).getWare().getId(), listStore.get(0).getStack().getId(), userId, belongId, min - step, max - step);

            result = JSONTools.toString(listDown);
        }

        return result;
    }

    @Override
    public String allDown(String wareId,String stackId, String userId, String belongId) {
        List<Store> listStore = storeMapper.select(wareId,stackId,userId,belongId);
        for (int i = listStore.size();i>0;i--){
            listStore.get(i).setLayer(i);
            num += storeMapper.updateByPrimaryKey(listStore.get(i));
        }
        result = Tools.moreThanZeroResultJSON(num);
        return result;
    }

    @Override
    public String move(String json, String from, String to, int layer, String userId, String belongId) {
        List<Store> listStore = JSON.parseObject(json, new TypeReference<List<Store>>() {
        });
        Stack fromStack = JSON.parseObject(from, new TypeReference<Stack>() {
        });
        Stack toStack = JSON.parseObject(to, new TypeReference<Stack>() {
        });
        Collections.sort(listStore);
        int currentLayer = Integer.parseInt(storeMapper.selectLayerByStackId(toStack.getId(), belongId));
        int layerNew = 0;
        int layerOld = 0;
        for (int i = 0; i < listStore.size(); i++) {
            layerOld = listStore.get(i).getLayer();

            if (toStack.getIsLayer().equals("0")) {
                layerNew = 0;
            } else if (toStack.getIsLayer().equals("1")) {
                layerNew = currentLayer + 1 + i;
            } else if (toStack.getIsLayer().equals("2")) {
                layerNew = layer;
            }

            listStore.get(i).setWare(toStack.getWare());
            listStore.get(i).setStack(toStack);
            listStore.get(i).setLayer(layerNew);

            MoveRecord moveRecord = getMoveRecord(listStore.get(i), fromStack, toStack, layerNew, layerOld, userId);
            num = moveRecordMapper.insert(moveRecord);


            num += storeMapper.updateByPrimaryKey(listStore.get(i));
        }
        result = Tools.moreThanZeroResultJSON(num);
        return result;
    }

    @Override
    public String moveCheck(String json, String from,
                            String to, String userId, String belongId) {
        List<Store> listStore = JSON.parseObject(json, new TypeReference<List<Store>>() {
        });
        Stack fromStack = JSON.parseObject(from, new TypeReference<Stack>() {
        });

        if (fromStack.getIsLayer().equals("0") || fromStack.getIsLayer().equals("2")) {
            result = JSONTools.toString("");
        } else {
            Collections.sort(listStore);
            int currentLayer = Integer.parseInt(storeMapper.selectLayerByStackId(listStore.get(0).getStack().getId(), belongId));
            int min = listStore.get(0).getLayer();
            int max = listStore.get(listStore.size() - 1).getLayer();
            if (currentLayer != max) {
                result = JSONTools.toString(ResponseCodeMsg.CODE_EX, "只能选中最上层数据移动！");
            } else if (!WareTools.checkOrder(listStore)) {
                result = JSONTools.toString(ResponseCodeMsg.CODE_EX, "请选中连续数据移动！");
            } else {
                result = JSONTools.toString("");
            }
        }
        return result;
    }

    private MoveRecord getMoveRecord(Store store, Stack fromStack, Stack toStack, int layerNew, int layerOld, String userId) {
        MoveRecord moveRecord = new MoveRecord();
        moveRecord.setWareNameOld(fromStack.getWare().getName());
        moveRecord.setWareNameNew(toStack.getWare().getName());
        moveRecord.setStackNameOld(fromStack.getName());
        moveRecord.setStackNameNew(toStack.getName());
        moveRecord.setLayerOld(layerOld);
        moveRecord.setLayerNew(layerNew);
        moveRecord.setMaterialName(store.getMaterial().getName());
        // moveRecord.setMaterialNo(store.getMaterialNo());
        moveRecord.setStandard(store.getMaterial().getStandard());
        moveRecord.setModel(store.getModel());
        moveRecord.setCustomerName(store.getCustomer().getName());
        // moveRecord.setCustomerNo(store.getCustomerNo());
        moveRecord.setCount(store.getCount());
        moveRecord.setWeight(store.getWeight());
        moveRecord.setRemark(store.getRemark());
        moveRecord.setBelongId(store.getBelongId());
        moveRecord.setPlateNo(store.getPlateNo());
        moveRecord.setAddUser(new SysUser(userId));
        moveRecord.setAddTime(new Date());
        moveRecord.setReceiveAddress(store.getReceiveAddress());
        moveRecord.setWgtDcnMtcCd(store.getWgtDcnMtcCd());
        moveRecord.setEdgeTy(store.getEdgeTy());
        moveRecord.setProductionPlace(store.getProductionPlace());
        moveRecord.setCancelFlag("0");
        return moveRecord;
    }

}


