package com.yeejoin.amos.boot.module.tdc.biz.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysql.cj.xdevapi.JsonArray;
import com.yeejoin.amos.boot.module.tdc.api.dto.CheckResultDto;
import com.yeejoin.amos.boot.module.tdc.api.dto.ModelTreeDto;
import com.yeejoin.amos.boot.module.tdc.api.entity.CheckModel;
import com.yeejoin.amos.boot.module.tdc.api.entity.CheckReport;
import com.yeejoin.amos.boot.module.tdc.api.entity.CheckResult;
import com.yeejoin.amos.boot.module.tdc.api.entity.PowerReportFile;
import com.yeejoin.amos.boot.module.tdc.api.enums.WordPowerTypeEum;
import com.yeejoin.amos.boot.module.tdc.api.feign.IdxFeignService;
import com.yeejoin.amos.boot.module.tdc.api.mapper.CheckResultMapper;
import com.yeejoin.amos.boot.module.tdc.api.service.CheckResultService;
import com.yeejoin.amos.boot.module.tdc.api.utils.WordPowerUtils;
import com.yeejoin.amos.boot.module.tdc.api.vo.SubjectTreeVo;
import com.yeejoin.amos.boot.module.tdc.api.vo.TableColumnsVo;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import org.codehaus.jettison.json.JSONString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class CheckResultImpl extends ServiceImpl<CheckResultMapper, CheckResult> implements CheckResultService {

    @Autowired
    CheckResultMapper checkResultMapper;

    @Autowired
    IdxFeignService idxFeignService;


    @Override
    public IPage<CheckResultDto> selectResult(int current,int size,String code) {
        Page page = new Page(current,size);
        return checkResultMapper.selectResult(page,code);

//        return checkResultMapper.selectResult(page,code);
    }


    @Override
    public List<CheckResult> selectCheckResult(String modelId,String amosOrgCode) {
        LambdaQueryWrapper<CheckResult> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CheckResult::getCheckItemResult, "1")
                .eq(CheckResult::getAmosOrgCode, amosOrgCode)
                .eq(CheckResult::getModelId, modelId);
        return baseMapper.selectList(wrapper);
    }

    @Override
    public List<CheckResultDto> selectTotal(String modelId, String amosOrgCode) {
        return checkResultMapper.selectTotal(modelId, amosOrgCode);
    }


    @Override
    public List<ModelTreeDto> test() {
        ResponseModel<List<JSONObject>> listResponseModel = idxFeignService.subjectTree("d2528788-b8d5-4170-ae62-edf153fddc59");
        List<JSONObject> result = listResponseModel.getResult();
        List<ModelTreeDto> modelTreeDtoList = new ArrayList<>();
        result.forEach(obj ->{
            JSONArray tables = (obj).getJSONArray("tables");
            tables.forEach(table -> {
                ModelTreeDto modelTreeDto = new ModelTreeDto();
                SubjectTreeVo subjectTreeVo = JSON.parseObject(JSON.toJSONString(table), SubjectTreeVo.class);
                select(modelTreeDto, subjectTreeVo);
                modelTreeDtoList.add(modelTreeDto);
            });
        });
        return modelTreeDtoList;
    }

    private void select(ModelTreeDto modelTreeDto, SubjectTreeVo subjectTreeVo) {
        modelTreeDto.setId(subjectTreeVo.getTableId());
        modelTreeDto.setName(subjectTreeVo.getTopicName());
        modelTreeDto.setTableName(subjectTreeVo.getTableName());
        List<TableColumnsVo> columns = subjectTreeVo.getColumns();
        Map tableMap = checkResultMapper.getTable(subjectTreeVo.getTableName());
        List<Map<String, Object>> list = new ArrayList<>();
        columns.forEach(tableColumnsVo -> {
            Map<String, Object> map = new HashMap<>(3);
            map.put("name", tableColumnsVo.getName());
            map.put("id", tableColumnsVo.getId());
            map.put("data", tableMap.get(tableColumnsVo.getColumnName()));
            list.add(map);
        });
        modelTreeDto.setChildren(list);
    }

    @Override
    public ModelTreeDto treeTwo(String tableId) {

        ResponseModel<JSONObject> listResponseModel = idxFeignService.queryByTableId(tableId);
        JSONObject result = listResponseModel.getResult();
        ModelTreeDto modelTreeDto = new ModelTreeDto();
        SubjectTreeVo subjectTreeVo = JSON.parseObject(JSON.toJSONString(result), SubjectTreeVo.class);

//        List<TableColumnsVo> list = result.getJSONArray("tableCols").toJavaList(TableColumnsVo.class);
//        subjectTreeVo.setColumns(list);
        select(modelTreeDto, subjectTreeVo);
        return modelTreeDto;

    }

    @Override
    public String select(String amosOrgCode) {
        Map<String, Object> dataMap = getData(amosOrgCode);
        WordPowerUtils instance = WordPowerUtils.getInstance();
        String pdfUrlString = "";
        File filepdf = null;
        try {
            filepdf = instance.getWordFileItem(dataMap, null, WordPowerTypeEum.select.getTemplateFile());
            filepdf.getAbsolutePath();
            MultipartFile multipartFile = new PowerReportFile("file", "file.pdf", "application/pdf", file2byte(filepdf));
            FeignClientResult<Map<String, String>> result = Systemctl.fileStorageClient.updateCommonFile(multipartFile);
            if (result != null) {
                Iterator<String> it = result.getResult().keySet().iterator();
                while (it.hasNext()) {
                    pdfUrlString = it.next();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (filepdf != null) {
                filepdf.delete();
            }
        }

        return pdfUrlString;
    }



    private Map<String,Object> getData(String amosOrgCode) {
        Map<String,Object> map = new HashMap<>();
//        JSONObject map=new JSONObject();
        //3.统计
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        List<CheckResultDto> selectBatch = checkResultMapper.getOne(amosOrgCode);
        for(CheckResultDto checkResultDto1 : selectBatch){
            List<CheckResultDto> systemList = selectStatistion( checkResultDto1.getBatchNo(), amosOrgCode);

            for (CheckResultDto system : systemList) {
                HashMap<String, Object> data = new HashMap<>();
            /*List<Map> collect = (List<Map>) indicatorConfiguration.stream().
                    filter(item -> item.get("code").equals(String.valueOf(system.getAmosOrgCode())));*/
                map.put("station",system.getAmosOrgName());
                data.put("modelName",system.getModelName());
                System.out.println(system.getModelName()+"----------------------------------------------------------------");
                data.put("allTotal",system.getAllTotal());
                data.put("failTotal",system.getFailTotal());
                list.add(data);
            /*for(int i = 0;i<list.size();i++){
                map.put(String.valueOf(i),list.get(i));
            }*/
                map.put("list",list);
            }

            //1.站名
//        List<Map> indicatorConfiguration = JSONObject.parseArray(json, Map.class);

            // 2.时间
            String date = new SimpleDateFormat("yyyy-MM-dd ").format(Calendar.getInstance().getTime());
            map.put("time", date);

            //4.校验明细
            ArrayList<Map<String,Object>> list2 = new ArrayList<>();
            systemList.forEach(checkResultDto -> {
                List<CheckResultDto> systemList2 = selectDetails( checkResultDto.getBatchNo(), checkResultDto.getModelId());

                HashMap<String,Object> object = new HashMap<>();
                ArrayList<Map<String,Object>> maps = new ArrayList<>();
                object.put("modelName", checkResultDto.getModelName());
                for(CheckResultDto system2: systemList2) {
                    //HashMap<String,Object> datas = new HashMap<>();


                    //for(CheckResultDto system3: systemList2){
                    HashMap<String, Object> item = new HashMap<>();
                    item.put("checkitemlabel", system2.getCheckItemLabel());
                    item.put("checkitemvalue", system2.getCheckItemValue());
                    item.put("isright", system2.getIsRight());
                    item.put("checkexplain", system2.getCheckExplain());
                    maps.add(item);
                    //}
                }
                object.put("itemList",maps);
                list2.add(object);
                map.put("list2",list2);

            });
        }
        return map;
    }



    private static byte[] file2byte(File file) {
        try {
            FileInputStream in = new FileInputStream(file);
            byte[] data = new byte[in.available()];
            in.read(data);
            in.close();
            return data;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public List<CheckResultDto> selectStatistion(String batchNo, String amosOrgCode) {
        return checkResultMapper.selectStatistion(batchNo, amosOrgCode);
    }

    @Override
    public List<CheckResultDto> selectDetails(String batchNo, Integer modelId) {
        return checkResultMapper.selectDetails(batchNo, modelId);
    }

}
