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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
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.TaAccessConfig;
import com.yeejoin.amos.api.openapi.face.orm.entity.TaLicenseDetailInfo;
import com.yeejoin.amos.openapi.enums.TaAccessConfigBizeEnum;
import org.springframework.beans.factory.annotation.Autowired;
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 java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 附件表 服务实现类
 *
 * @author duanwei
 * @date 2022-08-17
 */
@Service
public class TaLicenseDetailInfoServiceImpl extends BaseService<TaLicenseDetailInfoModel, TaLicenseDetailInfo, TaLicenseDetailInfoMapper> {
	@Autowired
	TaAccessConfigServiceImpl taAccessConfigServiceImpl;
    /**
     *
     * 新增许可信息-许可详细信息表
     *
     * @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.configMap.get(TaAccessConfigBizeEnum.LICENSE.getAttribute());
		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");
		int isAll = Integer.valueOf(map.get("isAllDetail"));
		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();
		if (isAll == 0) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			// 开始日期
			csoftDataTzsbXKxxListParam.setStaTime(startTime);
			// 结束日期
			csoftDataTzsbXKxxListParam.setEndTime(sdf.format(new Date()));
		} else {
			SimpleDateFormat sdfsta = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
			SimpleDateFormat sdfend = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
			// 开始日期
			csoftDataTzsbXKxxListParam.setStaTime(sdfsta.format(new Date()));
			// 结束日期
			csoftDataTzsbXKxxListParam.setEndTime(sdfend.format(new Date()));
		}
		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);
			}
			
			if (isAll == 0) {
				taAccessConfigServiceImpl
						.update(new LambdaUpdateWrapper<TaAccessConfig>().eq(TaAccessConfig::getBizType, "license")
								.eq(TaAccessConfig::getBizKey, "isAllDetail").set(TaAccessConfig::getBizValue, 1));
			}
		} 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());
		}
	}

}
