package com.chinaweal.aiccs.aiccs.system.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chinaweal.aiccs.aiccs.abnormal.entity.EBaseinfo;
import com.chinaweal.aiccs.aiccs.abnormal.service.EBaseinfoService;
import com.chinaweal.aiccs.aiccs.revoke.Vo.DisableListVo;
import com.chinaweal.aiccs.aiccs.system.entity.TRBaseCode;
import com.chinaweal.aiccs.aiccs.system.service.TRBaseCodeService;
import com.chinaweal.aiccs.common.base.controller.BaseController;
import com.chinaweal.aiccs.common.constant.FileParamModelConstant;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.crgs.system.entity.TDataTypeCode;
import com.chinaweal.aiccs.crgs.system.service.TDataTypeCodeService;
import com.chinaweal.youfool.framework.springboot.exception.custom.BusinessException;
import com.chinaweal.youfool.framework.springboot.rest.RestResult;
import com.chinaweal.youfool.framework.springboot.rest.ResultCode;
import com.chinaweal.youfool.framework.springboot.util.AssertUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 获取常量的Controller
 * @author <a href="https://blog.lroyia.top">lroyia</a>
 * @since 2021/2/19 9:24
 **/
@Api("常量接口")
@Slf4j
@RestController
@RequestMapping("constant")
public class ConstantController extends BaseController {

    @Autowired
    private TRBaseCodeService baseCodeService;
    @Autowired
    private EBaseinfoService eBaseinfoService;
    @Autowired
    private TDataTypeCodeService tDataTypeCodeService;

    /**
     * 通过codeId获取基础数据列表
     * @param codeId codeId
     * @return 获取结果
     * @author lroyia
     * @since 2021年2月19日 09:27:09
     */
    @ApiOperation("常量获取接口")
    @GetMapping("/{codeId}")
    public RestResult<?> getBaseCodeByCodeId(@ApiParam("常量分类编码id") @PathVariable String codeId){
        return RestResult.ok(baseCodeService.getBaseCodeListFromCache(codeId));
    }

    /**
     * 获取最新CD73 严重违法列入原因
     * @return 获取结果
     */
    @ApiOperation("最新CD73原因获取接口")
    @GetMapping("/getNewBaseCodeOfIllegal")
    public RestResult<?> getNewBaseCodeOfIllegal(){
        QueryWrapper<TRBaseCode> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(TRBaseCode::getCodeid,"CD73").eq(TRBaseCode::getIsgb,"1").orderByAsc(TRBaseCode::getCode);
        List<TRBaseCode> list = baseCodeService.list(wrapper);
        if(list.size() > 0){
            return RestResult.ok(JSON.parseArray(JSON.toJSONString(list), TRBaseCode.class));
        }
        return RestResult.error(ResultCode.DATA_NONE);
    }
    /**
     * excel文件查询参数解析
     * @param file 文件
     * @return 查询结果
     * @author lroyia
     * @since 2021年3月19日 18:27:19
     */
    @ApiOperation("excel文件查询参数解析")
    @PostMapping("fileParamExplain")
    public RestResult<?> fileParamExplain(@ApiParam("上传的excel文件") MultipartFile file, @ApiParam("参数模型名称") String model){
        AssertUtils.isNotNull(file);
        AssertUtils.isNotBlank(model);
        Map<String, String> modelMap = FileParamModelConstant.getModel(model);
        if(modelMap == null){
            throw new BusinessException("登录超时，请重新登录");
        }
        String fileName = file.getOriginalFilename();
        String ext = fileName.substring(fileName.lastIndexOf("."));
        Workbook book;
        try(InputStream is = file.getInputStream()){
            if(ext.equals(".xls")){
                book = new HSSFWorkbook(is);
            }else{
                book = new XSSFWorkbook(is);
            }
        }catch (IOException e) {
            log.error("上传查询参数文件错误", e);
            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR);
        }
        Sheet sheet = book.getSheetAt(0);
        // 读取文件头，获取参数名
        Row header = sheet.getRow(0);
        List<String> headerNames = new ArrayList<>();
        for(int i = 0; i < header.getLastCellNum();i++){
            headerNames.add(header.getCell(i).getStringCellValue());
        }
        List<Map<String, String>> result = new ArrayList<>();
        for(int i = 1; i <= sheet.getLastRowNum(); i++){
            Row curRow = sheet.getRow(i);
            Map<String, String> atom = new HashMap<>();
            for(int j = 0; j < headerNames.size() && j < curRow.getLastCellNum(); j++){
                String headerName = headerNames.get(j);
                String key = modelMap.get(headerName);
                if(StringUtils.isBlank(key)) continue;
                Cell cell = curRow.getCell(j);
                if(cell == null) continue;
                String stringCellValue = cell.getStringCellValue();
                if(StringUtils.isNotBlank(stringCellValue)){
                    atom.put(key, stringCellValue.trim());
                }
            }
            if(MapUtils.isNotEmpty(atom)){
                result.add(atom);
            }
        }
        ArrayList<EBaseinfo> enableList = new ArrayList<>();//可导
        ArrayList<DisableListVo> disableList = new ArrayList<>();//不可导
        for (Map<String, String> map : result) {
            QueryWrapper<EBaseinfo> wrapper = new QueryWrapper<>();
            EBaseinfo baseinfoModel = new EBaseinfo();
            baseinfoModel.setUniscid(map.get("uniscid"));
            baseinfoModel.setRegno(map.get("regno"));
            baseinfoModel.setEntname(map.get("entname"));

            wrapper.lambda().eq(StringUtils.isNotBlank(baseinfoModel.getUniscid()),EBaseinfo::getUniscid,baseinfoModel.getUniscid())
                    .eq(StringUtils.isNotBlank(baseinfoModel.getRegno()),EBaseinfo::getRegno,baseinfoModel.getRegno())
                    .eq(StringUtils.isNotBlank(baseinfoModel.getEntname()),EBaseinfo::getEntname,baseinfoModel.getEntname());
//                    .eq(EBaseinfo::getRegstate, "1");// 1为在营状态 要改
            EBaseinfo eBaseinfo = eBaseinfoService.getOne(wrapper);

            if(eBaseinfo != null){
                if("1".equals(eBaseinfo.getRegstate())){
                    enableList.add(eBaseinfo);
                }else {
                    DisableListVo disableListVo = new DisableListVo();
                    disableListVo.setEntname(eBaseinfo.getEntname());
                    disableListVo.setUniscid(eBaseinfo.getUniscid());
                    disableListVo.setRegno(eBaseinfo.getUniscid());
                    disableListVo.setReason(eBaseinfo.getRegstateCn());
                    disableList.add(disableListVo);
                }

            }else {
                DisableListVo disableListVo = new DisableListVo();
                disableListVo.setEntname(baseinfoModel.getEntname());
                disableListVo.setUniscid(baseinfoModel.getUniscid());
                disableListVo.setRegno(baseinfoModel.getRegno());
                disableListVo.setReason("主体信息有误");
                disableList.add(disableListVo);
            }
        }
        HashMap<String, Object> groupMap = new HashMap<>();
        groupMap.put("enableList",enableList);
        groupMap.put("disableList",disableList);

