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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapBuilder;
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.api.dto.BaseEnterpriseCertDto;
import com.yeejoin.amos.boot.module.jyjc.api.dto.InspectionCompanyPublicityDto;
import com.yeejoin.amos.boot.module.jyjc.api.entity.JyjcOpeningApplication;
import com.yeejoin.amos.boot.module.jyjc.api.model.JyjcOpeningApplicationModel;
import com.yeejoin.amos.boot.module.jyjc.api.model.JyjcOpeningApplicationRequstDto;
import com.yeejoin.amos.boot.module.jyjc.biz.config.BaseException;
import com.yeejoin.amos.boot.module.jyjc.biz.service.impl.JyjcOpeningApplicationServiceImpl;
import com.yeejoin.amos.boot.module.ymt.api.dto.TzBaseEnterpriseInfoDto;
import com.yeejoin.amos.boot.module.ymt.api.vo.TzsUserInfoVo;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.RoleModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.context.RequestContext;
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.*;
import java.util.stream.Collectors;

/**
 * @author system_generator
 * @date 2023-12-13
 */
@RestController
@Api(tags = "检验业务申请单api")
@RequestMapping(value = "/jyjc-opening-application")
public class JyjcOpeningApplicationController extends BaseController {

    @Autowired
    JyjcOpeningApplicationServiceImpl jyjcOpeningApplicationServiceImpl;

