package com.sunda.spmswms.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunda.spmswms.entity.Whs;
import com.sunda.spmswms.mapper.WhsMapper;
import com.sunda.spmswms.service.IWhsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 仓库信息表 服务实现类
 * </p>
 *
 * @author Wayne
 * @since 2020-11-24
 */
@Service
@Slf4j
public class WhsServiceImpl extends ServiceImpl<WhsMapper, Whs> implements IWhsService {

    @Autowired
    WhsMapper whsMapper;

    @Override
    public List<Map<String, Object>> getWhsList() {
        return whsMapper.getAllWhs();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertWhs(JSONObject doc) {
        try {
            JSONArray array = doc.getJSONArray("Z_SPMS_GETWAREHOUSE_IT_LGORT");
            for(int i = 0; i<array.size(); i++) {
                System.out.println("=======" + array.size() + "    " + i + "   SAP 仓库信息  " + array.get(i).toString());
                JSONArray json = JSONArray.parseArray(array.get(i).toString());
                if (i > 0){
                    Whs whs = new Whs();
                    whs.setWerks(json.getString(0));
                    whs.setWhsLocationCode(json.getString(1));
                    whs.setWhsLocationDesc(json.getString(2));
                    whs.setWhsType(json.getString(3));
                    whs.setUserId(json.getString(4));
                    whs.setAddress(json.getString(5));
                    whs.setTelephone(json.getString(6));
                    whs.setCity(json.getString(7));
                    if (whsMapper.selectOne(new QueryWrapper<Whs>().eq("werks", whs.getWerks())) != null){
                        whsMapper.update(whs, new QueryWrapper<Whs>().eq("whsLocationCode", whs.getWhsLocationCode()));
                    }else {
                        whsMapper.insert(whs);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            log.info("=========== WhsServiceImpl.insertWhs 执行异常 " + e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
    }
}
