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

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.bo.CompanyBo;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.module.jg.api.vo.ElevatorModelVo;
import com.yeejoin.amos.boot.module.jg.biz.service.IIdxBizJgRegisterInfoService;
import com.yeejoin.amos.boot.module.ymt.api.entity.PageParam;
import com.yeejoin.amos.feign.systemctl.model.DictionarieValueModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
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.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;

/**
 * 设备注册
 *
 * @author Provence
 * @version v1.0
 * @date 2023/12/13 14:37
 */
@RestController
@Api(tags = "设备注册Api")
@RequestMapping(value = "/equipment-register")
public class IdxBizJqEquipmentRegisterController extends BaseController {
    @Autowired
    IIdxBizJgRegisterInfoService idxBizJgRegisterInfoService;

    /**
     * 设备注册和更新信息
     *
     * @param paramMap
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/submit")
    @ApiOperation(httpMethod = "POST", value = "设备注册和更新信息", notes = "设备注册和更新信息")
    public ResponseModel<Object> submit(@RequestBody Map<String, Object> paramMap) {
        return ResponseHelper.buildResponse(idxBizJgRegisterInfoService.equipmentRegisterSubmit(paramMap));
    }


    /**
     * 根据recordList批量删除设备注册信息
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/deleteBatch")
    @ApiOperation(httpMethod = "POST", value = "批量删除设备注册信息", notes = "批量删除设备注册信息")
    public ResponseModel<Boolean> deleteByRecordList(@RequestBody Map<String, Object> map) {
        return ResponseHelper.buildResponse(idxBizJgRegisterInfoService.batchDeleteByRecord(map));
    }

    /**
     * 查询设备注册信息详情
     *
     * @param record
     * @return 返回由页签的key包裹详情对象
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/{record}")
    @ApiOperation(httpMethod = "GET", value = "根据record查询设备注册信息详情", notes = "根据record查询设备注册信息详情")
    public ResponseModel<Object> selectOne(@PathVariable String record, @RequestParam(required = false) String isCopy) {
        return ResponseHelper.buildResponse(idxBizJgRegisterInfoService.getEquipmentRegisterByRecord(record, isCopy));
    }


    /**
     * 查询设备注册信息详情
     *
     * @param record
     * @return 只返回详情对象
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/detail")
    @ApiOperation(httpMethod = "GET", value = "根据record查询设备注册信息详情", notes = "根据record查询设备注册信息详情")
    public ResponseModel<Map<String, Object>> getDetail(@RequestParam String record) {
        return ResponseHelper.buildResponse(idxBizJgRegisterInfoService.getDetailByRecord(record));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/detailFieldCamelCase")
    @ApiOperation(httpMethod = "GET", value = "根据record查询设备注册信息详情，返回字段驼峰命名", notes = "根据record查询设备注册信息详情，返回字段驼峰命名")
    public ResponseModel<Map<String, Object>> getDetailFieldCamelCase(@RequestParam String record) {
        return ResponseHelper.buildResponse(idxBizJgRegisterInfoService.getDetailFieldCamelCaseByRecord(record));
    }

    /**
     * 查询设备注册列表
     *
     * @param map
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/page")
    @ApiOperation(httpMethod = "GET", value = "设备注册信息分页查询", notes = "设备注册信息分页查询")
    public ResponseModel<Page<JSONObject>> queryForPage(@RequestParam Map<String, Object> map) {
        JSONObject jsonObject = new JSONObject(map);
        return ResponseHelper.buildResponse(idxBizJgRegisterInfoService.queryForEquipmentRegisterPage(jsonObject));
    }
//    /**
//     * 查询设备注册列表
//     *
//     * @param map
//     * @return
//     */
//    @TycloudOperation(ApiLevel = UserType.AGENCY)
//    @GetMapping(value = "/pageHistory")
//    @ApiOperation(httpMethod = "GET", value = "设备注册信息分页查询", notes = "设备注册信息分页查询")
//    public ResponseModel<Page<JSONObject>> queryForPageHistory(@RequestParam Map<String, Object> map) {
//        JSONObject jsonObject = new JSONObject(map);
//        return ResponseHelper.buildResponse(idxBizJgRegisterInfoService.queryForEquipmentRegisterPageHistory(jsonObject));
//    }
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/category/list")
    @ApiOperation(httpMethod = "GET", value = "查询不同单位类型可新增的设备种类列表", notes = "查询不同单位类型可新增的设备种类列表")
    public ResponseModel<List<DictionarieValueModel>> equCategoryListByCompanyType() {
        return ResponseHelper.buildResponse(idxBizJgRegisterInfoService.equCategoryListByCompanyType(getSelectedOrgInfo(), null, null,null, null));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/equ-category/listByPersonAndEquList")
    @ApiOperation(httpMethod = "GET", value = "按照人员身份、设备种类查询设备类别", notes = "按照人员身份、设备种类查询设备类别")
    public ResponseModel<List<DictionarieValueModel>> equCategoryList(@RequestParam(value = "equList") String equList,
                                                                      @RequestParam(value = "dataSource",required = false) String dataSource,
                                                                      @RequestParam(value = "businessScenarios",required = false) String businessScenarios,
                                                                      @RequestParam(value = "type",required = false) String type) {
        return ResponseHelper.buildResponse(idxBizJgRegisterInfoService.equCategoryListByCompanyType(getSelectedOrgInfo(), equList, businessScenarios,dataSource, type));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/equip/page")
    @ApiOperation(httpMethod = "GET", value = "单位办理设备列表查询", notes = "单位办理设备列表查询")
    public ResponseModel<Page<JSONObject>> queryEquipPage(@RequestParam Map<String, Object> queryMap) {
        JSONObject jsonObject = new JSONObject(queryMap);
        return ResponseHelper.buildResponse(idxBizJgRegisterInfoService.queryForUnitEquipmentPage(jsonObject));
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/equipCanUsedByVessel/page")
    @ApiOperation(httpMethod = "GET", value = "查询车用气瓶可进行选择的设备列表", notes = "查询车用气瓶可进行选择的设备列表")
    public ResponseModel<Page<JSONObject>> queryEquipCanUsedByVesselPage(@RequestParam Map<String, Object> queryMap) {
        JSONObject jsonObject = new JSONObject(queryMap);
        return ResponseHelper.buildResponse(idxBizJgRegisterInfoService.queryEquipCanUsedByVesselPage(jsonObject));
    }
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/equipCanUsedByVessel/pageHistory")
    @ApiOperation(httpMethod = "GET", value = "查询车用气瓶可进行选择的设备列表", notes = "查询车用气瓶可进行选择的设备列表")
    public ResponseModel<Page<JSONObject>> queryEquipCanUsedByVesselPageHistory(@RequestParam Map<String, Object> queryMap) {
        JSONObject jsonObject = new JSONObject(queryMap);
        return ResponseHelper.buildResponse(idxBizJgRegisterInfoService.queryEquipCanUsedByVesselPageHistory(jsonObject));
    }
    /**
     * 压力容器设备批量导入
     */
    @PostMapping("/importPressureVesselData")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "压力容器设备批量导入")
    public ResponseModel<?> importPressureVesselData(@RequestBody Map<String, Object> paramMap,@RequestPart MultipartFile multipartFile) {
        return ResponseHelper.buildResponse(idxBizJgRegisterInfoService.importPressureVesselData(paramMap, multipartFile));
    }

    /**
     *
     * 气瓶批量导入
     * **/
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/importData")
    @ApiOperation(httpMethod = "POST", value = "气瓶批量导入", notes = "气瓶批量导入")
    public ResponseModel<?> importPressureData (@RequestPart("file") MultipartFile multipartFile) throws Exception {
        return ResponseHelper.buildResponse(idxBizJgRegisterInfoService.importPressureData(multipartFile));
    }

    /**
     * 气瓶批量保存
     * **/
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/savePressureVesselData")
    @ApiOperation(httpMethod = "POST", value = "气瓶批量保存", notes = "气瓶批量保存")
    public ResponseModel<?> savePressureVesselData(@RequestBody Map<String, Object> paramMap) {
        return ResponseHelper.buildResponse(idxBizJgRegisterInfoService.savePressureVesselData(paramMap));
    }

    /**
     * 压力容器设备模版下载
     */
    @GetMapping("/pressureVesselTemplate")
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @ApiOperation(value = "压力容器设备模版下载")
    public void pressureVesselTemplate(HttpServletResponse response) throws Exception {
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("压力容器设备导入模版.xlsx", "UTF-8"));
        response.setContentType("application/vnd.ms-excel");
        Resource resource = new ClassPathResource("templates/pressureVesselTemplate.xlsx");
        try (OutputStream outputStream = response.getOutputStream();
             InputStream inputStream = resource.getInputStream()) {
            byte[] bytes = new byte[1024 * 1024];
            int len;
            while ((len = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
            }
        } catch (IOException e) {
            throw new Exception("系统异常");
        }
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getProjectContraption")
    @ApiOperation(httpMethod = "GET", value = "查询当前单位下工程装置信息", notes = "查询当前单位下工程装置信息")
    public ResponseModel<Object> queryEquipCanUsedByVesselPageHistory() {
        ReginParams info = getSelectedOrgInfo();
        CompanyBo companyBo = info.getCompany();
        // 确保公司级别符合要求
        if (!BaseController.COMPANY_TYPE_COMPANY.equals(companyBo.getLevel())) {
            return ResponseHelper.buildResponse(new ArrayList<String>());
        }
        String companyCode = companyBo.getCompanyCode();
        String type = companyBo.getCompanyType();
        // 根据公司类型设置使用和安装改造维修单位代码
        String useUnitCreditCode = type.contains("使用单位") || type.contains("个人主体") ? companyCode : "";
        String uscUnitCreditCode = type.contains("安装改造维修单位") ? companyCode : "";

        return ResponseHelper.buildResponse(
                idxBizJgRegisterInfoService.getProjectContraption(uscUnitCreditCode, useUnitCreditCode)
        );
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/esSynchronousProjectContraption")
    @ApiOperation(httpMethod = "GET", value = "ES历史数据同步工程装置字段值", notes = "ES历史数据同步工程装置字段值")
    public ResponseModel<Object> esSynchronousProjectContraption() {
        return ResponseHelper.buildResponse(idxBizJgRegisterInfoService.esSynchronousProjectContraption());
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/contraption/list")
    @ApiOperation(httpMethod = "GET", value = "查询当前单位下已注册或未注册工程装置信息", notes = "查询当前单位下已注册或未注册工程装置信息")
    public ResponseModel<List<Map<String, Object>>> getProjectContraptionByCondition() {
        String unitCreditCode = getSelectedOrgInfo().getCompany().getCompanyCode();
        return ResponseHelper.buildResponse(idxBizJgRegisterInfoService.getProjectContraptionList(unitCreditCode));
    }

    /**
     * 根据时间范围查询电梯数据
     * @param equCode 设备代码
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 电梯数据
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getElevatorInfo")
    @ApiOperation(httpMethod = "GET", value = "查询电梯信息列表", notes = "查询电梯信息列表")
    public ResponseModel<IPage<Map<String, Object>>> getElevatorInfo(@RequestParam(value = "equCode",required = false) String equCode,
                                                                 @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startTime,
                                                                 @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime,
                                                                 PageParam pageParam) {

        return ResponseHelper.buildResponse(idxBizJgRegisterInfoService.getElevatorInfo(equCode, startTime, endTime, pageParam));
    }

    /**
     * 查询气站信息
     * @return 查询气站信息
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getCylinderStationInfo")
    @ApiOperation(httpMethod = "GET", value = "查询气站信息", notes = "查询气站信息")
    public ResponseModel<List<Map<String, Object>>> getCylinderStationInfo() {
        return ResponseHelper.buildResponse(idxBizJgRegisterInfoService.getCylinderStationInfo());
    }

    /**
     * 车用气气瓶档案
     * @return 车用气气瓶档案
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getVehicleCylinderInfo")
    @ApiOperation(httpMethod = "GET", value = "车用气气瓶档案", notes = "车用气气瓶档案")
    public ResponseModel<List<Map<String, Object>>> getVehicleCylinderInfo(@RequestParam(value = "useCode") String useCode){
        return ResponseHelper.buildResponse(idxBizJgRegisterInfoService.getVehicleCylinderInfo(useCode));
    }

    /**
     * 根据时间范围查询液化石油气瓶档案
     * @param equCode 设备代码
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 电梯数据
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getCylinderInfo")
    @ApiOperation(httpMethod = "GET", value = "根据时间范围查询液化石油气瓶档案", notes = "根据时间范围查询液化石油气瓶档案")
    public ResponseModel<IPage<Map<String, Object>>> getCylinderInfo(@RequestParam(value = "equCode",required = false) String equCode,
                                                                     @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startTime,
                                                                     @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime,
                                                                     PageParam pageParam) {

        return ResponseHelper.buildResponse(idxBizJgRegisterInfoService.getCylinderInfo(equCode, startTime, endTime, pageParam));
    }
}
