package com.dk.mdm.service.common;

import com.dk.common.infrastructure.config.ApplicationContextUtil;
import com.dk.common.infrastructure.constant.Constant;
import com.dk.common.model.pojo.PageList;
import com.dk.common.response.ResponseResultUtil;
import com.dk.common.response.ResponseResultVO;
import com.dk.common.util.ExcelPoiUtils;
import com.dk.mdm.config.MesProxy;
import com.dk.mdm.mapper.core.JobMapper;
import com.dk.mdm.mapper.core.PostMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author : 周兴
 * @desc : 控件数据源API
 * @date : 2023/1/3 17:21
 */
@Service
@Slf4j
public class ExportService {

    @Autowired
    private JobMapper jobMapper;

    @Autowired
    private PostMapper postMapper;

    @Autowired
    private SqlSession sqlSession;

    /**
     * @desc : 导出excel
     * @author : 周兴
     * @date : 2023/2/22 15:13
     */
//    public void exportList(HttpServletResponse response, Map<String, Object> param,Map<String, Object> condition) {
    public ResponseResultVO<String> exportList(Map<String, Object> param) {
        Map<String, Object> condition = (Map<String, Object>) param.get("condition");
        Constant.FunUuidConstant constant = Constant.FunUuidConstant.get(param.get("name").toString());
        String title = param.get("title").toString();
        // 分页参数赋值
        if(param.get("pageSize") != null){
            param = this.getLimit(param);
        }
        List list = null;
        try {
            Class interfz = Class.forName(constant.getInterfz());
            Object instance = Proxy.newProxyInstance(interfz.getClassLoader(),new Class[]{interfz} ,new MesProxy(sqlSession.getMapper(interfz)));
            Method selectMethod;
            // 查询条件是map
            if(constant.getMapFlag() != null){
                selectMethod = instance.getClass().getDeclaredMethod(constant.getMethod(),Map.class);
            }else{
                selectMethod = instance.getClass().getDeclaredMethod(constant.getMethod(),Object.class);
            }
            list = (List)selectMethod.invoke(instance,param);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (list != null && list.size() > 0) {
            // 处理数据
            List<Map<String, Object>> mapList = filterExportColumns(condition, list);
            String fileName = UUID.randomUUID().toString();
            String path = ExcelPoiUtils.createExcel(mapList,
                    fileName + "_" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss")) + ".xlsx",
                    title, param.get("name").toString());
            return ResponseResultUtil.success(path);
        }
        return ResponseResultUtil.success("");
    }

    /**
     * @desc : 把list转成List<Map>，根据前台的传入的列进行过滤
     * @author : 周兴
     * @date : 2023/2/22 15:27
     */
    private List<Map<String, Object>> filterExportColumns(Map<String, Object> param, List list) {
        List<Map<String, Object>> mapList = new ArrayList<>();
        list.forEach(it -> {
            Map<String, Object> map = new LinkedHashMap<>();
            Set<String> mapKeys = param.keySet();
            for (String key : mapKeys) {
                map.put(param.get(key).toString(), getFieldValueByName(key, it));
            }
//            for (int i = 0; i < fields.length; i++) {
//                if (param.containsKey(fields[i].getName())) {
//                    map.put(param.get(fields[i].getName()).toString(), getFieldValueByName(fields[i].getName(), it));
//                }
//            }
            mapList.add(map);
        });
        return mapList;
    }

    /**
     * @desc : 获取实体值
     * @author : 周兴
     * @date : 2023/2/22 15:46
     */
    private Object getFieldValueByName(String fieldName, Object o) {
        try {
            Object value;
            if (o instanceof Map) {
                value = ((Map<?, ?>) o).get(fieldName);
            } else {
                String firstLetter = fieldName.substring(0, 1).toUpperCase();
                String getter = "get" + firstLetter + fieldName.substring(1);
                Method method = o.getClass().getMethod(getter, new Class[]{});
                value = method.invoke(o, new Object[]{});
            }
            return value;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * @desc : 设置分页参数
     * @author : 姜宁
     * @date : 2023/2/1 14:00
     */
    private Map<String, Object> getLimit(Map<String, Object> param) {
        if (param.get("limit") != null) {
            param.put("currentPage", 1);
            param.put("pageSize", param.get("limit"));
        }
        param.put("start", ((int) param.get("currentPage") - 1) * (int) param.get("pageSize"));
        param.put("end", param.get("pageSize"));
        return param;
    }
}
