package com.yeejoin.amos.boot.module.ugp.biz.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.workflow.feign.WorkflowFeignService;
import com.yeejoin.amos.boot.module.common.biz.service.impl.FailureDetailsServiceImpl;
import com.yeejoin.amos.boot.module.ugp.api.dto.ProblemCodeLibDto;
import com.yeejoin.amos.boot.module.ugp.api.entity.ProblemCodeLib;
import com.yeejoin.amos.boot.module.ugp.api.service.IProblemCodeLibService;
import com.yeejoin.amos.boot.module.ugp.biz.service.impl.ProblemCodeLibServiceImpl;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.ApplicationModel;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.DictionarieValueModel;
import feign.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.exception.BaseException;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@Api(tags = "质量问题代码库表Api")
@RequestMapping(value = "/problemCodeLib")
public class ProblemCodeLibController extends BaseController {

    @Resource
    ProblemCodeLibServiceImpl problemCodeLibServiceImpl;

    @Value("${appCode.pipeline.image:studio_normalapp_3404491,upload/tzs/amos_studio/9C968B74AC9F8C9F21C8E4A284FDEAB4.png}")
    private String pipeAppImage;

    @Value("${appCode.gasBottle.image:studio_normalapp_4403119,upload/tzs/amos_studio/9C968B74AC9F8C9F21C8E4A284FDEAB4.png}")
    private String gasBottleAppImage;

    @Resource
    private IProblemCodeLibService problemCodeLibService;


    @Autowired
    FailureDetailsServiceImpl failureDetailsServiceImpl;

    @Autowired
    WorkflowFeignService workflowFeignService;