        return RestResult.ok(groupMap);
    }

    /**
     * 获取crgs的t_data_type表的常量
     * @return  获取结果
     * @author lroyia
     * @since 2021年4月8日 13:51:11
     */
    @ApiOperation("获取crgs的t_data_type表的常量")
    @GetMapping("getDataType/{type}")
    public RestResult<?> getDataTypeList(@ApiParam("类型") @PathVariable String type){
        Map<String, TDataTypeCode> cache = tDataTypeCodeService.getDataTypeMapFormCache(type, false);
        if(MapUtils.isNotEmpty(cache)){
            return RestResult.ok(cache.values());
        }
        return OK;
    }

    @GetMapping("getCD72")
    public RestResult<?> getCD72(){
        List<TRBaseCode> trBaseCodes = baseCodeService.getBaseCodeListFromCache("CD72");
        List<TRBaseCode> rs = new ArrayList<>();
        for(TRBaseCode trBaseCode : trBaseCodes){
            if(!trBaseCode.getCode().equals("6") && !trBaseCode.getCode().equals("7")){
                rs.add(trBaseCode);
            }
        }
        return RestResult.ok(rs);
    }

    @ApiOperation("获取常用语模块常量")
    @GetMapping("getCYY")
    public RestResult<?> getCYY(){
        List<TRBaseCode> list = new ArrayList<>();
        List<TRBaseCode> trBaseCodes = baseCodeService.getBaseCodeListFromCache("CYY");
        if(CollectionUtils.isNotEmpty(trBaseCodes)){
            list = trBaseCodes;
        }
        return RestResult.ok(list);
    }

    /**
     * 市监部门常量获取接口
     * @return 获取结果
     */
    @ApiOperation("市监常量获取接口")
    @GetMapping("getAllDepts")
    public RestResult<?> getAllDepts(){
        QueryWrapper<TRBaseCode> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(TRBaseCode::getCodeid,"CA11")
                .likeRight(TRBaseCode::getCode,"15")
                .orderByAsc(TRBaseCode::getCode);
        List<TRBaseCode> list = baseCodeService.list(wrapper);
        if(list.size() > 0){
            return RestResult.ok(list);
        }
        return RestResult.error(ResultCode.DATA_NONE);
    }

    @ApiOperation(value = "根据codeId获取基础数据")
    @PostMapping("/list")
    public RestResult<List<TRBaseCode>> listXrbasecode(@RequestBody TRBaseCode query) {
        List<TRBaseCode> data = baseCodeService.listXrbasecodes(query);
        return RestResult.ok(data);
    }
}
