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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yeejoin.amos.api.common.restful.utils.ApplicationContextUtils;
import com.yeejoin.amos.api.openapi.constant.Constant;
import com.yeejoin.amos.api.openapi.enums.EightCategorySubformEnum;
import com.yeejoin.amos.api.openapi.enums.EquipTypeEnum;
import com.yeejoin.amos.api.openapi.face.model.BizTokenModel;
import com.yeejoin.amos.api.openapi.face.orm.dao.EquipTechParamBoilerMapper;
import com.yeejoin.amos.api.openapi.face.orm.entity.AbstractEquipBaseEntity;
import com.yeejoin.amos.api.openapi.face.orm.entity.EquipTechParamRopeway;
import net.sf.json.JSONObject;
import org.apache.catalina.core.ApplicationContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.ui.context.support.UiApplicationContextUtils;
import org.typroject.tyboot.component.cache.Redis;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;

import java.util.*;

@Service
public class TechInfoService {

    public String saveTechInfo(List<JSONObject> techInfoList){
        List<String> failSupervisoryCode = new ArrayList<>();
        String appId = getAppId();
        for (JSONObject techInfo: techInfoList) {
            AbstractEquipBaseEntity entity = null;
            String type = techInfo.getString("type");
            try {
                //存主表
                String entityClasspath = EquipTypeEnum.classPathmap.get(type);
                String serviceClasspath = EquipTypeEnum.servicePathmap.get(type);
                if(ValidationUtil.isEmpty(entityClasspath)){
                    failSupervisoryCode.add("type类型错误{"+"type:"+type+",supervisoryCode:"+techInfo.getString("supervisoryCode")+"}");
                    continue;
                }
                Class entityClazz = Class.forName(entityClasspath);
                Class serviceClazz = Class.forName(serviceClasspath);
                BaseService service = (BaseService) ApplicationContextUtils.newAutoWiredInstance(serviceClazz);
                entity = (AbstractEquipBaseEntity) JSON.parseObject(JSON.toJSONString(techInfo),entityClazz);
                entity.setRecDate(new Date());
                entity.setAppId(appId);
                service.save(entity);
            } catch (Exception e) {
                e.printStackTrace();
                failSupervisoryCode.add("数据错误{"+"type:"+type+",supervisoryCode:"+techInfo.getString("supervisoryCode")+"}");
                continue;
            }

            try {
                //存子表单
                String fileNames = EquipTypeEnum.serviceFileListmap.get(type);
                if(!ValidationUtil.isEmpty(fileNames)) {
                    String[] fileName = fileNames.split(",");
                    for (String file : fileName) {
                        String value = techInfo.getString(file);
                        if(!ValidationUtil.isEmpty(value)) {
                            String subFormEntitypath = EightCategorySubformEnum.classPathmap.get(file);
                            String subFormServicepath = EightCategorySubformEnum.servicePathmap.get(file);
                            Class subFormEntityClazz = Class.forName(subFormEntitypath);
                            Class subFormServiceClazz = Class.forName(subFormServicepath);
                            List<AbstractEquipBaseEntity> array = new ArrayList<>();
                            array = JSON.parseArray(value, subFormEntityClazz);
                            AbstractEquipBaseEntity finalEntity = entity;
                            array.forEach(e -> {
                                e.setAppId(appId);
                                e.setRecDate(new Date());
                                e.setSyncDate(finalEntity.getSyncDate());
                                e.setSyncState(finalEntity.getSyncState());
                            });
                            BaseService service = (BaseService) ApplicationContextUtils.newAutoWiredInstance(subFormServiceClazz);
                            service.saveBatch(array);
                        }
                    }
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        String result = "ok";
        if(!ValidationUtil.isEmpty(failSupervisoryCode)){
            result = "数据添加失败:"+JSON.toJSONString(failSupervisoryCode);
        }
        return result;
    }


    @Autowired
    private RedisTemplate redisTemplate;

    public String getAppId() {
        String tokenKey = Redis.genKey(Constant.TOKEN_PREFIX, RequestContext.getToken());
        BizTokenModel bizTokenModel = (BizTokenModel) redisTemplate.opsForValue().get(tokenKey);
        return bizTokenModel.getAppId();
    }

//    public String getAppId() {
//        return "HSICIOWOC";
//    }
}