    /**
     * 新增质量监检信息表
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/save")
    @ApiOperation(httpMethod = "POST", value = "新增或修改质量问题代码库表", notes = "新增或修改质量问题代码库表")
    public ResponseModel<ProblemCodeLibDto> save(@RequestBody ProblemCodeLibDto model) {
        ProblemCodeLib problemCodeLib = new ProblemCodeLib();
        BeanUtils.copyProperties(model, problemCodeLib, "idxThresholds");
        List<Map<String, String>> idxThresholds = model.getIdxThresholds();
        if (CollectionUtils.isNotEmpty(idxThresholds)) {
            for (Map<String, String> idxThreshold : idxThresholds) {
                idxThreshold.remove("Symbol_key");
            }
            problemCodeLib.setIdxThresholds(JSON.toJSONString(idxThresholds));
        }
        problemCodeLib.setCode(Objects.isNull(problemCodeLib.getSequenceNbr()) ? problemCodeLibServiceImpl.getProblemCode() : problemCodeLib.getCode());
        problemCodeLibService.saveOrUpdate(problemCodeLib);
        model.setSequenceNbr(problemCodeLib.getSequenceNbr());
        return ResponseHelper.buildResponse(model);
    }


    /**
     * 根据sequenceNbr删除
     *
     * @param sequenceNbr 主键
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @DeleteMapping(value = "/{sequenceNbr}")
    @ApiOperation(httpMethod = "DELETE", value = "根据sequenceNbr删除质量问题代码库表", notes = "根据sequenceNbr删除质量问题代码库表")
    public ResponseModel<Boolean> deleteBySequenceNbr(@PathVariable(value = "sequenceNbr") Long sequenceNbr) {
        ProblemCodeLib model = new ProblemCodeLib();
        model.setSequenceNbr(sequenceNbr);
        model.setIsDelete(Boolean.TRUE);
        return ResponseHelper.buildResponse(problemCodeLibService.updateById(model));
    }

    /**
     * 根据sequenceNbr查询
     *
     * @param sequenceNbr 主键
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/{sequenceNbr}")
    @ApiOperation(httpMethod = "GET", value = "根据sequenceNbr查询单个质量问题代码库表", notes = "根据sequenceNbr查询单个质量问题代码库表")
    public ResponseModel<ProblemCodeLibDto> selectOne(@PathVariable Long sequenceNbr) {
        ProblemCodeLib problemCodeLib = problemCodeLibService.getById(sequenceNbr);
        ProblemCodeLibDto problemCodeLibDto = new ProblemCodeLibDto();
        if (StringUtils.isNotEmpty(problemCodeLib.getIdxThresholds())) {
            List<Map<String, String>> listObject = JSON.parseObject(problemCodeLib.getIdxThresholds(), List.class);
            problemCodeLibDto.setIdxThresholds(listObject);
        }
        BeanUtils.copyProperties(problemCodeLib, problemCodeLibDto, "idxThresholds");
        return ResponseHelper.buildResponse(problemCodeLibDto);
    }

    /**
     * 列表分页查询
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/page")
    @ApiOperation(httpMethod = "GET", value = "质量问题代码库表分页查询", notes = "质量问题代码库表分页查询")
    public ResponseModel<IPage<ProblemCodeLib>> queryForPage(@RequestParam(value = "current") int current, @RequestParam
            (value = "size") int size) {
        Page<ProblemCodeLib> page = new Page<>();
        page.setCurrent(current);
        page.setSize(size);
        return ResponseHelper.buildResponse(problemCodeLibServiceImpl.queryProblemCodeInfoPage(page));
    }

    /**
     * 列表全部数据查询
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "质量问题代码库表列表全部数据查询", notes = "质量问题代码库表列表全部数据查询")
    @GetMapping(value = "/list")
    public ResponseModel<List<ProblemCodeLib>> selectForList() {
        return ResponseHelper.buildResponse(problemCodeLibServiceImpl.queryProblemCodeInfoList());
    }

    /**
     * 查询当前登录人的应用信息【燃气管道系统和气瓶安全追溯系统】
     *
     * @return List<Map < String, Object>> 查询当前登录人的应用信息【燃气管道系统和气瓶安全追溯系统】
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "查询当前登录人的应用信息【燃气管道系统和气瓶安全追溯系统】", notes = "查询当前登录人的应用信息【燃气管道系统和气瓶安全追溯系统】")
    @GetMapping(value = "/queryApplyByToken")
    public ResponseModel<Map<String, Object>> queryApplyByToken() {
        String exeUserId = RequestContext.getExeUserId();
        String[] pipeInfo = pipeAppImage.split(",");
        //存放配置文件中取出的应用code和图片信息 key：应用Code  value：图片信息
        Map<String, String> appCodeImageMap = new HashMap<>();
        appCodeImageMap.put(pipeInfo[0], pipeInfo[1]);
        String[] gasBottleInfo = gasBottleAppImage.split(",");
        appCodeImageMap.put(gasBottleInfo[0], gasBottleInfo[1]);
        //存放应用code用于下面过滤
        List<String> list = Arrays.asList(pipeInfo[0], gasBottleInfo[0]);
        AgencyUserModel result = Privilege.agencyUserClient.queryByUserId(exeUserId).getResult();
        Map<String, String> appCodeMap = Privilege.applicationClient.queryAgencyApplications().getResult().stream().filter(t -> list.contains(t.getAppCode())).collect(Collectors.toMap(ApplicationModel::getAppCode, ApplicationModel::getAppName));
        List<Map<String, Object>> resultList = new ArrayList<>();
        result.getAppCodes().stream().filter(list::contains).forEach(item -> {
            Map<String, Object> map = new HashMap<>();
            map.put("appCode", item);
            map.put("appName", appCodeMap.get(item));
            map.put("image", appCodeImageMap.get(item));
            resultList.add(map);
        });
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("current", 1);
        resultMap.put("total", resultList.size());
        resultMap.put("records", resultList);
        return ResponseHelper.buildResponse(resultMap);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getDictDataByCode")
    @ApiOperation(httpMethod = "GET", value = "常用功能", notes = "常用功能")
    public ResponseModel<Object> getDictDataByCode(@RequestParam String dictCode) {
        FeignClientResult<List<DictionarieValueModel>> adminCommonlyUsed = Systemctl.dictionarieClient.dictValues(dictCode);
        List<DictionarieValueModel> result = adminCommonlyUsed.getResult();
        return ResponseHelper.buildResponse(result);
    }

    /**
     * 参考JCS服务流程图信息
     * @param instanceId 流程实例ID
     * @return 流程图
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getInstanceImage")
    @ApiOperation(httpMethod = "GET", value = "流程图高亮图片", notes = "流程图高亮图片")
    public ResponseEntity<String> downloadFile(@RequestParam String instanceId, HttpServletRequest request, HttpServletResponse response) {
        Response feignResponse = workflowFeignService.thighLineImg(instanceId);
        try {
            Response.Body body = feignResponse.body();
            return new ResponseEntity<>(IOUtils.toString(body.asInputStream()),  HttpStatus.OK);
        } catch (Exception e) {
            throw new BaseException("Error exporting diagram", "500", instanceId);
        }

    }
}
