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

import cn.hutool.core.bean.BeanUtil;
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.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.foundation.utils.ValidationUtil;
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.*;
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 model) {
        JyjcOpeningApplicationModel jyjcOpeningApplicationModel = new JyjcOpeningApplicationModel();
        // 兼容工作台暂存逻辑、编辑时报错逻辑
        if (model.containsKey("applyInfo")) {
            // 工作台暂存逻辑
            BeanUtil.copyProperties(model.get("applyInfo"), jyjcOpeningApplicationModel);
        } else {
            // 详情保存逻辑
            BeanUtil.copyProperties(model, jyjcOpeningApplicationModel);
        }
        return ResponseHelper.buildResponse(jyjcOpeningApplicationServiceImpl.saveOrUpdate(jyjcOpeningApplicationModel));
    }


    @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);
        }
        model.setSequenceNbr(sequenceNbr);
        if (sequenceNbr != null) {
            JyjcOpeningApplicationModel jyjcOpeningApplicationModel = jyjcOpeningApplicationServiceImpl.queryDetail(sequenceNbr);
            if (jyjcOpeningApplicationModel == null || ValidationUtil.isEmpty(jyjcOpeningApplicationModel.getBaseUnitLicences()) || ValidationUtil.isEmpty(jyjcOpeningApplicationModel.getUserInfos())) {
                throw new BadRequest("企业资质信息和检验人员信息为空，无法提交！");
            }
        }
        JyjcOpeningApplicationModel data = jyjcOpeningApplicationServiceImpl.submitApplication(model);
        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));
    }

    /**
     * 列表分页查询
     *
     * @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) {
        Page<JyjcOpeningApplication> page = new Page<JyjcOpeningApplication>();
        page.setCurrent(current);
        page.setSize(size);
        return ResponseHelper.buildResponse(jyjcOpeningApplicationServiceImpl.queryForJyjcOpeningApplicationPage(page, jyjcOpeningApplicationRequstDto));
    }

    /**
     * 列表全部数据查询
     *
     * @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>> execueFlow(@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.stopFlow(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 = "/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());
    }

}
