package com.yeejoin.amos.boot.module.jyjc.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.ReginParams;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.module.common.api.dto.ContraptionQueryParams;
import com.yeejoin.amos.boot.module.common.biz.utils.CommonResponseUtil;
import com.yeejoin.amos.boot.module.jyjc.api.dto.InspectMockAppData;
import com.yeejoin.amos.boot.module.jyjc.api.entity.JyjcInspectionApplication;
import com.yeejoin.amos.boot.module.jyjc.api.model.JyjcInspectionApplicationEquipModel;
import com.yeejoin.amos.boot.module.jyjc.api.model.JyjcInspectionApplicationModel;
import com.yeejoin.amos.boot.module.jyjc.biz.event.InspectionApplicationPushEvent;
import com.yeejoin.amos.boot.module.jyjc.biz.event.publisher.EventPublisher;
import com.yeejoin.amos.boot.module.jyjc.biz.service.impl.CommonServiceImpl;
import com.yeejoin.amos.boot.module.jyjc.biz.service.impl.InspectAppMockServiceImpl;
import com.yeejoin.amos.boot.module.jyjc.biz.service.impl.JyjcInspectionApplicationServiceImpl;
import com.yeejoin.amos.boot.module.ymt.api.dto.TzBaseEnterpriseInfoDto;
import com.yeejoin.amos.boot.module.ymt.api.entity.IdxBizJgProjectContraption;
import com.yeejoin.amos.feign.systemctl.model.DictionarieModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.component.event.RestEventTrigger;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author system_generator
 * @date 2023-12-14
 */
@RestController
@Api(tags = "报检申请Api")
@RequestMapping(value = "/jyjc-inspection-application")
@Slf4j
public class JyjcInspectionApplicationController extends BaseController {

    @Autowired
    private JyjcInspectionApplicationServiceImpl jyjcInspectionApplicationServiceImpl;

    @Autowired
    private InspectAppMockServiceImpl inspectAppMockServiceImpl;

    /**
     * 业务通用发起——基本信息
     */
    private static final String BASIC = "basic";

    /**
     * 业务通用发起——设备信息
     */
    private static final String EQUIP_PAGE_INFO = "equipPageInfo";

    /**
     * 业务通用发起——技术参数
     */
    private static final String FILE_PAGE_DATA = "filePageData";

    @Autowired
    private EventPublisher eventPublisher;

