package cn.ibizlab.api.rest.extensions;

import cn.ibizlab.core.analysis.domain.DAReport;
import cn.ibizlab.core.analysis.service.impl.DAReportServiceImpl;
import cn.ibizlab.core.dict.domain.DictOption;
import cn.ibizlab.core.dict.service.impl.DictOptionServiceImpl;
import cn.ibizlab.core.extensions.dto.FetchItem;
import cn.ibizlab.core.extensions.dto.FetchParam;
import cn.ibizlab.core.extensions.dto.FetchResult;
import cn.ibizlab.core.extensions.service.BuildResultService;
import cn.ibizlab.core.extensions.service.DACoreService;
import cn.ibizlab.util.errors.BadRequestAlertException;
import cn.ibizlab.util.helper.DataObject;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Lazy;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.sql.Timestamp;
import java.util.List;

@Slf4j
@Api(tags = {"接口" })
@RestController("api-dagridcore")
@RequestMapping("")
public class DAGridCoreResource {

    @Autowired
    private DACoreService daCoreService;
    @Autowired
    @Lazy
    private DAReportServiceImpl daReportService;
    @Autowired
    @Lazy
    private DictOptionServiceImpl dictOptionService;

    @Autowired
    @Lazy
    private DAGridCoreResource proxyService;


    @RequestMapping(method = RequestMethod.POST, value = "/ibizutil/reportdatas")
    public ResponseEntity<JSONObject> getReportdatas(@RequestBody JSONObject data) {
        JSONObject responseJson = new JSONObject();
        String id = data.getString("id");

        String strLoadDimval = StringUtils.isEmpty(data.getString("domin")) ? "%" : data.getString("domin");
        Timestamp strLoadStartTime = StringUtils.isEmpty(data.getString("startTime")) ? daCoreService.getDefaultStartTimestamp() :daCoreService.getTimestamp( data.getString("startTime"));
        Timestamp strLoadEndTime = StringUtils.isEmpty(data.getString("endTime")) ? daCoreService.getDefaultEndTimestamp() : daCoreService.getTimestamp(data.getString("endTime"));
        //获取表头及表单名称
        DAReport daReport = daReportService.getById(id);
        Object vmcfg = JSON.parse(daReport.getConfig());
        String reportname = daReport.getReportName();
        String strDict = "CL_DST_REGION";
        if (daReport != null && !StringUtils.isEmpty(daReport.getDict())) {
            strDict = daReport.getDict();
        }
        //获取表格数据
        JSONObject jsonObject = daCoreService.getERPortData(daReport, strLoadDimval, strDict, strLoadStartTime, strLoadEndTime, "default", "");
        responseJson.put("vmcfg",vmcfg);
        responseJson.put("reportname",reportname);
        responseJson.put("resportdata",jsonObject);
        responseJson.put("dataDict", daReport.getDict());
        return ResponseEntity.ok().body(responseJson);
    }

    @RequestMapping(method = RequestMethod.POST, value = "/ibizutil/getCodelist")
    @Cacheable( value="getCodelist",key = "'getCodelist:'+#p0.getString(\"cid\")")
    public ResponseEntity<JSONArray> getCodelist(@RequestBody JSONObject data) {
        JSONArray result = new JSONArray();
        String cid = data.getString("cid");
        if (StringUtils.isEmpty(cid)){
            log.error("未指定字典项过滤条件");
            return ResponseEntity.ok().body(result);
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("cid",cid);
        queryWrapper.orderByAsc("val");
        List<DictOption> list = dictOptionService.list(queryWrapper);
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = null;
        for (DictOption entity: list) {
            jsonObject = new JSONObject();
            jsonObject.put("id",entity.getValue());
            jsonObject.put("value",entity.getValue());
            jsonObject.put("text",entity.getLabel());
            jsonObject.put("label",entity.getLabel());
            jsonObject.put("parentValue",entity.getParent());
            jsonObject.put("disabled",entity.getDisabled());
            jsonArray.add(jsonObject);
        }
        result = getTrees(jsonArray,"");
        return ResponseEntity.ok().body(result);
    }

    /**
     * 获取代码表指定层级结构；（如：全国代码表，只展示js省市代码值）
     * 参数 :
     *   1.cid：代码表标识
     *   2.optionid：父代码项标识
     * @param data
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/dst/getCodelist")
    public ResponseEntity<JSONArray> getCodelist2(@RequestBody JSONObject data) {
        JSONArray result = new JSONArray();
        String cid = data.getString("cid");
        if (StringUtils.isEmpty(cid)){
            log.error("未传入代码表标识");
            return ResponseEntity.ok().body(result);
        }
        String optionId = data.getString("optionid");
        if (!StringUtils.isEmpty(optionId)){
            return proxyService.getCodelist3(data);
        }
        else{
            return proxyService.getCodelist(data);
        }
    }

    @Cacheable( value="getCodelist",key = "'getCodelist:'+#p0.getString(\"cid\")+'||'+#p0.getString(\"optionid\")")
    public ResponseEntity<JSONArray> getCodelist3(@RequestBody JSONObject data) {
        JSONArray result = new JSONArray();
        String cid = data.getString("cid");
        if (StringUtils.isEmpty(cid)){
            log.error("未指定字典项过滤条件");
            return ResponseEntity.ok().body(result);
        }
        String optionId = data.getString("optionid");
        if (StringUtils.isEmpty(optionId)){
            log.error("未能获取字典项");
            return ResponseEntity.ok().body(result);
        }
        QueryWrapper<DictOption> queryWrapper = new QueryWrapper();
        queryWrapper.eq("cid",cid);
        queryWrapper.and(wrapper -> wrapper.eq("val", optionId).or().likeRight("pval",optionId));
        queryWrapper.orderByAsc("val");
        List<DictOption> list = dictOptionService.list(queryWrapper);
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = null;
        for (DictOption entity: list) {
            jsonObject = new JSONObject();
            jsonObject.put("id",entity.getValue());
            jsonObject.put("value",entity.getValue());
            jsonObject.put("text",entity.getLabel());
            jsonObject.put("label",entity.getLabel());
            jsonObject.put("parentValue",entity.getParent());
            jsonObject.put("disabled",entity.getDisabled());
            jsonArray.add(jsonObject);
        }
        result = getTrees(jsonArray,optionId);
        return ResponseEntity.ok().body(result);
    }



    /**
     * 递归创建树结构数据
     * @param jsonArray
     * @param parentValue
     * @return
     */
    public JSONArray getTrees(JSONArray jsonArray, Object parentValue) {
        JSONArray trees = new JSONArray();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String codeItemParentValue = jsonObject.getString("parentValue");
            if (StringUtils.isEmpty(codeItemParentValue)) {
                codeItemParentValue = "";
            }
            if (parentValue.equals(codeItemParentValue)) {
                JSONArray childCodeItemArray = getTrees(jsonArray, jsonObject.getString("value"));
                if (childCodeItemArray.size() > 0) {
                    jsonObject.put("children",childCodeItemArray);
                }
                trees.add(jsonObject);
            }
        }
        return trees;
    }
}
