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


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
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.api.model.JyjcInspectionResultModel;
import com.yeejoin.amos.boot.module.jyjc.biz.config.BaseException;
import com.yeejoin.amos.boot.module.jyjc.biz.service.impl.JyjcInspectionApplicationServiceImpl;
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.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 java.util.*;

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

    @Autowired
    JyjcInspectionApplicationServiceImpl jyjcInspectionApplicationServiceImpl;

	// 业务通用发起——基本信息
	private static final String basic = "basic";
	// 业务通用发起——设备信息
	private static final String equipPageInfo = "equipPageInfo";
	// 业务通用发起——技术参数-
	private static final String filePageData = "filePageData";

    /**
     * 新增
     *
     * @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(equipPageInfo);
			Map<String, Object> filePageDataObj = (Map<String, Object>) model.get(filePageData);
			finallyJson.putAll(model);
			finallyJson.putAll(basicObj);
			finallyJson.putAll(equipPageInfoObj);
			finallyJson.putAll(filePageDataObj);
			model = finallyJson;
		}
		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)));
    }


	/**
     * 根据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));
    }

    /**
     * 列表分页查询
     *
     * @param current 当前页
     * @param current 每页大小
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/pageByInstitution")
    @ApiOperation(httpMethod = "GET", value = "分页查询（检验机构）", notes = "分页查询（检验机构）")
    public ResponseModel<Page<JyjcInspectionApplicationModel>> queryForPageByInstitution(@RequestParam(value = "current") int current,
                                                                                         @RequestParam(value = "size") int size,
                                                                                         @RequestParam(required = false) String applicationNo,
                                                                                         @RequestParam(required = false) String inspectionClassify,
                                                                                         @RequestParam(required = false) String applicationUnitCode,
                                                                                         @RequestParam(required = false) String applicationUnitName,
                                                                                         @RequestParam(required = false) String inspectionUnitName,
                                                                                         @RequestParam(required = false) String equipClassify,
                                                                                         @RequestParam(required = false) String inspectionUnitCode,
                                                                                         @RequestParam(required = false) String applicationDate,
                                                                                         @RequestParam(required = false) String acceptDate,
                                                                                         @RequestParam(required = false) String inspectionChargePerson,
                                                                                         @RequestParam(required = false) String status,
                                                                                         @RequestParam(required = false) String roles, String bizType) {
        Page<JyjcInspectionApplication> page = new Page<JyjcInspectionApplication>();
        page.setCurrent(current);
        page.setSize(size);

        ReginParams reginParams = getSelectedOrgInfo();
        inspectionUnitCode = reginParams.getCompany().getCompanyCode();
        List<String> roleIds = StrUtil.split(roles, ",");

        return ResponseHelper.buildResponse(jyjcInspectionApplicationServiceImpl.queryForJyjcInspectionApplicationPage(page, applicationNo, inspectionClassify, applicationUnitCode, equipClassify, inspectionUnitCode, applicationUnitName, inspectionUnitName, applicationDate, acceptDate, inspectionChargePerson, status, bizType));
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/pageByCompany")
    @ApiOperation(httpMethod = "GET", value = "分页查询（报检单位）", notes = "分页查询（报检单位）")
    public ResponseModel<Page<JyjcInspectionApplicationModel>> queryForPageByCompany(@RequestParam(value = "current") int current,
                                                                                     @RequestParam (value = "size") int size,
                                                                                     @RequestParam(required = false) String applicationNo,
                                                                                     @RequestParam(required = false) String inspectionClassify,
                                                                                     @RequestParam(required = false) String applicationUnitCode,
                                                                                     @RequestParam(required = false) String equipClassify,
                                                                                     @RequestParam(required = false) String inspectionUnitCode,
                                                                                     @RequestParam(required = false) String applicationUnitName,
                                                                                     @RequestParam(required = false) String inspectionUnitName,
                                                                                     @RequestParam(required = false) String applicationDate,
                                                                                     @RequestParam(required = false) String acceptDate,
                                                                                     @RequestParam(required = false) String inspectionChargePerson,
                                                                                     @RequestParam(required = false) String roles,
                                                                                     @RequestParam(required = false) String status, String bizType) {
        Page<JyjcInspectionApplication> page = new Page<JyjcInspectionApplication>();
        page.setCurrent(current);
        page.setSize(size);
        ReginParams reginParams = getSelectedOrgInfo();
        applicationUnitCode = reginParams.getCompany().getCompanyCode();
        List<String> roleIds = StrUtil.split(roles, ",");
//			return ResponseHelper.buildResponse(jyjcInspectionApplicationServiceImpl.queryForJyjcInspectionApplicationPage(page,applicationNo,inspectionClassify,applicationUnitCode,equipClassify,inspectionUnitCode,applicationUnitName,inspectionUnitName,applicationDate,acceptDate,inspectionChargePerson,status,bizType,roleIds));
        return ResponseHelper.buildResponse(jyjcInspectionApplicationServiceImpl.queryForJyjcInspectionApplicationPage(page, applicationNo, inspectionClassify, applicationUnitCode, equipClassify, inspectionUnitCode, applicationUnitName, inspectionUnitName, applicationDate, acceptDate, inspectionChargePerson, status, bizType));

    }


    @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<HashMap<String, String>> execueFlow(@PathVariable(value = "type") String type, @RequestBody Map<String, Object> params) {
        params.put("type", type);
        try {
            jyjcInspectionApplicationServiceImpl.doReceive(params);
        } catch (Exception e) {
            return CommonResponseUtil.failure("该项流程发生变化，请返回列表刷新查看状态后重试");
        }
        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 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) {
        return ResponseHelper.buildResponse(jyjcInspectionApplicationServiceImpl.doRollback(sequenceNbr));
    }

    /**
     * 查询指定设备种类的设备列表
     *
     * @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));
    }
}
