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


import com.alibaba.fastjson.JSONObject;
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.biz.utils.CommonResponseUtil;
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.JyjcInspectionApplicationServiceImpl;
import com.yeejoin.amos.boot.module.ymt.api.dto.TzBaseEnterpriseInfoDto;
import com.yeejoin.amos.feign.systemctl.model.DictionarieModel;
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.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

    @Autowired
    private JyjcInspectionApplicationServiceImpl jyjcInspectionApplicationServiceImpl;

    /**
     * 业务通用发起——基本信息
     */
    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 = "新增")
    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", selectedOrgInfo.getCompany().getCompanyCode());

        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,
                                                                                @RequestBody JyjcInspectionApplicationModel model) {
        Page<JyjcInspectionApplication> page = new Page<JyjcInspectionApplication>();
        page.setCurrent(current);
        page.setSize(size);

        return ResponseHelper.buildResponse(jyjcInspectionApplicationServiceImpl.queryForPageList(page, model));

    }

    /**
     * 列表全部数据查询
     *
     * @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")
    public ResponseModel executeFlow(@PathVariable(value = "type") String type, @RequestBody Map<String, Object> params) {
        params.put("type", type);
        jyjcInspectionApplicationServiceImpl.doReceive(params);
        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")
    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")
    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")
    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")
    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<JSONObject>> getEquipListWithOutFlowing(@RequestParam Map<String, Object> map) {
        JSONObject jsonObject = new JSONObject(map);
        return ResponseHelper.buildResponse(jyjcInspectionApplicationServiceImpl.queryForEquipmentRegisterPage(jsonObject));
    }

    /**
     * 查询检验检测机构列表（基本信息及联系人）-工作台专用
     *
     * @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));
    }
}
