package com.bailuntec.job;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.bailuntec.domain.entity.DcBaseCompanyAccount;
import com.bailuntec.domain.entity.JobPointLog;
import com.bailuntec.domain.example.DcBaseCompanyAccountExample;
import com.bailuntec.domain.pojo.AccountResult;
import com.bailuntec.domain.pojo.CompanyAccountInfo;
import com.bailuntec.mapper.DcBaseCompanyAccountMapper;
import com.bailuntec.support.PointJob;
import com.bailuntec.utils.OkHttpUtil;
import com.bailuntec.utils.PropertiesUtil;
import com.bailuntec.utils.SessionUtil;
import com.dangdang.ddframe.job.api.ShardingContext;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
public class CompanyAccountSyncJob extends PointJob {
    private PropertiesUtil propertiesUtil = PropertiesUtil.getInstance("const");
    private OkHttpClient client = OkHttpUtil.getInstance();

    @Override
    public void executeJob(ShardingContext shardingContext, JobPointLog jobPointLog) {
        Request request = new Request.Builder()
                .url(propertiesUtil.getPropertyAsString("COMPANY_ACCOUNT_URL"))
                .get()
                .addHeader("Content-Type", "application/json")
                .build();
        Response response = null;
        String resultStr = null;
        try {
            response = client.newCall(request).execute();
            resultStr = response.body().string();
        } catch (IOException e) {
            throw new RuntimeException("调用公司账户授权信息接口失败", e);
        } finally {
            if (response != null) {
                response.close();
            }
        }
        if (StringUtils.isNotBlank(resultStr)) {
            AccountResult<CompanyAccountInfo> companyAccountInfoResult = JSONObject.parseObject(resultStr, new TypeReference<AccountResult<CompanyAccountInfo>>() {
            });
            if (companyAccountInfoResult.getSuccess() != null && companyAccountInfoResult.getSuccess()) {
                List<CompanyAccountInfo> result = companyAccountInfoResult.getData();
                if (result != null && result.size() > 0) {
                    DcBaseCompanyAccountMapper mapper = SessionUtil.getSession().getMapper(DcBaseCompanyAccountMapper.class);
                    DcBaseCompanyAccount dcBaseCompanyAccount = new DcBaseCompanyAccount();

                    try {
                        // Add by Allan at 20200718
                        mapper.updatesetstatusoff();

                        for (CompanyAccountInfo companyAccountInfo : result) {
                            BeanUtils.copyProperties(dcBaseCompanyAccount, companyAccountInfo);
                            dcBaseCompanyAccount.setBjModified(LocalDateTime.now());
                            int i = mapper.updateByExampleSelective(dcBaseCompanyAccount, DcBaseCompanyAccountExample.newAndCreateCriteria()
                                    .andCompanyIdEqualTo(companyAccountInfo.getCompanyId())
                                    .andAccountIdEqualTo(companyAccountInfo.getAccountId()).example());
                            if (i == 0) {
                                mapper.insertSelective(dcBaseCompanyAccount);
                            }
                        }
                    } catch (Exception e) {
                        throw new RuntimeException("Mybatis操作DB失败", e);
                    } finally {
                        SessionUtil.closeSession();
                    }
                }
                log.info("授权账户信息完成");

            } else {
                throw new RuntimeException("调用公司账户授权信息接口返回错误");
            }
        } else {
            throw new RuntimeException("调用公司账户授权信息接口返回null");
        }
    }

}
