package com.yunzhupaas.base.util;

import cn.hutool.core.util.ObjectUtil;
import com.yunzhupaas.database.util.DynamicDataSourceUtil;
import com.yunzhupaas.message.model.websocket.onconnettion.OnLineModel;
import com.yunzhupaas.model.visualJson.FieLdsModel;
import com.yunzhupaas.permission.entity.PositionEntity;
import com.yunzhupaas.permission.entity.UserEntity;
import com.yunzhupaas.util.DateUtil;
import com.yunzhupaas.util.JsonUtil;
import com.yunzhupaas.util.visiual.YunzhupaasKeyConsts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.sql.Clob;
import java.util.*;

import static com.yunzhupaas.util.Constants.ADMIN_KEY;

/**
 * 在线详情编辑工具类
 *
 * @author 云筑产品开发平台组
 * @version V3.2
 * @copyright 深圳市乐程软件有限公司（http://www.szlecheng.cn）
 * @date 2024/10/27
 */
@Slf4j
@Component
public class FormInfoUtils {
    @Autowired
    private ServiceBaseUtil serviceUtil;

    /**
     * 转换数据格式(编辑页)
     *
     * @param modelList 控件
     * @param dataMap   数据
     * @return
     */
    public Map<String, Object> swapDataInfoType(List<FieLdsModel> modelList, Map<String, Object> dataMap) {
        dataMap = Optional.ofNullable(dataMap).orElse(new HashMap<>());
        try {
            DynamicDataSourceUtil.switchToDataSource(null);
            List<String> systemConditions = new ArrayList() {
                {
                    add(YunzhupaasKeyConsts.CURRORGANIZE);
                    add(YunzhupaasKeyConsts.CURRDEPT);
                    add(YunzhupaasKeyConsts.CURRPOSITION);
                }
            };
            List<String> nullIsList = new ArrayList() {
                {
                    add(YunzhupaasKeyConsts.UPLOADFZ);
                    add(YunzhupaasKeyConsts.UPLOADIMG);
                }
            };
            for (FieLdsModel swapDataVo : modelList) {
                String yunzhupaasKey = swapDataVo.getConfig().getYunzhupaasKey();
                String vModel = swapDataVo.getVModel();

                // clob字段转换
                FormInfoUtils.swapClob(dataMap, vModel);
                // 获取原字段数据
                FormPublicUtils.relationGetYunzhupaasId(dataMap, yunzhupaasKey, dataMap.get(vModel), vModel);

                Object value = dataMap.get(vModel);
                if (value == null || ObjectUtil.isEmpty(value)) {
                    if (systemConditions.contains(yunzhupaasKey)) {
                        dataMap.put(vModel, " ");
                    }
                    if (nullIsList.contains(yunzhupaasKey)) {
                        dataMap.put(vModel, Collections.emptyList());
                    }
                    continue;
                }
                switch (yunzhupaasKey) {
                    case YunzhupaasKeyConsts.UPLOADFZ:
                    case YunzhupaasKeyConsts.UPLOADIMG:
                        // 数据传递-乱塞有bug强行置空
                        List<Map<String, Object>> fileList = new ArrayList<>();
                        try {
                            fileList = JsonUtil.getJsonToListMap(dataMap.get(vModel).toString());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        dataMap.put(vModel, fileList);
                        break;
                    case YunzhupaasKeyConsts.DATE:
                        Long dateTime = DateTimeFormatConstant.getDateObjToLong(dataMap.get(vModel));
                        dataMap.put(vModel, dateTime != null ? dateTime : dataMap.get(vModel));
                        break;
                    case YunzhupaasKeyConsts.CREATETIME:
                    case YunzhupaasKeyConsts.MODIFYTIME:
                        String pattern = DateTimeFormatConstant.YEAR_MOnTH_DHMS;
                        Long time = DateTimeFormatConstant.getDateObjToLong(dataMap.get(vModel));
                        dataMap.put(vModel, time != null ? DateUtil.dateToString(new Date(time), pattern) : "");
                        break;
                    case YunzhupaasKeyConsts.SWITCH:
                    case YunzhupaasKeyConsts.SLIDER:
                    case YunzhupaasKeyConsts.RATE:
                    case YunzhupaasKeyConsts.CALCULATE:
                    case YunzhupaasKeyConsts.NUM_INPUT:
                        dataMap.put(vModel, value != null ? new BigDecimal(String.valueOf(value)) : null);
                        break;
                    case YunzhupaasKeyConsts.CURRPOSITION:
                        PositionEntity positionEntity = serviceUtil.getPositionInfo(String.valueOf(value));
                        dataMap.put(vModel, Objects.nonNull(positionEntity) ? positionEntity.getFullName() : value);
                        break;

                    case YunzhupaasKeyConsts.CREATEUSER:
                    case YunzhupaasKeyConsts.MODIFYUSER:
                        UserEntity userEntity = serviceUtil.getUserInfo(String.valueOf(value));
                        String userValue = Objects.nonNull(userEntity)
                                ? userEntity.getAccount().equalsIgnoreCase(ADMIN_KEY)
                                        ? "管理员/" + ADMIN_KEY
                                        : userEntity.getRealName() + "/" + userEntity.getAccount()
                                : String.valueOf(value);
                        dataMap.put(vModel, userValue);
                        break;
                    case YunzhupaasKeyConsts.CURRORGANIZE:
                        String currentOrganizeName = serviceUtil.getCurrentOrganizeName(value,
                                swapDataVo.getShowLevel());
                        dataMap.put(vModel, currentOrganizeName);
                        break;
                    case YunzhupaasKeyConsts.COM_INPUT:
                        if (dataMap.get(vModel) != null) {
                            dataMap.put(vModel, String.valueOf(dataMap.get(vModel)));
                        }
                        break;
                    default:
                        dataMap.put(vModel, FormPublicUtils.getDataConversion(value));
                        break;
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            DynamicDataSourceUtil.clearSwitchDataSource();
        }
        return dataMap;
    }

    public static void swapClob(Map<String, Object> map, String key) {
        if (map != null && map.get(key) != null && map.get(key) instanceof Clob) {
            Clob clob = (Clob) map.get(key);
            StringBuilder sb = new StringBuilder();
            // 获取CLOB字段的内容长度
            int length = 0;
            // 以流的形式读取CLOB字段的内容
            try (java.io.Reader reader = clob.getCharacterStream()) {
                length = (int) clob.length();
                char[] buffer = new char[length];
                int bytesRead;
                // 逐个字符读取并添加到字符串构建器中
                while ((bytesRead = reader.read(buffer)) != -1) {
                    sb.append(buffer, 0, bytesRead);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            map.put(key, sb.toString());
        }
    }
}
