package com.yeejoin.amos.api.openapi.face.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.csoft.sdk.client.CsoftDefaultSdkClient;
import com.csoft.sdk.domain.App;
import com.csoft.sdk.domain.CsoftDataTzsbXkxxListParam;
import com.csoft.sdk.domain.request.CsoftDataTzsbXkxxListRequest;
import com.csoft.sdk.domain.response.CsoftDataTzsbXkxxListResponse;
import com.yeejoin.amos.api.openapi.face.model.TaLicenseDetailInfoModel;
import com.yeejoin.amos.api.openapi.face.orm.dao.TaLicenseDetailInfoMapper;
import com.yeejoin.amos.api.openapi.face.orm.entity.TaLicenseDetailInfo;

/**
 * 附件表 服务实现类
 *
 * @author duanwei
 * @date 2022-08-17
 */
@Service
public class TaLicenseDetailInfoServiceImpl extends BaseService<TaLicenseDetailInfoModel, TaLicenseDetailInfo, TaLicenseDetailInfoMapper> {

    /**
     *
     * 新增许可信息-许可详细信息表
     *
     * @param model 许可详细信息实体类集合
     * @return 成功返回“OK”
     */
    @Transactional(rollbackFor= {Exception.class})
    public String saveLicenseDetailInfo(List<TaLicenseDetailInfo> model) {
        //TODO Auto-generated method stub
        if (ValidationUtil.isEmpty(model)) {
            throw new BadRequest("接入配置表信息为空.");
        }
        for (TaLicenseDetailInfo models : model) {
//            checkModel(models);
            models.setRecDate(new Date());
//            models.setAppId(getAppId());
        }
        this.saveBatch(model);
        return "OK";
    }
    
    public void syncLicenseData() throws Exception {
		Map<String, String> map = TaAccessConfigServiceImpl.licenseConfig;
		String appId = map.get("appId");
		String appKey = map.get("appKey");
		String appSecret = map.get("appSecret");
		String server = map.get("server");
		String startTime = map.get("startTime");
		String endTime = map.get("endTime");
		App app = App.of(appId, appKey, appSecret, server);
		int current = 1;
		int size = Integer.valueOf(map.get("pageSize"));
		// 2.初始化请求客户端
		CsoftDefaultSdkClient client = CsoftDefaultSdkClient.of(app);
		// 3.设置参数，发送请求，并处理结果
		CsoftDataTzsbXkxxListParam csoftDataTzsbXKxxListParam = new CsoftDataTzsbXkxxListParam();
		csoftDataTzsbXKxxListParam.setStaTime(startTime);
		// 开始日期
		csoftDataTzsbXKxxListParam.setEndTime(endTime);
		// 结束日期
		csoftDataTzsbXKxxListParam.setPageSize(size); // 每 页记录数
		csoftDataTzsbXKxxListParam.setCurrentPage(current); // 当前页码
		CsoftDataTzsbXkxxListRequest request = new CsoftDataTzsbXkxxListRequest(csoftDataTzsbXKxxListParam);
		CsoftDataTzsbXkxxListResponse response = client.execute(request);
		// 4.返回校验
		if (response.isSuccess()) {
			System.out.println("成功：" + response.getData());
			System.out.println(response.getResult());
			JSONObject jsonObject = JSONObject.parseObject(response.getData());
			JSONObject data = jsonObject.getJSONObject("data");
			JSONArray jsonArray = data.getJSONArray("objList");
			List<TaLicenseDetailInfo> list = new ArrayList<TaLicenseDetailInfo>();
			for (Object obj : jsonArray) {
				String jsonString = JSONObject.toJSONString(obj);
				TaLicenseDetailInfo taLicenseDetailInfo = JSONObject.parseObject(jsonString, TaLicenseDetailInfo.class);
				taLicenseDetailInfo.setSyncDate(new Date());
				taLicenseDetailInfo.setSyncState(0);
				TaLicenseDetailInfo oldTaLicenseDetailInfo = this.getOne(new LambdaQueryWrapper<TaLicenseDetailInfo>()
						.eq(TaLicenseDetailInfo::getId, taLicenseDetailInfo.getId()));
				if (oldTaLicenseDetailInfo != null) {
					taLicenseDetailInfo.setSequenceNbr(oldTaLicenseDetailInfo.getSequenceNbr());
				}
				list.add(taLicenseDetailInfo);
			}
			this.saveOrUpdateBatch(list);

			while (data.getInteger("totalNum") > current * size) {
				csoftDataTzsbXKxxListParam.setCurrentPage(++current);
				saveData(client, csoftDataTzsbXKxxListParam);
			}
		} else {
			System.out.println("失败：" + response.getErrorMsg());
			System.out.println("失败：" + response.getErrorCode());
			throw new Exception(response.getErrorMsg());
		}
	}

	private void saveData(CsoftDefaultSdkClient client, CsoftDataTzsbXkxxListParam csoftDataTzsbXKxxListParam) throws Exception {
		// 2.初始化请求客户端
		CsoftDataTzsbXkxxListRequest request = new CsoftDataTzsbXkxxListRequest(csoftDataTzsbXKxxListParam);
		CsoftDataTzsbXkxxListResponse response = client.execute(request);
		// 4.返回校验
		if (response.isSuccess()) {
			System.out.println("成功：" + response.getData());
			System.out.println(response.getResult());
			JSONObject jsonObject = JSONObject.parseObject(response.getData());
			JSONObject data = jsonObject.getJSONObject("data");
			JSONArray jsonArray = data.getJSONArray("objList");
			List<TaLicenseDetailInfo> list = new ArrayList<TaLicenseDetailInfo>();
			for (Object obj : jsonArray) {
				String jsonString = JSONObject.toJSONString(obj);
				TaLicenseDetailInfo taLicenseDetailInfo = JSONObject.parseObject(jsonString, TaLicenseDetailInfo.class);
				taLicenseDetailInfo.setSyncDate(new Date());
				taLicenseDetailInfo.setSyncState(0);
				TaLicenseDetailInfo oldTaLicenseDetailInfo = this.getOne(new LambdaQueryWrapper<TaLicenseDetailInfo>()
						.eq(TaLicenseDetailInfo::getId, taLicenseDetailInfo.getId()));
				if (oldTaLicenseDetailInfo != null) {
					taLicenseDetailInfo.setSequenceNbr(oldTaLicenseDetailInfo.getSequenceNbr());
				}
				list.add(taLicenseDetailInfo);
			}
			this.saveOrUpdateBatch(list);
		} else {
			System.out.println("失败：current:" + csoftDataTzsbXKxxListParam.getCurrentPage());
			System.out.println("失败：" + response.getErrorMsg());
			System.out.println("失败：" + response.getErrorCode());
			throw new Exception(response.getErrorMsg());
		}
	}

}