    /**
     * 新增
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/save")
    @ApiOperation(httpMethod = "POST", value = "报检申请-暂存、提交", notes = "新增")
    @RestEventTrigger(value = "operateLogRestEventHandler")
    public ResponseModel<List<JyjcInspectionApplicationModel>> save(@RequestBody JSONObject model) {
        if (model.containsKey(BASIC)) {
            JSONObject finallyJson = new JSONObject();
            Map<String, Object> basicObj = (Map<String, Object>) model.get(BASIC);
            Map<String, Object> equipPageInfoObj = (Map<String, Object>) model.get(EQUIP_PAGE_INFO);
            Map<String, Object> filePageDataObj = (Map<String, Object>) model.get(FILE_PAGE_DATA);
            finallyJson.putAll(model);
            finallyJson.putAll(basicObj);
            finallyJson.putAll(equipPageInfoObj);
            finallyJson.putAll(filePageDataObj);
            model = finallyJson;
        }
        // operationType: 1-暂存 0-提交
        ReginParams selectedOrgInfo = getSelectedOrgInfo();
        model.put("applicationUnitCode", CommonServiceImpl.getUnitCode(getSelectedOrgInfo().getCompany()));

        if (model.get("operationType").toString().equals("2") || model.get("operationType").toString().equals("0")) {

            if (null == model.get("equip") || model.getJSONArray("equip").size() < 1) {
                return CommonResponseUtil.failure("未选择报检设备时不可提交");
            }
        }
        return ResponseHelper.buildResponse(Collections.singletonList(jyjcInspectionApplicationServiceImpl.save(model, selectedOrgInfo)));
    }


    /**
     * 根据sequenceNbr删除
     *
     * @param sequenceNbr 主键
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @DeleteMapping(value = "/{sequenceNbr}")
    @ApiOperation(httpMethod = "DELETE", value = "根据sequenceNbr删除", notes = "根据sequenceNbr删除")
    public ResponseModel<Boolean> deleteBySequenceNbr(HttpServletRequest request, @PathVariable(value = "sequenceNbr") Long sequenceNbr) {
        return ResponseHelper.buildResponse(jyjcInspectionApplicationServiceImpl.removeById(sequenceNbr));
    }


    /**
     * 根据sequenceNbr删除
     *
     * @param sequenceNbr 主键
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @DeleteMapping(value = "/deleteBatch")
    @ApiOperation(httpMethod = "DELETE", value = "批量删除", notes = "批量删除")
    public ResponseModel<Boolean> deleteBySequenceNbr(HttpServletRequest request, @RequestParam List<Long> sequenceNbr) {

        return ResponseHelper.buildResponse(jyjcInspectionApplicationServiceImpl.deleteBatchData(sequenceNbr));
    }

    /**
     * 根据sequenceNbr查询
     *
     * @param sequenceNbr 主键
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/{sequenceNbr}")
    @ApiOperation(httpMethod = "GET", value = "根据sequenceNbr查询单个", notes = "根据sequenceNbr查询单个")
    public ResponseModel<Map<String, Object>> selectOne(@PathVariable Long sequenceNbr) {
        return ResponseHelper.buildResponse(jyjcInspectionApplicationServiceImpl.selectBySeq(sequenceNbr, getSelectedOrgInfo().getCompany().getCompanyType()));
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/pageList")
    @ApiOperation(httpMethod = "POST", value = "分页列表页面(检验检测单位、使用单位共用）", notes = "分页列表页面(检验检测单位、使用单位共用）")
    public ResponseModel<Page<JyjcInspectionApplicationModel>> queryForPageList(@RequestParam(value = "current") int current,
                                                                                @RequestParam(value = "size") int size,
                                                                                @RequestParam(value = "sort", required = false) String sort,
                                                                                @RequestBody JyjcInspectionApplicationModel model,
                                                                                @ApiParam(value = "客户端类型: jgAudit-监管审核;jgLook-监管查看") @RequestParam(value = "client", required = false, defaultValue = "jgAudit") String client
    ) {
        Page<JyjcInspectionApplication> page = new Page<>();
        page.setCurrent(current);
        page.setSize(size);
        return ResponseHelper.buildResponse(jyjcInspectionApplicationServiceImpl.queryForPageList(page, model, sort, client));
    }

    /**
     * 列表全部数据查询
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "列表全部数据查询", notes = "列表全部数据查询")
    @GetMapping(value = "/list")
    public ResponseModel<List<JyjcInspectionApplicationModel>> selectForList() {
        return ResponseHelper.buildResponse(jyjcInspectionApplicationServiceImpl.queryForJyjcInspectionApplicationList());
    }

    /**
     * 接收接口
     *
     * @param params params
     * @return {@link  ResponseModel< HashMap< String  String>>}
     * @throws
     * @author yangyang
     * @date 2023/12/15 11:25
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "报检申请-接收", notes = "接收")
    @PostMapping(value = "/flow/{type}/receive")
    @RestEventTrigger(value = "operateLogRestEventHandler")
    public ResponseModel<?> executeFlow(@PathVariable(value = "type") String type, @RequestBody Map<String, Object> params) {
        params.put("type", type);
        jyjcInspectionApplicationServiceImpl.doReceive(params, getSelectedOrgInfo());
        HashMap<String, String> result = new HashMap<>();
        result.put("result", "success");
        return ResponseHelper.buildResponse(result);
    }

    /**
     * 退回接口（监督检验、定（首）检、检测）-通用
     *
     * @param params params
     * @return {@link }
     * @throws
     * @author yangyang
     * @date 2023/12/15 13:44
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "报检申请-退回", notes = "退回")
    @PostMapping(value = "/flow/reject")
    @RestEventTrigger(value = "operateLogRestEventHandler")
    public ResponseModel<Boolean> doRejectFlow(@RequestBody Map<String, Object> params) {
        return ResponseHelper.buildResponse(jyjcInspectionApplicationServiceImpl.doReject(params));
    }

    /**
     * 不予受理接口（监督检验、定（首）检、检测）-通用
     *
     * @param params params
     * @return {@link }
     * @author shg
     * @date 2023/12/15 13:44
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "报检申请-不予受理", notes = "不予受理")
    @PostMapping(value = "/flow/noAccept")
    @RestEventTrigger(value = "operateLogRestEventHandler")
    public ResponseModel<Boolean> doNoAcceptFlow(@RequestBody Map<String, Object> params) {
        return ResponseHelper.buildResponse(jyjcInspectionApplicationServiceImpl.doNoAccept(params));
    }

    /**
     * 撤回接口（监督检验、定（首）检、检测）-通用
     *
     * @param sequenceNbr sequenceNbr
     * @return {@link }
     * @throws
     * @author yangyang
     * @date 2023/12/15 13:39
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "报检申请-撤回", notes = "撤回")
    @GetMapping(value = "/flow/rollback")
    @RestEventTrigger(value = "operateLogRestEventHandler")
    public ResponseModel<Boolean> doRollbackFlow(@RequestParam("sequenceNbr") String sequenceNbr,
                                                 @RequestParam("instanceId") String instanceId,
                                                 @RequestParam("nextTaskId") String nextTaskId) {
        return ResponseHelper.buildResponse(jyjcInspectionApplicationServiceImpl.doRollback(sequenceNbr, instanceId, nextTaskId));
    }

    /**
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "查询指定设备种类的设备列表", notes = "查询指定设备种类的设备列表")
    @GetMapping(value = "/listByCategory")
    public ResponseModel<Page<JyjcInspectionApplicationEquipModel>> listByCategory(
            @RequestParam("current") int current,
            @RequestParam("size") int size,
            @RequestParam("equipClassify") String equipClassify) {
        Page<JyjcInspectionApplicationEquipModel> page = new Page<>();
        page.setCurrent(current);
        page.setSize(size);
        return ResponseHelper.buildResponse(jyjcInspectionApplicationServiceImpl.listByCategory(page, equipClassify));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "报检信息手工推送至kafka", notes = "报检信息手工推送至kafka,预留")
    @GetMapping(value = "/data-push")
    @Transactional
    public void pushTest(
            @RequestParam("id") Long id) {
        JyjcInspectionApplicationModel model = jyjcInspectionApplicationServiceImpl.queryBySeq(id);
        InspectionApplicationPushEvent event = new InspectionApplicationPushEvent(this, model);
        eventPublisher.publish(event);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "设备注册信息分页查询", notes = "设备注册信息分页查询")
    @GetMapping(value = "/equip/list")
    public ResponseModel<Page<?>> getEquipListWithOutFlowing(@RequestParam Map<String, Object> map) {
        JSONObject jsonObject = new JSONObject(map);
        return ResponseHelper.buildResponse(jyjcInspectionApplicationServiceImpl.queryForEquipmentRegisterPageDispatch(jsonObject));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "设备注册信息分页查询-所有设备-使用单位检验结果录入过滤设备使用", notes = "设备注册信息分页查询-所有设备-使用单位检验结果录入过滤设备使用")
    @GetMapping(value = "/equip/all")
    public ResponseModel<Page<JSONObject>> getAllEquipList(@RequestParam Map<String, Object> map) {
        JSONObject jsonObject = new JSONObject(map);
        return ResponseHelper.buildResponse(jyjcInspectionApplicationServiceImpl.getAllEquipListPage(jsonObject));
    }

    /**
     * 查询单位下的所有工程装置（父ID为空）的数据
     *
     * @param useUnitCreditCode 使用单位统一信用代码
     * @param current           当前页
     * @param size              每页数
     * @return page
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/jgAllProConPage")
    @ApiOperation(value = "查询单位下的所有工程装置（父ID为空）的数据")
    public ResponseModel<IPage<IdxBizJgProjectContraption>> getJgAllProConPage(@RequestParam(value = "useUnitCreditCode") String useUnitCreditCode,
                                                                               @RequestParam(value = "projectContraption", required = false) String projectContraption,
                                                                               @RequestParam(value = "current") int current,
                                                                               @RequestParam(value = "size") int size) {
        Page<IdxBizJgProjectContraption> page = new Page<>();
        page.setCurrent(current);
        page.setSize(size);
        IPage<IdxBizJgProjectContraption> re = jyjcInspectionApplicationServiceImpl.getJgAllProConPage(useUnitCreditCode, projectContraption, page);
        return ResponseHelper.buildResponse(re);
    }

    /**
     * 查询检验检测机构列表（基本信息及联系人）-工作台专用
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/workbench/getInspectionUnitList")
    @ApiOperation(httpMethod = "GET", value = "查询检验检测机构列表所有已注册开通的", notes = "查询检验检测机构列表所有已注册开通的")
    public ResponseModel<List<TzBaseEnterpriseInfoDto>> getInspectionUnitListForWorkbench(@RequestParam String openBizType) {
        return ResponseHelper.buildResponse(jyjcInspectionApplicationServiceImpl.getInspectionUnitListForWorkbench(openBizType));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "检验类型-按照业务查询", notes = "检验类型-按照业务查询")
    @GetMapping(value = "/{bizType}/inspectType/list")
    public ResponseModel<List<DictionarieModel>> inspectTypeListByBizType(@PathVariable String bizType) {
        return ResponseHelper.buildResponse(jyjcInspectionApplicationServiceImpl.inspectTypeListByBizType(bizType));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/{bizType}/export")
    @ApiOperation(httpMethod = "GET", value = "定（首）检验列表（企业）/电梯检测/监督检验 列表数据导出", notes = "定（首）检验列表（企业）/电梯检测/监督检验 列表数据导出")
    public void export(@PathVariable(value = "bizType") String bizType, HttpServletResponse response, String ids) {
        Assert.hasText(ids, "未选择导出数据");
        jyjcInspectionApplicationServiceImpl.export(bizType, response, Arrays.asList(ids.split(",")));
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/projectContraptionPage")
    @ApiOperation(value = "按照检验类型查询可进行检验的装置", notes = "不包括流程中的")
    public ResponseModel<IPage<IdxBizJgProjectContraption>> getJgProjectContraptionPage(ContraptionQueryParams queryParams,
                                                                                        @RequestParam(value = "current") int current,
                                                                                        @RequestParam(value = "size") int size) {
        ReginParams selectedOrgInfo = getSelectedOrgInfo();
        Page<IdxBizJgProjectContraption> page = new Page<>();
        page.setCurrent(current);
        page.setSize(size);
        IPage<IdxBizJgProjectContraption> re = jyjcInspectionApplicationServiceImpl.getJgProjectContraptionPage(queryParams, page, selectedOrgInfo.getCompany().getCompanyCode());
        return ResponseHelper.buildResponse(re);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "查询指定工程装置下的管道及安装信息", notes = "查询指定工程装置下的管道及安装信息")
    @GetMapping(value = "/getDeviceListByProjectContraptionSeq")
    public ResponseModel<Object> getDeviceListByProjectContraption(@RequestParam("record") String projectContraptionSeq) {
        return ResponseHelper.buildResponse(jyjcInspectionApplicationServiceImpl.getDeviceListByProjectContraption(projectContraptionSeq));
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getRegion")
    @ApiOperation(httpMethod = "GET", value = "获取行政区划", notes = "获取行政区划")
    public ResponseModel<Object> getRegion(@RequestParam(value = "level", required = false) String level,
                                           @RequestParam(value = "parentId", required = false) String parentId) {
        return ResponseHelper.buildResponse(jyjcInspectionApplicationServiceImpl.getRegion(level, parentId));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PutMapping(value = "/file/test")
    @ApiOperation(httpMethod = "PUT", value = "报检申请表测试", notes = "报检申请表测试")
    public ResponseModel<Object> fileTest(String appSeq) {
        return ResponseHelper.buildResponse(jyjcInspectionApplicationServiceImpl.genDocPath(appSeq));
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/pageList2")
    @ApiOperation(httpMethod = "POST", value = "检验业务查询-分页列表页面(检验检测单位、监管审核）", notes = "检验业务查询-分页列表页面(检验检测单位、监管审核共用）")
    public ResponseModel<Page<JyjcInspectionApplicationModel>> queryForPageList2(@RequestParam(value = "current") int current,
                                                                                 @RequestParam(value = "size") int size,
                                                                                 @RequestParam(value = "sort", required = false) String sort,
                                                                                 @RequestBody JyjcInspectionApplicationModel model
    ) {
        Page<JyjcInspectionApplication> page = new Page<>();
        page.setCurrent(current);
        page.setSize(size);
        return ResponseHelper.buildResponse(jyjcInspectionApplicationServiceImpl.queryForPageList2(page, model, sort));
    }

    /**
     * 模拟报检接口
     *
     * @param appData 测试数据
     * @return 是否成功
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "PUT", value = "模拟报检接口", notes = "模拟报检接口,联调使用，模拟用户的报检接收")
    @PutMapping(value = "/test-push")
    public ResponseModel<Boolean> testAppAndPassApp(@Validated @RequestBody InspectMockAppData appData, BindingResult bindingResult) {
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        if (!fieldErrors.isEmpty()) {
            throw new BadRequest(fieldErrors.get(0).getDefaultMessage());
        }
        log.info("模拟报检接口请求的数据内容：{}", JSONObject.toJSONString(appData));
        return ResponseHelper.buildResponse(inspectAppMockServiceImpl.testAppAndPassApp(appData));
    }
}
