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

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.module.common.api.entity.DynamicFormInstance;
import com.yeejoin.amos.boot.module.common.biz.service.impl.DynamicFormInstanceServiceImpl;
import com.yeejoin.amos.boot.module.ys.api.enums.MaintenanceExpiredEarlyWarningEnum;
import com.yeejoin.amos.boot.module.ys.biz.service.impl.CommonServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author system_generator
 * @date 2024-09-24
 */
@RestController
@Api(tags = "维保过期预警分析")
@RequestMapping(value = "/maintenanceEarlyWarningWarning/{equTypeCode}")
public class MaintenanceEarlyWarningController extends BaseController {

    private static final String SXCode = "50";
    private static final HashMap<String, String> unitTypeMap = new HashMap<>();

    @Autowired
    private DynamicFormInstanceServiceImpl dynamicFormInstanceService;

    @Autowired
    private CommonServiceImpl commonService;

    static {
        unitTypeMap.put("useUnit", "使用单位");
    }

    /**
     * 从URL中获取对应的 MaintenanceExpiredEarlyWarningEnum 枚举
     *
     * @param equTypeCode 设备类型代码
     * @return 对应的 MaintenanceExpiredEarlyWarningEnum 枚举
     * @throws BadRequest 如果设备类型代码无效
     */
    public MaintenanceExpiredEarlyWarningEnum getWaringEnumsForPath(String equTypeCode) {
        return MaintenanceExpiredEarlyWarningEnum.getEnum(equTypeCode)
                .orElseThrow(() -> new BadRequest("Invalid equipment type code: " + equTypeCode));
    }


    /**
     * 新增或者更新接口
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/saveOrUpdate")
    @ApiOperation(httpMethod = "POST", value = "新增或者更新接口", notes = "新增或者更新接口")
    public ResponseModel<Object> saveOrUpdate(
            @PathVariable(value = "equTypeCode") String equTypeCode,
            @RequestBody Map<String, Object> model) {
        String groupCode = getWaringEnumsForPath(equTypeCode).getGroupCode();
        String instanceId = (String) model.get("instanceId");
        try {
            // 判断是更新还是新增操作
            if (!ValidationUtil.isEmpty(instanceId)) {
                // 更新操作：先删除再保存
                LambdaQueryWrapper<DynamicFormInstance> lambda =
                        new QueryWrapper<DynamicFormInstance>().lambda();
                lambda.eq(DynamicFormInstance::getInstanceId, instanceId);
                dynamicFormInstanceService.getBaseMapper().delete(lambda);
            }

            // 保存新实例或更新后的实例

            // 兼容附件格式新
            model.keySet().stream()
                    .filter(key -> key.endsWith("file") || key.endsWith("File"))
                    .forEach(key -> model.put(key, JSONObject.toJSONString(model.get(key))));

            dynamicFormInstanceService.commonSave(groupCode, model);
            return ResponseHelper.buildResponse(instanceId != null
                    ? Long.parseLong(instanceId)
                    : Long.MIN_VALUE);
        } catch (Exception e) {
            return ResponseHelper.buildResponse("Error saving or updating instance: " + e.getMessage());
        }
    }


    /**
     * 根据sequenceNbr删除
     *
     * @param instanceId 主键
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @DeleteMapping(value = "/deleteBySeq")
    @ApiOperation(httpMethod = "DELETE", value = "根据instanceId删除", notes = "根据sequenceNbr删除")
    public ResponseModel<Integer> deleteBySeq(@RequestParam(value = "instanceId") String instanceId) {
        LambdaQueryWrapper<DynamicFormInstance> lambda = new QueryWrapper<DynamicFormInstance>().lambda();
        lambda.eq(DynamicFormInstance::getInstanceId, instanceId);
        return ResponseHelper.buildResponse(dynamicFormInstanceService.getBaseMapper().delete(lambda));
    }

    /**
     * 根据sequenceNbr查询
     *
     * @param instanceId 主键
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/detailBySeq")
    @ApiOperation(httpMethod = "GET", value = "根据sequenceNbr查询单个", notes = "根据sequenceNbr查询单个")
    public ResponseModel<Map<String, Object>> detailBySeq(@PathVariable(value = "equTypeCode") String equTypeCode,
                                                          @RequestParam(value = "instanceId") Long instanceId) {
        String groupCode = getWaringEnumsForPath(equTypeCode).getGroupCode();
        Map<String, Object> oneMap = dynamicFormInstanceService.getOneMap(instanceId, groupCode);
        // 兼容附件格式返回
        oneMap.keySet().stream()
                .filter(key -> key.endsWith("file") || key.endsWith("File"))
                .forEach(key -> oneMap.put(key, JSONObject.parseArray((String) oneMap.get(key))));
        return ResponseHelper.buildResponse(oneMap);
    }

    /**
     * 列表分页查询
     *
     * @param current 当前页
     * @param current 每页大小
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/page")
    @ApiOperation(httpMethod = "GET", value = "分页查询", notes = "分页查询")
    public ResponseModel<IPage<Map<String, Object>>> queryForPage(@RequestParam(value = "current") int current,
                                                                  @RequestParam(value = "size") int size,
                                                                  @PathVariable(value = "equTypeCode") String equTypeCode) {
        MaintenanceExpiredEarlyWarningEnum enums = getWaringEnumsForPath(equTypeCode);
        IPage<Map<String, Object>> mapIPage = dynamicFormInstanceService.pageList(current, size, enums.getGroupCode());
        List<Map<String, Object>> records = mapIPage.getRecords();
        List<Map<String, Object>> collect = records.stream().peek(item -> {
            String useCompany = (String) item.get("useCompany");
            String unitType = (String) item.get("unitType");
            if (!ValidationUtil.isEmpty(useCompany)){
                item.put("useCompany", useCompany.split("_")[1]);
            }
            if (!ValidationUtil.isEmpty(unitType)){
                item.put("equType", enums.getTypeName());
            }
            item.put("unitType", unitTypeMap.get(unitType));
        }).collect(Collectors.toList());
        mapIPage.setRecords(collect);
        return ResponseHelper.buildResponse(mapIPage);
    }

    /**
     * 图标统计数量
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/statistics")
    @ApiOperation(httpMethod = "GET", value = "图标统计数量", notes = "图标统计数量")
    public ResponseModel<JSONObject> statistics(@PathVariable(value = "equTypeCode") String equTypeCode) {
        MaintenanceExpiredEarlyWarningEnum enums = getWaringEnumsForPath(equTypeCode);
        // 问题设备数
        long numberOfProblemEqu = dynamicFormInstanceService.pageList(1, 2, enums.getGroupCode()).getTotal();
        // 气瓶总设备数
        long numberOfCylinder = commonService.staticsCenterMapCountDataForCylinder(SXCode);
        // 各类型设备总数
        long totalNumberOfEqu;

        if (enums.getTypeCode().equals("2300")) {
            totalNumberOfEqu = numberOfCylinder;
        } else {
            totalNumberOfEqu = commonService.staticsCenterMapCountDataForEquip(enums.getTypeCode(), numberOfCylinder, SXCode);
        }

        return ResponseHelper.buildResponse(new JSONObject()
                .fluentPut("numberOfProblemEqu", numberOfProblemEqu)
                .fluentPut("totalNumberOfEqu", totalNumberOfEqu));
    }
}
