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.finance.AccountDetailMapper;
import com.th.demo.mapping.maint.*;
import com.th.demo.mapping.ware.*;
import com.th.demo.model.finance.AccountDetail;
import com.th.demo.model.maint.Price;
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.*;
import com.th.demo.service.ware.InService;
import com.th.demo.service.ware.OutService;
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.*;

@Service("OutService")
public class OutServiceImpl implements OutService {

    @Autowired
    public OutRecordMapper outRecordMapper;
    @Autowired
    public StoreMapper storeMapper;
    @Autowired
    public WareMapper wareMapper;
    @Autowired
    public StackMapper stackMapper;
    @Autowired
    public CustomerMapper customerMapper;
    @Autowired
    public MaterialMapper materialMapper;
    @Autowired
    public DistributionMapper distributionMapper;
    @Autowired
    public AccountDetailMapper accountDetailMapper;
    @Autowired
    public ChangeRecordMapper changeRecordMapper;
    @Autowired
    public PriceMapper priceMapper;

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

    @Override
    public String out(String json, String userId, String belongId) {

//        List<Store> listStore = JSON.parseObject(json, new TypeReference<List<Store>>() {
//        });
//        Stack stack = stackMapper.selectByWareNameStackName(listStore.get(0).getWareName(), listStore.get(0).getStackName(), userId, belongId);
//
//        if (stack.getIsLayer().equals("0")||stack.getIsLayer().equals("2")) {
//            for (int i = 0; i < listStore.size(); i++) {
//                OutRecord outRecord = getOutRecord(listStore.get(i), "","1", userId);
//                num += outRecordMapper.insert(outRecord);
//                listStore.get(i).setOutId(outRecord.getId());
//                listStore.get(i).setCancelFlag("4");
//                num += storeMapper.updateByPrimaryKey(listStore.get(i));
//            }
//            result = Tools.moreThanZeroResultJSON(num);
//        } else {
//            Collections.sort(listStore);
//            int currentLayer = Integer.parseInt(storeMapper.selectLayerByStackName(listStore.get(0).getWareName(), listStore.get(0).getStackName(), 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 {
//                for (int i = 0; i < listStore.size(); i++) {
//                    OutRecord outRecord = getOutRecord(listStore.get(i),"", "1", userId);
//                    num += outRecordMapper.insert(outRecord);
//                    listStore.get(i).setOutId(outRecord.getId());
//                    listStore.get(i).setOutFlag("9");
//                    num += storeMapper.updateByPrimaryKey(listStore.get(i));
//                }
//                result = Tools.moreThanZeroResultJSON(num);
//            }
//        }
        return result;
    }