    /**
     * 新增
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/save")
    @ApiOperation(httpMethod = "POST", value = "新增、编辑的保存", notes = "新增、编辑的保存")
    public ResponseModel<JyjcOpeningApplicationModel> save(@RequestBody JSONObject jsonObject) {
        JyjcOpeningApplicationModel jyjcOpeningApplicationModel = new JyjcOpeningApplicationModel();
        // 兼容工作台暂存逻辑、编辑时报错逻辑
        if (jsonObject.containsKey("applyInfo")) {
            // 工作台暂存逻辑
            BeanUtil.copyProperties(jsonObject.get("applyInfo"), jyjcOpeningApplicationModel);
        } else {
            // 详情保存逻辑
            BeanUtil.copyProperties(jsonObject, jyjcOpeningApplicationModel);
        }
        if (jsonObject.containsKey("buniessInfo") && jsonObject.getJSONObject("buniessInfo") != null) {
            JSONObject businessInfo = jsonObject.getJSONObject("buniessInfo");
            if (businessInfo.containsKey("baseUnitLicences") && businessInfo.get("baseUnitLicences") != null) {
                List<BaseEnterpriseCertDto> baseUnitLicences = businessInfo.getJSONArray("baseUnitLicences")
                        .toJavaList(BaseEnterpriseCertDto.class);
                jyjcOpeningApplicationModel.setBaseUnitLicences(baseUnitLicences);
            }
        }
        return ResponseHelper.buildResponse(jyjcOpeningApplicationServiceImpl.saveOrUpdate(jyjcOpeningApplicationModel, getCompanyCode()));
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PutMapping(value = "/submit")
    @ApiOperation(httpMethod = "PUT", value = "保存并提交、提交", notes = "保存并提交")
    public ResponseModel<List<JyjcOpeningApplicationModel>> updateBySequenceNbrAndStartFlow(@RequestBody JSONObject jsonObject, @RequestParam(value = "sequenceNbr", required = false) Long sequenceNbr) {
        JyjcOpeningApplicationModel model = new JyjcOpeningApplicationModel();
        if (jsonObject.containsKey("applyInfo")) {
            BeanUtil.copyProperties(jsonObject.get("applyInfo"), model);
        } else {
            BeanUtil.copyProperties(jsonObject, model);
        }
        if (jsonObject.containsKey("buniessInfo") && jsonObject.getJSONObject("buniessInfo") != null) {
            JSONObject businessInfo = jsonObject.getJSONObject("buniessInfo"); // 注意拼写修正
            if (businessInfo.containsKey("baseUnitLicences") && businessInfo.get("baseUnitLicences") != null) {
                List<BaseEnterpriseCertDto> baseUnitLicences = businessInfo.getJSONArray("baseUnitLicences")
                        .toJavaList(BaseEnterpriseCertDto.class);
                model.setBaseUnitLicences(baseUnitLicences);
            }
        }
        model.setSequenceNbr(sequenceNbr);
        JyjcOpeningApplicationModel data = jyjcOpeningApplicationServiceImpl.submitApplication(model, getCompanyCode());
        return ResponseHelper.buildResponse(Collections.singletonList(data));
    }


    /**
     * 根据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(jyjcOpeningApplicationServiceImpl.removeById(sequenceNbr));
    }

    /**
     * 根据sequenceNbr删除
     *
     * @param sequenceNbrList 主键列表
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @DeleteMapping(value = "batchDelete")
    @ApiOperation(httpMethod = "DELETE", value = "根据sequenceNbr删除", notes = "根据sequenceNbr删除")
    public ResponseModel<Boolean> deleteBySequenceNbr(@RequestParam(value = "sequenceNbrList") List<Long> sequenceNbrList) {
        return ResponseHelper.buildResponse(jyjcOpeningApplicationServiceImpl.deleteBatchByIds(sequenceNbrList));
    }

    /**
     * 根据sequenceNbr查询
     *
     * @param sequenceNbr 主键
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/detail")
    @ApiOperation(httpMethod = "GET", value = "根据sequenceNbr查询单个", notes = "根据sequenceNbr查询单个")
    public ResponseModel<JyjcOpeningApplicationModel> selectOne(@RequestParam(value = "sequenceNbr", required = false) Long sequenceNbr) {
        return ResponseHelper.buildResponse(jyjcOpeningApplicationServiceImpl.queryDetail(sequenceNbr, getSelectedOrgInfo().getCompany()));
    }

    /**
     * 列表分页查询
     *
     * @param current 当前页
     * @param current 每页大小
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/page")
    @ApiOperation(httpMethod = "POST", value = "分页查询", notes = "分页查询")
    public ResponseModel<Page<JyjcOpeningApplicationModel>> queryForPage(@RequestParam(value = "current") int current,
                                                                         @RequestParam(value = "size") int size,
                                                                         @RequestBody JyjcOpeningApplicationRequstDto jyjcOpeningApplicationRequstDto,
                                                                         @ApiParam(value = "客户端类型: jgAudit-监管审核;jgLook-监管查看") @RequestParam(value = "client", required = false, defaultValue = "jgAudit") String client
    ) {
        Page<JyjcOpeningApplication> page = new Page<JyjcOpeningApplication>();
        page.setCurrent(current);
        page.setSize(size);
        return ResponseHelper.buildResponse(jyjcOpeningApplicationServiceImpl.queryForJyjcOpeningApplicationPage(page, jyjcOpeningApplicationRequstDto,client));
    }

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


    /**
     * 列表全部数据查询
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "流程节点执行", notes = "流程节点执行")
    @PostMapping(value = "/execueFlow")
    public ResponseModel<HashMap<String, String>> executeFlow(@RequestBody Map<String, Object> params) {
        jyjcOpeningApplicationServiceImpl.executeFlow(params);
        HashMap<String, String> result = new HashMap<>();
        result.put("result", "success");
        return ResponseHelper.buildResponse(result);
    }

    /**
     * 列表全部数据查询
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "撤回业务开通申请", notes = "撤回业务开通申请")
    @GetMapping(value = "/rollBackFlow")
    public ResponseModel<Object> overflow(@RequestParam("sequenceNbr") String sequenceNbr,
                                          @RequestParam("instanceId") String instanceId,
                                          @RequestParam("nextTaskId") String nextTaskId) {
        return ResponseHelper.buildResponse(jyjcOpeningApplicationServiceImpl.rollBackFlow(sequenceNbr, instanceId, nextTaskId));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getUserRole")
    @ApiOperation(httpMethod = "GET", value = "获取用户所属组", notes = "获取用户所属组")
    public ResponseModel<List<Long>> getUserRole() {
        AgencyUserModel userModel = Privilege.agencyUserClient.queryByUserId(RequestContext.getExeUserId()).getResult();
        if (userModel == null) {
            throw new BaseException("请先登陆！");
        }
        List<RoleModel> roleModels = userModel.getOrgRoles()
                .values().stream().flatMap(Collection::stream).collect(Collectors.toList());
        List<Long> roleIds = roleModels.stream().map(RoleModel::getSequenceNbr).distinct().collect(Collectors.toList());
        return ResponseHelper.buildResponse(roleIds);
    }

    /**
     * 废弃接口, 已替换成公共接口
     *
     * @param
     * @return {@link  ResponseModel< List< Map< String  Object>>>}
     * @throws
     * @author yangyang
     */
    @Deprecated
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "办理状态枚举列表", notes = "办理状态枚举列表")
    @GetMapping(value = "/flow-status/list")
    public ResponseModel<List<Map<String, Object>>> selectForFlowStatusList() {
        return ResponseHelper.buildResponse(jyjcOpeningApplicationServiceImpl.selectForFlowStatusList());
    }

    /**
     * 查询检验检测机构列表（基本信息及联系人）by 开通机构过滤
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getInspectionUnitList")
    @ApiOperation(httpMethod = "GET", value = "查询检验检测机构列表（基本信息及联系人）", notes = "查询检验检测机构列表（基本信息及联系人）by 开通机构过滤")
    public ResponseModel<List<TzBaseEnterpriseInfoDto>> getInspectionUnitList() {
        return ResponseHelper.buildResponse(jyjcOpeningApplicationServiceImpl.getInspectionUnitList());
    }

    /**
     * 作废
     *
     * @param
     * @return {@link  ResponseModel< List< TzBaseEnterpriseInfoDto>>}
     * @throws
     * @author yangyang
     * @date 2023/12/22 16:13
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PutMapping(value = "/discard")
    @ApiOperation(httpMethod = "PUT", value = "作废", notes = "作废")
    public ResponseModel<Boolean> doDiscard(@RequestBody Map<String, Object> params) {
        String sequenceNbr = (String) params.get("sequenceNbr");
        String remark = (String) params.get("remark");
        return ResponseHelper.buildResponse(jyjcOpeningApplicationServiceImpl.doDiscard(Long.parseLong(sequenceNbr), remark));
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/unit/list")
    @ApiOperation(httpMethod = "GET", value = "查询指定设备所在地的检测机构", notes = "查询指定设备所在地的检测机构")
    public ResponseModel<List<TzBaseEnterpriseInfoDto>> getUnitListByRecord(@RequestParam String record) {
        return ResponseHelper.buildResponse(jyjcOpeningApplicationServiceImpl.getUnitListByRecord(record));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/user-list")
    @ApiOperation(httpMethod = "GET", value = "查询指定公司、指定人员类型的人员列表,默认当前登录人所在公司", notes = "查询指定公司、指定人员类型的人员列表,默认当前登录人所在公司")
    public ResponseModel<List<TzsUserInfoVo>> getBizUserInfosByUnitCode(@ApiParam(value = "公司编码") @RequestParam(required = false) String unitCode, @ApiParam(value = "人员类型", allowableValues = "jy,jc") @RequestParam String personType) {
        if (StringUtils.isEmpty(unitCode)) {
            ReginParams reginParams = getSelectedOrgInfo();
            unitCode = reginParams.getCompany().getCompanyCode();
        }
        return ResponseHelper.buildResponse(jyjcOpeningApplicationServiceImpl.getUserListByUnitCodeAndPost(unitCode, personType));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/v2/users")
    @ApiOperation(httpMethod = "GET", value = "查询当前登录人、指定人员类型的人员map结构", notes = "查询当前登录人、指定人员类型的人员map结构，key为jyjcUserInfos代表检验检测人员，chargeUserInfos为检验检测区域负责人")
    public ResponseModel<Map<String, List<TzsUserInfoVo>>> getBizUserInfosByUnitCodeV2(@ApiParam(value = "人员类型", allowableValues = "jy,jc,charge", defaultValue = "jy,jc,charge") @RequestParam(required = false, defaultValue = "jy,jc,charge") String personType) {
        return ResponseHelper.buildResponse(jyjcOpeningApplicationServiceImpl.getUserListByUnitCodeAndPostV2(getCompanyCode(), personType));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/user-map")
    @ApiOperation(httpMethod = "GET", value = "查询指定公司、指定人员类型的人员列表,默认当前登录人所在公司，map", notes = "查询指定公司、指定人员类型的人员列表,默认当前登录人所在公司，map")
    public ResponseModel<Map<String, List<TzsUserInfoVo>>> getBizUserInfosByUnitCodeMap(@ApiParam(value = "公司编码") @RequestParam(required = false) String unitCode,
                                                                                        @ApiParam(value = "人员类型", allowableValues = "jy,jc") @RequestParam String personType) {
        if (StringUtils.isEmpty(unitCode)) {
            ReginParams reginParams = getSelectedOrgInfo();
            unitCode = reginParams.getCompany().getCompanyCode();
        }
        // 前端表单特殊结构封装 ，key有用不能更换
        Map<String, List<TzsUserInfoVo>> result = new HashMap<>();
        result.put("userInfos", jyjcOpeningApplicationServiceImpl.getUserListByUnitCodeAndPost(unitCode, personType));
        return ResponseHelper.buildResponse(result);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "检验检测机构公示", notes = "检验检测机构公示")
    @PostMapping(value = "/inspectionOrgList/publicity")
    public ResponseModel<List<InspectionCompanyPublicityDto>> inspectionOrgListForPublicity() {
        return ResponseHelper.buildResponse(jyjcOpeningApplicationServiceImpl.queryInspectionOrgListForBiz());
    }


    /**
     * 检验业务开通列表导出
     *
     * @param response
     * @param ids
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/exportdata")
    @ApiOperation(httpMethod = "GET", value = "检验业务开通列表导出", notes = "检验业务开通列表导出")
    public void dataExport(HttpServletResponse response, String ids) {
        if (StringUtils.isEmpty(ids)) {
            throw new BadRequest("请选择需要导出的数据！");
        }
        jyjcOpeningApplicationServiceImpl.exportData(response, Arrays.asList(ids.split(",")));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getAppId")
    @ApiOperation(httpMethod = "GET", value = "获取appId", notes = "获取appId")
    public ResponseModel<Map<String, String>> getAppId(@RequestParam(value = "relationId") Long seq) {
        String appId = jyjcOpeningApplicationServiceImpl.getAppIdBySeq(seq);
        return ResponseHelper.buildResponse(MapBuilder.<String, String>create().put("appId", appId).build());
    }
}
