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

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
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.jg.api.dto.JgChangeRegistrationUnitDto;
import com.yeejoin.amos.boot.module.jg.api.entity.JgChangeRegistrationUnit;
import com.yeejoin.amos.boot.module.jg.biz.service.impl.JgChangeRegistrationUnitServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
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.HttpServletResponse;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 单位变更登记
 *
 * @author system_generator
 * @date 2023-12-22
 */
@RestController
@Api(tags = "单位变更登记Api")
@RequestMapping(value = "/jg-change-registration-unit")
public class JgChangeRegistrationUnitController extends BaseController {

    @Autowired
    JgChangeRegistrationUnitServiceImpl jgChangeRegistrationUnitServiceImpl;

    /**
     * 新增
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/save")
    @ApiOperation(httpMethod = "POST", value = "新增单位变更", notes = "新增单位变更")
    public ResponseModel<String> save(@RequestParam String submitType, @RequestBody JSONObject model) {
        ReginParams reginParams = getSelectedOrgInfo();
        jgChangeRegistrationUnitServiceImpl.saveNotice(submitType, model, reginParams);
        return ResponseHelper.buildResponse("");
    }

    /**
     * 根据sequenceNbr更新
     *
     * @param model 单位变更
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PutMapping(value = "/update")
    @ApiOperation(httpMethod = "PUT", value = "根据sequenceNbr更新单位变更", notes = "根据sequenceNbr更新单位变更")
    public ResponseModel<JgChangeRegistrationUnitDto> updateBySequenceNbrJgInstallationNotice(@RequestParam String submitType, @RequestBody Map<String, Object> model, @RequestParam(value = "op", required = false) String op) {
        JgChangeRegistrationUnitDto jgChangeRegistrationUnitDto = BeanUtil.mapToBean(((LinkedHashMap) model.get("changeRegisInfo")), JgChangeRegistrationUnitDto.class, true);
        if (Objects.isNull(jgChangeRegistrationUnitDto)) {
            throw new IllegalArgumentException("参数installationInfo不能为空");
        }
        Object o = ((LinkedHashMap<?, ?>) model.get("changeRegisInfo")).get("changeCertificateList");
        jgChangeRegistrationUnitDto.setChangeCertificateList((List<Map<String, Object>>) o);
        ReginParams reginParams = getSelectedOrgInfo();

        return ResponseHelper.buildResponse(jgChangeRegistrationUnitServiceImpl.updateInstallationNotice(submitType, jgChangeRegistrationUnitDto, op, reginParams));
    }

    /**
     * 根据sequenceNbr删除
     *
     * @param sequenceNbr 主键
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @DeleteMapping(value = "/delete")
    @ApiOperation(httpMethod = "DELETE", value = "根据sequenceNbr删除单位变更", notes = "根据sequenceNbr删除单位变更")
    public ResponseModel<Boolean> deleteBySequenceNbr(@RequestParam(value = "sequenceNbr") Long sequenceNbr) {
        jgChangeRegistrationUnitServiceImpl.deleteForBatch(new Long[]{sequenceNbr});
        return ResponseHelper.buildResponse(Boolean.TRUE);
    }

    /**
     * 根据sequenceNbr批量删除
     *
     * @param sequenceNbrs 主键
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @DeleteMapping(value = "/batchDelete")
    @ApiOperation(value = "根据sequenceNbr删除维保合同备案", notes = "根据sequenceNbr删除维保合同备案")
    public ResponseModel<Boolean> deleteForBatch(@RequestParam("sequenceNbrs") Long[] sequenceNbrs) {
        try {
            return ResponseHelper.buildResponse(jgChangeRegistrationUnitServiceImpl.deleteForBatch(sequenceNbrs));
        } catch (Exception e) {
            return CommonResponseUtil.failure(e.getMessage());
        }
    }

    /**
     * 根据sequenceNbr查询
     *
     * @param sequenceNbr 主键
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/details")
    @ApiOperation(httpMethod = "GET", value = "根据sequenceNbr查询单个单位变更", notes = "根据sequenceNbr查询单个单位变更")
    public ResponseModel<Map<String, Map<String, Object>>> selectOne(@RequestParam("sequenceNbr") Long sequenceNbr) {
        return ResponseHelper.buildResponse(jgChangeRegistrationUnitServiceImpl.queryBySequenceNbr(sequenceNbr, getSelectedOrgInfo()));
    }

    /**
     * 根据sequenceNbr查询详情
     *
     * @param sequenceNbr 主键
     * @return ResponseModel
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/projectContraption/details")
    @ApiOperation(httpMethod = "GET", value = "根据sequenceNbr查询单个管道工程装置表", notes = "根据sequenceNbr查询单个管道工程装置表")
    public ResponseModel<Map<String, Map<String, Object>>> detailsByProjectContraption(@RequestParam("sequenceNbr") String sequenceNbr,
                                                                                       @RequestParam("applyNo")String applyNo) {
        return ResponseHelper.buildResponse(jgChangeRegistrationUnitServiceImpl.detailsByProjectContraption(sequenceNbr,applyNo));
    }

    /**
     * 列表分页查询
     *
     * @param current 当前页
     * @param current 每页大小
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/page")
    @ApiOperation(httpMethod = "POST", value = "单位变更分页查询", notes = "单位变更分页查询")
    public ResponseModel<Page<JgChangeRegistrationUnitDto>> queryForPage(
            @ApiParam(value = "当前页码", required = true) @RequestParam(value = "current", defaultValue = "1") int current,
            @ApiParam(value = "每页大小", required = true) @RequestParam(value = "size", defaultValue = "20") int size,
            @ApiParam(value = "类型：enterprise-企业端、supervision-监管端", required = true) @RequestParam(value = "type", defaultValue = "enterprise") String type,
            @ApiParam(value = "排序字段", required = false) @RequestParam(value = "sort", required = false) String sort,
            @RequestBody(required = false) JgChangeRegistrationUnitDto model,
            @ApiParam(value = "客户端类型: jgAudit-监管审核;jgLook-监管查看") @RequestParam(value = "client", required = false, defaultValue = "jgAudit") String client
    ) {
        Page<JgChangeRegistrationUnit> page = new Page<>(current, size);
        ReginParams reginParams = getSelectedOrgInfo();
        if (reginParams.getCompany().getLevel().equals(BaseController.COMPANY_TYPE_COMPANY)) {
            type = "enterprise";
        } else {
            type = "supervision";
        }
        type = "jgLook".equals(client) ? null : type;
        String orgCode = "jgLook".equals(client) ? reginParams.getCompany().getOrgCode() : null;
        return ResponseHelper.buildResponse(jgChangeRegistrationUnitServiceImpl.queryForJgChangeRegistrationUnitPage(page, sort, model, type, reginParams, orgCode));
    }

    /**
     * 撤销
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/cancel")
    @ApiOperation(httpMethod = "POST", value = "单位变更撤销", notes = "单位变更撤销")
    public ResponseModel<JgChangeRegistrationUnitDto> cancel(@RequestBody Map<String, Object> model) {
        JgChangeRegistrationUnitDto installationInfo = BeanUtil.mapToBean(((LinkedHashMap) model.get("changeRegisInfo")), JgChangeRegistrationUnitDto.class, true);
        if (Objects.isNull(installationInfo)) {
            throw new IllegalArgumentException("参数installationInfo不能为空");
        }
        jgChangeRegistrationUnitServiceImpl.cancel(installationInfo);
        return ResponseHelper.buildResponse(installationInfo);
    }

    /**
     * 受理
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/accept")
    @ApiOperation(httpMethod = "POST", value = "单位变更受理", notes = "单位变更受理")
    public ResponseModel<JgChangeRegistrationUnitDto> accept(@RequestBody Map<String, Object> model, String op) {
        // TODO 受理单位变更流程
        LinkedHashMap model1 = (LinkedHashMap) model.get("changeRegisInfo");
        String opinion = (String) model.get("opinion");
        LinkedHashMap installationInfo = (LinkedHashMap) model1.get("changeRegisInfo");
        List<String> newCarNumberList = (List<String>) model.get("newCarNumberList");
        if (newCarNumberList != null && !newCarNumberList.isEmpty()) {
            installationInfo.put("registrationList", newCarNumberList);
        }
        JgChangeRegistrationUnitDto changeRegistrationUnitDto = JSON.parseObject(JSON.toJSONString(installationInfo), JgChangeRegistrationUnitDto.class);
        changeRegistrationUnitDto.setProcessAdvice(opinion);
        jgChangeRegistrationUnitServiceImpl.accept(changeRegistrationUnitDto, op);
        return ResponseHelper.buildResponse(null);
    }


    /**
     * 导出使用登记证
     *
     * @param response    返回
     * @param sequenceNbr 主键
     * @param printType   打印类型，0-正常打印，1-套打（默认0）
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/export")
    @ApiOperation(httpMethod = "GET", value = "导出使用登记证", notes = "导出使用登记证")
    public void exportImageZip(HttpServletResponse response, @RequestParam("sequenceNbr") String sequenceNbr,
                               @RequestParam(value = "printType", defaultValue = "0") String printType) {
        jgChangeRegistrationUnitServiceImpl.exportUseRegistrationCertificate(sequenceNbr, response, printType);
    }

    /**
     * bug24304脏数据处理（单位变更登记 注销 一勾选过多，部分变更设备失败，现在将变更失败的设备变更过去）
     *
     * @param applyNos 单位变更 / 注销 的申请编号
     * @return result
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/bug24304")
    @ApiOperation(httpMethod = "GET", value = "bug24304脏数据处理（单位变更登记 注销 一勾选过多，部分变更设备失败，现在将变更失败的设备变更过去）",
            notes = "bug24304脏数据处理（单位变更登记 注销 一勾选过多，部分变更设备失败，现在将变更失败的设备变更过去")
    public ResponseModel<String> bug24304(@RequestParam(value = "businessType", defaultValue = "1")
                                          @ApiParam(value = "业务类型 ， 单位变更 =》 1,   注销 =》 2,   默认值为单位变更") String businessType,
                                          @RequestParam(value = "applyNos")
                                          @ApiParam(value = "单位变更/注销业务的申请编号,多个用逗号分隔") String applyNos) {
        jgChangeRegistrationUnitServiceImpl.bug24304Handle(businessType, applyNos);
        return ResponseHelper.buildResponse(businessType.equals("1") ? "单位变更" : "注销" + "业务，" + "申请单号：" + applyNos + "数据修改成功");
    }

    /**
     * 处理单位变更流程结束，业务未结束单子问题
     * @param applyNo 申请单号
     * @return s
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/handleChangeRegistrationUnitWrongData")
    @ApiOperation(httpMethod = "POST", value = "处理单位变更流程结束，业务未结束单子问题", notes = "处理单位变更流程结束，业务未结束单子问题")
    public ResponseModel<Object> handleChangeRegistrationUnitWrongData(@RequestParam("applyNo") String applyNo) {
        jgChangeRegistrationUnitServiceImpl.handleChangeRegistrationUnitWrongData(applyNo);
        return ResponseHelper.buildResponse("ok");
    }

}