    @Override
    public String back(String json, String to, String userId, String belongId) {
        List<OutRecord> listOutRecord = JSON.parseObject(json, new TypeReference<List<OutRecord>>() {
        });
        Stack stack = JSON.parseObject(to, new TypeReference<Stack>() {
        });
        int currentLayer = 0;
        Store store;
        String noUserParam = "a";
        for (int i = 0; i < listOutRecord.size(); i++) {
            listOutRecord.get(i).setBackFlag("1");
            listOutRecord.get(i).setCancelFlag("9");
            num += outRecordMapper.updateByPrimaryKey(listOutRecord.get(i));
            store = storeMapper.selectByOutId(listOutRecord.get(i).getId(), noUserParam, userId, belongId);
            storeMapper.updateByOutId(listOutRecord.get(i).getId(), noUserParam, userId, belongId);
            store.setOutFlag("0");   //孙雪松 取消出库恢复原有状态
            store.setOutId("");
            store.setLockFlag("0");
            currentLayer = Integer.parseInt(storeMapper.selectLayerByStackId(store.getStack().getId(), belongId));
            store.setLayer(currentLayer + 1);
            //store.setStack(stack);
            OutRecord outRecord = getOutRecord(store, "", "0", userId);
            num += outRecordMapper.insert(outRecord);
            num += storeMapper.insert(store);
            Distribution distribution = distributionMapper.selectByPrimaryKey(listOutRecord.get(i).getDistributionId());
            distribution.setSumWeight(distribution.getSumWeight()- store.getWeight());
            distribution.setSumCount(distribution.getSumCount()- store.getCount());
            num=distributionMapper.updateByPrimaryKey(distribution);
        }
        result = Tools.moreThanZeroResultJSON(num);
        return result;


    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String outByDistribution(String json, String userId, String belongId) throws Exception {
        Distribution distribution = JSON.parseObject(json, new TypeReference<Distribution>() {
        });
        distribution.setOutFlag("1");
        num += distributionMapper.updateByPrimaryKey(distribution);
        List<String> listStoreId = new ArrayList<String>();
        for (int i = 0; i < distribution.getListDetail().size(); i++) {
            listStoreId.add(distribution.getListDetail().get(i).getStore().getId());
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("storeId", listStoreId);
        for(int i = 0 ;i < listStoreId.size();i++){
            System.out.println(listStoreId.get(i));
        }
        List<StoreOfWareStack> listSows = storeMapper.selectWareStackByDistributionStore(map);

        for (int m = 0; m < listSows.size(); m++) {


            Stack stack = stackMapper.selectByPrimaryKey(listSows.get(m).getStackId());
            Map<String, Object> mapParam = new HashMap<String, Object>();
            mapParam.put("storeId", listStoreId);
            mapParam.put("wareId", listSows.get(m).getWareId());
            mapParam.put("stackId", listSows.get(m).getStackId());

            List<Store> listStore = storeMapper.selectByWareIdStackIdInStoreId(mapParam);
            if (stack.getIsLayer().equals("0") || stack.getIsLayer().equals("2")) {
                for (int i = 0; i < listStore.size(); i++) {
                    OutRecord outRecord = getOutRecord(listStore.get(i), distribution.getId(), "1", userId);
                    num += outRecordMapper.insert(outRecord);
                    AccountDetail accountDetail = getAccountDetail(listStore.get(i), distribution.getSumWeight(), distribution.getSuttle(), userId, belongId);
                    num += accountDetailMapper.insert(accountDetail);
                    listStore.get(i).setOutId(outRecord.getId());
                    listStore.get(i).setOutFlag("1");
                    num += storeMapper.updateByPrimaryKey(listStore.get(i));
                }
                result = Tools.moreThanZeroResultJSON(num);
            } 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) {
//                    throw new Exception("库房：" + listStore.get(m).getWare().getName() + ",垛位：" + listStore.get(m).getStack().getName() + ",出库物料不在最上层，无法出库！");
//                    // result = JSONTools.toString(ResponseCodeMsg.CODE_EX, "必须选择最上层出库！");
//                } else if (!WareTools.checkOrder(listStore)) {
//                    throw new Exception("库房：" + listStore.get(m).getWare().getName() + ",垛位：" + listStore.get(m).getStack().getName() + ",出库物料不在最上层，无法出库！");
//                    //  result = JSONTools.toString(ResponseCodeMsg.CODE_EX, "请选中连续数据移动！");
//                } else {
//
//                }
                for (int i = 0; i < listStore.size(); i++) {
                    OutRecord outRecord = getOutRecord(listStore.get(i), distribution.getId(), "1", userId);
                    num += outRecordMapper.insert(outRecord);

                    AccountDetail accountDetail = getAccountDetail(listStore.get(i), distribution.getSumWeight(), distribution.getSuttle(), userId, belongId);
                    num += accountDetailMapper.insert(accountDetail);

                    listStore.get(i).setOutId(outRecord.getId());
                    listStore.get(i).setOutFlag("1");
                    num += storeMapper.updateByPrimaryKey(listStore.get(i));

                }
                result = Tools.moreThanZeroResultJSON(num);
            }
        }
        return result;
    }

    private AccountDetail getAccountDetail(Store store, Double sumWeight, Double suttle, String userId, String belongId) throws Exception {
        int changeTime = 0;
        int changeTimeForPrice = 0;
        Double plateSuttle = 0.0;
        Double storagePrice = 0.0;
        Double weightPrice = 0.0;

        List<ChangeRecord> list = changeRecordMapper.selectByPlantNoForAccount(store.getPlateNo(), belongId);
        if (list == null || list.size() == 0) {
            changeTime = 0;
            changeTimeForPrice = 0;
        } else {
            changeTime = list.size();
            changeTimeForPrice = 1;
        }
        /*Price price = priceMapper.selectByMaterialChangeTime(store.getMaterial().getId(), changeTimeForPrice, belongId);
        if (price == null) {
            throw new Exception(store.getMaterial().getName() + "," + store.getMaterial().getStandard() + "没有对应价格信息");
        }*/
        AccountDetail accountDetail = new AccountDetail();
        accountDetail.setChangeTime(changeTime);
        accountDetail.setRecordType("出库");

        accountDetail.setPlateNo(store.getPlateNo());
        accountDetail.setWareName(store.getWare().getName());
        accountDetail.setStackName(store.getStack().getName());
        accountDetail.setLayer(store.getLayer());
        accountDetail.setMaterialName(store.getMaterial().getName());
        accountDetail.setStandard(store.getMaterial().getStandard());
        accountDetail.setModel(store.getModel());
        accountDetail.setCustomerName(store.getCustomer().getName());
        accountDetail.setCount(store.getCount());
        accountDetail.setWeight(store.getWeight());
        accountDetail.setReceiveAddress(store.getReceiveAddress());
        accountDetail.setAccountFlag("0");
        accountDetail.setAddUser(new SysUser(userId));
        accountDetail.setAddTime(new Date());
        accountDetail.setCancelFlag("0");
        accountDetail.setBelongId(belongId);
        if (suttle == 0) {
            plateSuttle = 0.0;
            //storagePrice = price.getStoragePrice() * store.getWeight();
            weightPrice = 0.0;
        } else {
            plateSuttle = suttle / sumWeight * store.getWeight();
            //storagePrice = price.getStoragePrice() * plateSuttle;
           // weightPrice = price.getWeightPrice() * plateSuttle;
        }
        accountDetail.setSuttle(plateSuttle);

        accountDetail.setStoragePrice(storagePrice);
        accountDetail.setWeightPrice(weightPrice);
        accountDetail.setReducePrice(0.0);
        accountDetail.setTotalPrice(storagePrice+weightPrice);

      //  accountDetail.setStorageUnitPrice(price.getStoragePrice());
       // accountDetail.setWeightUnitPrice(price.getWeightPrice());
        accountDetail.setReduceUnitPrice(0.0);

        return accountDetail;
    }

    private OutRecord getOutRecord(Store store, String distributionId, String recordType, String userId) {
        OutRecord outRecord = new OutRecord();
        outRecord.setWareName(store.getWare().getName());
        outRecord.setStackName(store.getStack().getName());
        outRecord.setLayer(store.getLayer());
        outRecord.setMaterialName(store.getMaterial().getName());
        outRecord.setStandard(store.getMaterial().getStandard());
        outRecord.setModel(store.getModel());
        outRecord.setCustomerName(store.getCustomer().getName());
        if (recordType.equals("0")) {
            outRecord.setCount(-1 * store.getCount());
            outRecord.setWeight(-1 * store.getWeight());
        } else {
            outRecord.setCount(store.getCount());
            outRecord.setWeight(store.getWeight());
        }
        if (recordType.equals("0")) {
            outRecord.setCancelFlag("9");
        } else {
            outRecord.setCancelFlag("0");
        }

        outRecord.setPackNo(store.getPackNo());
        outRecord.setContractNo(store.getContractNo());
        outRecord.setOrdNo(store.getOrdNo());

        outRecord.setRemark(store.getRemark());
        outRecord.setBelongId(store.getBelongId());
        outRecord.setPlateNo(store.getPlateNo());
        outRecord.setAddUser(new SysUser(userId));
        outRecord.setAddTime(new Date());
        outRecord.setInId(store.getInId());
        outRecord.setRecordType(recordType);
        outRecord.setReceiveAddress(store.getReceiveAddress());
        outRecord.setDistributionId(distributionId);


        outRecord.setWgtDcnMtcCd(store.getWgtDcnMtcCd());
        outRecord.setEdgeTy(store.getEdgeTy());
        outRecord.setProductionPlace(store.getProductionPlace());
        outRecord.setInvoicePrice(store.getInvoicePrice());
        return outRecord;
    }


}
