package com.bailuntec.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.bailuntec.domain.entity.DcBaseWarehouse;
import com.bailuntec.domain.pojo.AccountNoToken;
import com.bailuntec.domain.pojo.BaseWarehouse;
import com.bailuntec.mapper.DcBaseWarehouseMapper;
import com.bailuntec.support.CallBailunSystem;
import com.bailuntec.utils.OkHttpUtil;
import com.bailuntec.utils.PropertiesUtil;
import com.bailuntec.utils.SessionUtil;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import okhttp3.*;
import org.apache.commons.beanutils.BeanUtils;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

public class WarehouseSyncJob implements SimpleJob {
    private PropertiesUtil propertiesUtil = PropertiesUtil.getInstance("const");

    @Override
    public void execute(ShardingContext shardingContext) {
        OkHttpClient client = OkHttpUtil.getInstance();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{data:{}}");
        Request request = new Request.Builder()
                .url(propertiesUtil.getPropertyAsString("WAREHOUSE_URL"))
                .post(body)
                .addHeader("Content-Type", "application/json")
                .addHeader("cache-control", "no-cache")
                .build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("调用WMS仓库信息接口失败", e);
        }
        DcBaseWarehouse dcBaseWarehouse = null;
        if (response != null && response.isSuccessful()) {
            JSONObject jsonObject = null;
            try {
                jsonObject = JSON.parseObject(response.body().string());
            } catch (IOException e) {
                throw new RuntimeException("WMS接口仓库信息JSON解析失败", e);
            } finally {
                if (response != null) {
                    response.close();
                }
            }
            if (jsonObject.get("isSuccess") != null && jsonObject.getBooleanValue("isSuccess")) {
                List<BaseWarehouse> baseWarehouseList = jsonObject.getObject("data", new TypeReference<List<BaseWarehouse>>() {
                });
                if (baseWarehouseList != null && baseWarehouseList.size() > 0) {
                    DcBaseWarehouseMapper mapper = SessionUtil.getSession().getMapper(DcBaseWarehouseMapper.class);
                    try {
                        for (BaseWarehouse baseWarehouse : baseWarehouseList) {
                            dcBaseWarehouse = new DcBaseWarehouse();
                            try {
                                BeanUtils.copyProperties(dcBaseWarehouse, baseWarehouse);
                            } catch (IllegalAccessException e) {
                                throw new RuntimeException("BeanUtils-copyProperties失败", e);
                            } catch (InvocationTargetException e) {
                                throw new RuntimeException("BeanUtils-copyProperties失败", e);
                            }
                            dcBaseWarehouse.setAreaId(baseWarehouse.getArea().getId());
                            dcBaseWarehouse.setAreaName(baseWarehouse.getArea().getName());
                            dcBaseWarehouse.setFunctions(JSON.toJSONString(baseWarehouse.getFunctions()));
                            //通过BailunAccountId调接口取bailunAccount
                            AccountNoToken account = null;
                            if (dcBaseWarehouse.getBailunAccountId() > 0) {
                                account = CallBailunSystem.getBailunAccount(dcBaseWarehouse.getBailunAccountId());
                                if (account != null) {
                                    dcBaseWarehouse.setBailunAccount(account.getAccount() + "-" + account.getSiteEn());
                                }
                            }

                            mapper.upsertSelective(dcBaseWarehouse);
                            SessionUtil.getSession().commit();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw new RuntimeException("解析WMS接口仓库信息并插入DB失败", e);
                    } finally {
                        SessionUtil.closeSession();
                    }
                }
            } else {
                throw new RuntimeException("调用WMS接口同步仓库信息失败, 响应200, 请求参数无");
            }
        }
    }

}
