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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
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.*;
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.*;
import com.th.demo.service.ware.DistributionService;
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("DistributionService")
public class DistributionServiceImpl implements DistributionService {

    @Autowired
    public DistributionMapper distributionMapper;
    @Autowired
    public DistributionDetailMapper distributionDetailMapper;
    @Autowired
    public DistributionRecordMapper distributionRecordMapper;
    @Autowired
    public StoreMapper storeMapper;

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

    @Override
    public String queryWaitTrucks(String userId, String belongId) {

        List<Distribution> list = distributionMapper.selectWaitTrucks(userId, belongId);

        result = JSONTools.toString(list);
        return result;
    }

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

        Distribution distribution = JSON.parseObject(json, new TypeReference<Distribution>() {
        });
        List<Store> list = JSON.parseObject(jsonList, new TypeReference<List<Store>>() {
        });
        Distribution isExist = distributionMapper.selectByTruckNo(distribution.getTruckNo(), belongId);
        if (isExist == null) {
            distribution.setAddId(userId);
            distribution.setAddTime(new Date());
            distribution.setOutFlag("0");
            distribution.setBelongId(belongId);
            num += distributionMapper.insert(distribution);
            lockAndInsertDetail(list,distribution,userId,belongId);
        } else {
            distribution.setModifyId(userId);
            distribution.setModifyTime(new Date());
            num += distributionMapper.updateByPrimaryKey(distribution);
            lockAndInsertDetail(list,distribution,userId,belongId);
        }
        return Tools.moreThanZeroResultJSON(num);
    }

    @Override
    public String cancel(String json, String jsonList, String userId, String belongId) {
        Distribution distribution = JSON.parseObject(json, new TypeReference<Distribution>() {
        });
        List<Store> list = JSON.parseObject(jsonList, new TypeReference<List<Store>>() {
        });
        if (distribution.getListDetail().size() == list.size()) {
            distribution.setOutFlag("2");
            num += distributionMapper.updateByPrimaryKey(distribution);
        }
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setLockFlag("0");
            num += storeMapper.updateByPrimaryKey(list.get(i));
        }
        for (int i = 0; i < distribution.getListDetail().size(); i++) {
            for (int j = 0; j < list.size(); j++) {
                if (distribution.getListDetail().get(i).getStore().getId().equals(list.get(j).getId())) {
                    distribution.getListDetail().get(i).setCancelFlag("9");
                    distribution.getListDetail().get(i).setCancelId(userId);
                    distribution.getListDetail().get(i).setCancelTime(new Date());
                    num += distributionDetailMapper.updateByPrimaryKey(distribution.getListDetail().get(i));
                    DistributionRecord record  = getDistributionRecord(distribution,distribution.getListDetail().get(i).getStore(), "0",userId, belongId);
                    num += distributionRecordMapper.insert(record);
                }
            }

        }
        return Tools.moreThanZeroResultJSON(num);
    }

public void lockAndInsertDetail(  List<Store> list,  Distribution distribution , String userId, String belongId){
    // 重新获取ID，第一次配车的时候会出现没有ID的情况
    Distribution distribution1 = distributionMapper.selectByTruckNo(distribution.getTruckNo(), belongId);
    for (int i = 0; i < list.size(); i++) {
        Store store = storeMapper.selectByPrimaryKey(list.get(i).getId());
        // 存在赋值为空的情况，追加一次赋值
        // 2025.4.20 数据库增加默认为0的修改临时解决，此处其他项目中要注意
        if (store.getLockFlag() == null || store.getLockFlag() == ""){
            store.setLockFlag("0");
        }
        if (!store.getLockFlag().equals("1") && distribution1.getId() != null && distribution1.getId() != ""){
            list.get(i).setLockFlag("1");
            num += storeMapper.updateByPrimaryKey(list.get(i));
            DistributionDetail detail = getDistributionDetail(distribution1, list.get(i), userId, belongId);
            num += distributionDetailMapper.insert(detail);
            DistributionRecord record  = getDistributionRecord(distribution1, list.get(i), "1",userId, belongId);
            num += distributionRecordMapper.insert(record);
        }
    }
}
    public DistributionDetail getDistributionDetail(Distribution distribution, Store store, String userId, String belongId) {
        DistributionDetail detail = new DistributionDetail();
        detail.setDistributionId(distribution.getId());
        detail.setStore(store);
        detail.setAddId(userId);
        detail.setAddTime(new Date());
        detail.setCancelFlag("0");
        detail.setBelongId(belongId);
        return detail;
    }

    public DistributionRecord getDistributionRecord( Distribution distribution,Store store,String recordType,String userId,String belongId) {
        DistributionRecord record = new DistributionRecord();
        record.setTruckNo(distribution.getTruckNo());
        record.setWareName(store.getWare().getName());
        record.setStackName(store.getStack().getName());
        record.setLayer(store.getLayer());
        record.setMaterialName(store.getMaterial().getName());
        record.setStandard(store.getMaterial().getStandard());
        record.setModel(store.getModel());
        record.setCustomerName(store.getCustomer().getName());
        if (recordType.equals("0")) {
            record.setCount(-1 * store.getCount());
            record.setWeight(-1 * store.getWeight());
        } else {
            record.setCount(store.getCount());
            record.setWeight(store.getWeight());
        }
        record.setReceiveAddress(store.getReceiveAddress());
        record.setRemark(store.getRemark());
        record.setBelongId(belongId);
        record.setPlateNo(store.getPlateNo());
        record.setAddUser(new SysUser(userId));
        record.setAddTime(new Date());
        record.setRecordType(recordType);
        return record;
    }
}
