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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.bo.CompanyBo;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.entity.DataDictionary;
import com.yeejoin.amos.boot.biz.common.excel.ExcelUtil;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.common.api.dto.UserPermissionDto;
import com.yeejoin.amos.boot.module.tcm.api.dto.GroupAndPersonInfoDto;
import com.yeejoin.amos.boot.module.tcm.api.dto.TzIndividualityDto;
import com.yeejoin.amos.boot.module.tcm.api.dto.TzsEquipListDto;
import com.yeejoin.amos.boot.module.tcm.api.dto.TzsUserInfoDto;
import com.yeejoin.amos.boot.module.tcm.api.entity.TzsUserInfo;
import com.yeejoin.amos.boot.module.tcm.api.service.ITzsUserInfoService;
import com.yeejoin.amos.boot.module.tcm.api.vo.JGUserInfoVo;
import com.yeejoin.amos.boot.module.tcm.biz.service.impl.TzsUserInfoServiceImpl;
import com.yeejoin.amos.component.feign.utils.FeignUtil;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.DictionarieValueModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
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.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
@Api(tags = "用户信息Api")
@RequestMapping(value = "/userInfo")
public class TzsUserInfoController extends BaseController {

    @Autowired
    private TzsUserInfoServiceImpl tzsUserInfoServiceImpl;

    @Autowired
    private ITzsUserInfoService tzsUserInfoService;

    @Autowired
    RedisUtils redisUtils;

    private static final String REGULATOR_UNIT_TREE = "REGULATOR_UNIT_TREE";

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/save")
    @ApiOperation(httpMethod = "POST", value = "新增人员信息", notes = "新增人员信息")
    public ResponseModel<TzsUserInfoDto> save(@RequestBody JSONObject map) {
        Map<String, Object> userInfo = (Map<String, Object>) map.get("userInfo");
        TzsUserInfoDto tzsUserInfo = JSON.parseObject(JSON.toJSONString(userInfo), TzsUserInfoDto.class);
        TzsUserInfoDto userInfoDto = tzsUserInfoServiceImpl.saveUserInfo(tzsUserInfo);
        return ResponseHelper.buildResponse(userInfoDto);
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/update")
    @ApiOperation(httpMethod = "POST", value = "修改人员信息", notes = "修改人员信息")
    public ResponseModel<TzsUserInfoDto> update(@RequestBody JSONObject map,
                                                @RequestParam Long rowId) {
        Map<String, Object> userInfo = (Map<String, Object>) map.get("userInfo");
        TzsUserInfoDto tzsUserInfoDto = JSON.parseObject(JSON.toJSONString(userInfo), TzsUserInfoDto.class);
        TzsUserInfoDto userInfoDto = tzsUserInfoServiceImpl.updateUserInfo(rowId, tzsUserInfoDto);
        return ResponseHelper.buildResponse(userInfoDto);
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/deleteBatch")
    @ApiOperation(httpMethod = "POST", value = "批量删除", notes = "批量删除")
    public ResponseModel<Object> deleteBatch(@RequestBody JSONObject map) {
//        ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
//        if (ObjectUtils.isEmpty(reginParams)) {
//            return null;
//        }
//        TzsUserInfo tzsUserInfo = tzsUserInfoMapper.selectOne(new QueryWrapper<TzsUserInfo>().eq("amos_user_id", reginParams.getUserModel().getUserId()));
        Object[] ids = ((List<Long>) map.get("ids")).toArray();
//        Boolean flag = false;
//        for (Object id : ids) {
//            if (id.equals(tzsUserInfo.getSequenceNbr().toString())) {
//                flag = true;
//                break;
//            }
//        }
//        if (flag) {
//            throw new BadRequest("不能删除当前登录人所对应的数据，请取消勾选后再做删除处理");
//        }
        tzsUserInfoService.deleteBatch(ids);
        return ResponseHelper.buildResponse("ok");
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getDetail")
    @ApiOperation(httpMethod = "GET", value = "详情", notes = "详情")
    public ResponseModel<Map<String, Object>> queryForPage(@RequestParam(value = "id") Long id) {
        return ResponseHelper.buildResponse(tzsUserInfoService.getDetail(id, getSelectedOrgInfo()));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/page")
    @ApiOperation(httpMethod = "GET", value = "人员信息列表", notes = "人员信息列表")
    public ResponseModel<IPage<TzsUserInfoDto>> queryForPage(@RequestParam(value = "current") String current,
                                                             @RequestParam(value = "size") String size,
                                                             @RequestParam(value = "sort", required = false) String sort,
                                                             @RequestParam Map<String, Object> map) {
        TzsUserInfoDto dto = JSON.parseObject(JSON.toJSONString(map), TzsUserInfoDto.class);
        ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        if (ObjectUtils.isEmpty(reginParams)) {
            return null;
        }
        CompanyBo company = reginParams.getCompany();
        if (ObjectUtils.isEmpty(company)) {
            throw new BadRequest("未指定人员归属单位信息");
        }
        dto.setUnitCode(company.getCompanyCode());
        Page<TzsUserInfoDto> page = new Page<>();
        page.setCurrent(Long.parseLong(current));
        page.setSize(Long.parseLong(size));
        return ResponseHelper.buildResponse(tzsUserInfoService.page(dto, page, sort));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/queryESForPage")
    @ApiOperation(httpMethod = "GET", value = "人员信息列表,从ES中获取数据", notes = "人员信息列表，替换掉原先的从数据库查询的接口，用于监管和企业的人员管理列表")
    public ResponseModel<IPage<JSONObject>> queryESForPage(@RequestParam(value = "current") String current,
                                                           @RequestParam(value = "size") String size,
                                                           @RequestParam(value = "sort", required = false) String sort,
                                                           @RequestParam Map<String, String> map) {
        return ResponseHelper.buildResponse(tzsUserInfoService.queryESForPage(getSelectedOrgInfo(), current, size, sort, map));
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/createUnitPerson")
    @ApiOperation(httpMethod = "GET", value = "给单位历史管理员添加两员配备默认数据", notes = "给单位历史管理员添加两员配备默认数据")
    public ResponseModel<Object> createUnitPerson() {
        return ResponseHelper.buildResponse(tzsUserInfoService.createUnitPerson());
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/BindAccount")
    @ApiOperation(httpMethod = "POST", value = "人员绑定用户", notes = "人员绑定用户")
    public ResponseModel<Boolean> BindAccount(@RequestBody Map<String, Object> map) {
        return ResponseHelper.buildResponse(tzsUserInfoService.BindAccount(map));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/startOrStopAccount")
    @ApiOperation(httpMethod = "POST", value = "启用或者停用账户", notes = "启用或者停用账户")
    public ResponseModel<String> startOrStopAccount(@RequestBody Map<String, Object> map) {
        return ResponseHelper.buildResponse(tzsUserInfoService.startOrStopAccount(map));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getEquipmentType")
    @ApiOperation(httpMethod = "GET", value = "企业下涉及设备类型", notes = "企业下涉及设备类型")
    public ResponseModel<List<Map<String, Object>>> getEquipmentType(@RequestParam(value = "creditCode") String creditCode) {
        return ResponseHelper.buildResponse(tzsUserInfoService.getEquipmentType(creditCode));
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/arrangement-statistic")
    @ApiOperation(httpMethod = "GET", value = "两员配备说明统计", notes = "两员配备说明统计")
    public ResponseModel<Map<String, Integer>> arrangementStatistic() {
        List<CompanyModel> companyModels = FeignUtil.remoteCall(() -> Privilege.companyClient.queryListByChild(RequestContext.getExeUserId()));
        if (companyModels.isEmpty()) {
            throw new BadRequest("未指定人员归属单位信息");
        }
        return ResponseHelper.buildResponse(tzsUserInfoService.getArrangementStatistic(companyModels.get(0).getCompanyCode()));
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getCompanyType")
    @ApiOperation(httpMethod = "GET", value = "当前登录用户单位类型获取", notes = "当前登录用户单位类型获取")
    public ResponseModel<Map<String, Object>> getCompanyType() {
        return ResponseHelper.buildResponse(tzsUserInfoService.getCompanyType());
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getCompanyTypeForRedis")
    @ApiOperation(httpMethod = "GET", value = "从redis获取当前登录用户单位类型获取，避免多角色的单位获取到多个单位类型", notes = "从redis获取当前登录用户单位类型获取，避免多角色的单位获取到多个单位类型")
    public ResponseModel<Map<String, Object>> getCompanyTypeForRedis() {
        ReginParams selectedOrgInfo = getSelectedOrgInfo();
        return ResponseHelper.buildResponse(tzsUserInfoService.getCompanyTypeForRedis(selectedOrgInfo));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getUserType")
    @ApiOperation(httpMethod = "GET", value = "获取所有人员类型", notes = "获取所有人员类型")
    public ResponseModel<List<Map<String, Object>>> getUserAllPostType() {
        return ResponseHelper.buildResponse(tzsUserInfoService.getUserAllPostType());
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getSubPostByParentsIds")
    @ApiOperation(httpMethod = "GET", value = "根据岗位父类型ids获取对应岗位子类型", notes = "根据岗位父类型ids获取对应岗位子类型")
    public ResponseModel<List<DataDictionary>> getSubPostByParentsIds(@RequestParam(value = "postIds") String postIds) {
        return ResponseHelper.buildResponse(tzsUserInfoService.getSubPostByParentsIds(postIds));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getEquipList")
    @ApiOperation(httpMethod = "GET", value = "设备查询（可绑定、可解绑）", notes = "设备查询（可绑定、可解绑）")
    public ResponseModel<IPage<TzsEquipListDto>> getEquipList(@RequestParam(value = "type") String type,
                                                              @RequestParam(value = "userSeq", required = false) String userSeq,
                                                              @RequestParam(value = "current") String current,
                                                              @RequestParam(value = "size") String size,
                                                              TzsEquipListDto dto) {

        Page<TzsEquipListDto> page = new Page<>();
        page.setCurrent(Long.parseLong(current));
        page.setSize(Long.parseLong(size));
        return ResponseHelper.buildResponse(tzsUserInfoService.getEquipList(type, userSeq, dto, page));
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/equipBind")
    @ApiOperation(httpMethod = "POST", value = "设备绑定解绑", notes = "设备绑定解绑")
    public ResponseModel<Boolean> equipBind(@RequestParam(value = "type") String type,
                                            @RequestParam(value = "userSeq") String userSeq,
                                            @RequestParam(value = "creditCode") String creditCode,
                                            @RequestBody Map<String, Object> map) {
        return ResponseHelper.buildResponse(tzsUserInfoService.equipBind(type, userSeq, creditCode, map));
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getSafetyList")
    @ApiOperation(httpMethod = "GET", value = "企业安全员查询", notes = "企业安全员查询")
    public ResponseModel<List<TzsUserInfo>> getSafetyList(@RequestParam(value = "companyCode") String companyCode) {
        return ResponseHelper.buildResponse(tzsUserInfoService.getSafetyList(companyCode));
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getGroupList")
    @ApiOperation(httpMethod = "GET", value = "两个规定用户组列表查询", notes = "两个规定用户组列表查询")
    public ResponseModel<List<Map<String, Object>>> getGroupList() {
        return ResponseHelper.buildResponse(tzsUserInfoService.getGroupList());
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getPersonType")
    @ApiOperation(httpMethod = "GET", value = "获取当前登录人人员类型", notes = "获取当前登录人人员类型")
    public ResponseModel<Map<String, Object>> getPersonType() {
        return ResponseHelper.buildResponse(tzsUserInfoService.getPersonType());
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @GetMapping(value = "/getGroupAndPersonInfo")
    @ApiOperation(httpMethod = "GET", value = "通过组id查询组及组内人员信息", notes = "通过组id查询组及组内人员信息")
    public ResponseModel<List<GroupAndPersonInfoDto>> getGroupAndPersonInfo(@RequestParam(value = "groupId") Long groupId) {
        return ResponseHelper.buildResponse(tzsUserInfoService.getGroupAndPersonInfo(groupId));
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/testGroup")
    @ApiOperation(httpMethod = "GET", value = "给组内添加人员", notes = "给组内添加人员")
    public ResponseModel<Object> testGroup(@RequestParam(value = "groupSeq") String groupSeq) {
        tzsUserInfoService.testGroup(groupSeq);
        return ResponseHelper.buildResponse("ok");
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getTree")
    @ApiOperation(httpMethod = "GET", value = "根据当前登录人获取监管机构", notes = "根据当前登录人获取监管机构")
    public ResponseModel<Object> getGroupAndPersonInfo() {
        ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        if (ObjectUtils.isEmpty(reginParams)) {
            return null;
        }
        Long id = reginParams.getCompany().getSequenceNbr();
        List<LinkedHashMap> data = (List<LinkedHashMap>) redisUtils.get(REGULATOR_UNIT_TREE);
        ArrayList<LinkedHashMap> result = new ArrayList<>();
        return ResponseHelper.buildResponse(tzsUserInfoServiceImpl.screenData(result, data, id.toString()));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/individuality")
    @ApiOperation(httpMethod = "GET", value = "获取人主体信息", notes = "获取人主体信息")
    public ResponseModel<TzIndividualityDto> getIndividualityInfo() {
        return ResponseHelper.buildResponse(tzsUserInfoServiceImpl.getIndividualityInfo());
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/individualityByCompanyCode")
    @ApiOperation(httpMethod = "GET", value = "根据companyCode获取人主体信息", notes = "根据companyCode获取人主体信息")
    public ResponseModel<TzIndividualityDto> individualityByCompanyCode(@RequestParam(value = "companyCode") String companyCode) {
        return ResponseHelper.buildResponse(tzsUserInfoServiceImpl.individualityByCompanyCode(companyCode));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/individuality")
    @ApiOperation(httpMethod = "POST", value = "修改个人主体信息", notes = "修改个人主体信息")
    public ResponseModel<TzIndividualityDto> updateIndividualityInfo(@RequestBody TzIndividualityDto individualityDto) {
        return ResponseHelper.buildResponse(tzsUserInfoServiceImpl.updateIndividualityInfo(individualityDto));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "查询指定类型的下的人", notes = "查询指定类型的下的人")
    @PostMapping(value = "/permission-page")
    public ResponseModel<Page<UserPermissionDto>> getUserByPermission(@RequestParam(value = "current") long current,
                                                                      @RequestParam(value = "size") long size,
                                                                      @RequestParam(value = "sort", required = false) String sort,
                                                                      @RequestParam(required = false, defaultValue = "all") String type,
                                                                      @RequestBody Map<String, Object> map) {
        UserPermissionDto filter = JSON.parseObject(JSON.toJSONString(map), UserPermissionDto.class);
        filter.setOrgCode(getSelectedOrgInfo().getCompany().getOrgCode());
        filter.setCityCode(getSelectedOrgInfo().getCompany().getCompanyCode());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (!ValidationUtil.isEmpty(map.get("createDateRange"))) {
            String createDateRangeObj = Objects.toString(map.get("createDateRange"));
            String[] split = createDateRangeObj.replace("[", "").replace("]", "").split(",");
            String startDateStr = split[0];
            String endDateStr = split[1];
            try {
                Date startDate = sdf.parse(startDateStr);
                Date endDate = sdf.parse(endDateStr);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(endDate);
                calendar.set(Calendar.HOUR_OF_DAY, 23);
                calendar.set(Calendar.MINUTE, 59);
                calendar.set(Calendar.SECOND, 59);
                calendar.set(Calendar.MILLISECOND, 999);
                endDate = calendar.getTime();
                filter.setCreateDateStart(startDate);
                filter.setCreateDateEnd(endDate);
            } catch (Exception e) {
                log.error("日期转化异常：{}", e.getMessage());
            }
        }
        Page<UserPermissionDto> userPermissionDtos = tzsUserInfoServiceImpl.getUserByPermission(current, size, type, filter, sort);
        return ResponseHelper.buildResponse(userPermissionDtos);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "查询当前登录人所属公司下的人", notes = "查询当前登录人所属公司下的人")
    @GetMapping(value = "/listByLogin")
    public ResponseModel<List<UserPermissionDto>> getUserPermissionOfCurrentLogin() {
        UserPermissionDto filter = new UserPermissionDto();
        filter.setCityCode(getSelectedOrgInfo().getCompany().getCompanyCode());
        List<UserPermissionDto> userPermissionDtos = tzsUserInfoServiceImpl.getUserPermissionOfCurrentLogin(filter);
        return ResponseHelper.buildResponse(userPermissionDtos);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "查询指定公司下的人", notes = "查询指定公司下的人")
    @GetMapping(value = "/listByCompanySeq")
    public ResponseModel<List<UserPermissionDto>> getUserPermissionByCompanySeq(@RequestParam Long comSeq) {
        List<UserPermissionDto> userPermissionDtos = tzsUserInfoServiceImpl.getUserPermissionByCompanySeq(comSeq);
        return ResponseHelper.buildResponse(userPermissionDtos);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "人员管理-人员类型-查询所有人员类型", notes = "人员管理-人员类型-查询所有人员类型")
    @GetMapping(value = "/getAllUserType")
    public ResponseModel<List<DataDictionary>> getAllUserType() {
        List<DataDictionary> dataDictionaries = tzsUserInfoServiceImpl.getAllUserType();
        return ResponseHelper.buildResponse(dataDictionaries);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/export")
    @ApiOperation(httpMethod = "GET", value = "人员管理列表数据导出", notes = "人员管理列表数据导出")
    public void userInfoExport(HttpServletResponse response, String ids) {
        Assert.hasText(ids, "未选择导出数据");
        tzsUserInfoService.userInfoExport(response, Arrays.asList(ids.split(",")));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "导出指定类型的下的人--监管账号下的人员列表", notes = "导出指定类型的下的人--监管账号下的人员列表")
    @PostMapping(value = "/jg/export")
    public void jgUserInfoExport(HttpServletResponse response,
                                 @RequestParam(required = false, defaultValue = "all") String type,
                                 @RequestBody UserPermissionDto filter) {
        filter.setOrgCode(getSelectedOrgInfo().getCompany().getOrgCode());
        filter.setCityCode(getSelectedOrgInfo().getCompany().getCompanyCode());
        Page<UserPermissionDto> userPermissionDtos = tzsUserInfoServiceImpl.getUserByPermission(1, Long.MAX_VALUE, type, filter, null);
        List<JGUserInfoVo> exportData = JSON.parseArray(JSON.toJSONString(userPermissionDtos.getRecords()), JGUserInfoVo.class);
        ExcelUtil.createTemplate(response, "人员列表数据", "人员列表", exportData, JGUserInfoVo.class, null, false);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/import")
    @ApiOperation(value = "人员导入", httpMethod = "POST", notes = "导入已经存在公司的人员")
    public ResponseModel<?> importUser(@RequestBody MultipartFile file) {
        return tzsUserInfoService.importUserBatch(file);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/company/import", produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "企业人员导入", httpMethod = "POST", notes = "企业人员导入")
    public ResponseModel<?> importCompanyUser(@RequestBody MultipartFile file) {
        return tzsUserInfoService.importCompanyUser(file, getSelectedOrgInfo());
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/personnelTransferOut")
    @ApiOperation(httpMethod = "GET", value = "人员转出：逻辑删除人员并删除关联的系统账号", notes = "人员转出：逻辑删除人员并删除关联的系统账号")
    public ResponseModel<Boolean> personnelTransferOut(@RequestParam(value = "userSeqNbrs") String userSeqNbrs) {
        return ResponseHelper.buildResponse(tzsUserInfoService.personnelTransferOut(userSeqNbrs));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/statisticsOfPersonnelTypes")
    @ApiOperation(httpMethod = "GET", value = "人员类型统计", notes = "人员类型统计")
    public ResponseModel<JSONObject> statisticsOfPersonnelTypes(@RequestParam(value = "type") String type) {
        return ResponseHelper.buildResponse(tzsUserInfoService.statisticsOfPersonnelTypes(type));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/statisticsOfPersonnelTypesByPatentCode")
    @ApiOperation(httpMethod = "GET", value = "人员类型统计", notes = "人员类型统计")
    public ResponseModel<JSONObject> statisticsOfPersonnelTypesByPatentCode(@RequestParam(value = "parentId") String parentId) {
        return ResponseHelper.buildResponse(tzsUserInfoService.statisticsOfPersonnelTypesByPatentCode(parentId));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getJobItemBySubPost")
    @ApiOperation(httpMethod = "GET", value = "根据人员子类型查询作业项目", notes = "根据人员子类型查询作业项目")
    public ResponseModel<List<DictionarieValueModel>> getJobItemBySubPost(@RequestParam(value = "dicKey") String dicKey,
                                                                          @RequestParam(value = "") String subPost) {
        List<DictionarieValueModel> result = Systemctl.dictionarieClient.dictValues(dicKey).getResult();
        // 包含 持证人员（P）6764 或 持证人员（R2）6765 并且不包含持证人员 6713 的情况下 只显示【移动式压力容器充装】和【气瓶充装】
        if ((subPost.contains("6764") || subPost.contains("6765")) && !subPost.contains("6713")) {
            List<DictionarieValueModel> collect = result.stream()
                    .filter(x -> x.getDictDataKey().equals("移动式压力容器充装") || x.getDictDataKey().equals("气瓶充装"))
                    .collect(Collectors.toList());
            return ResponseHelper.buildResponse(collect);
        }
        return ResponseHelper.buildResponse(result);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/postByUnitType")
    @ApiOperation(httpMethod = "GET", value = "根据单位类型查询对应的人员类型", notes = "根据单位类型查询对应的人员类型")
    public ResponseModel<List<DataDictionary>> postByUnitType(@ApiParam(value = "表单类型：add/edit/detail，用于过滤监管单位查询人员类型，详情页面查询所有（可能是查看其他单位的人员详情），新增编辑页面只过滤自己类型下的，限制添加的人员类型", required = true, defaultValue = "detail")
                                                              @RequestParam(value = "formType", defaultValue = "") String formType) {
        CompanyBo company = getSelectedOrgInfo().getCompany();
        return ResponseHelper.buildResponse(tzsUserInfoService.postByUnitType(company, formType));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/subPostByUnitType")
    @ApiOperation(httpMethod = "GET", value = "根据单位类型查询对应的人员类型子类型", notes = "根据单位类型查询对应的人员类型子类型")
    public ResponseModel<List<DataDictionary>> subPostByUnitType(@RequestParam(value = "parentCode") String parentCode) {
        CompanyBo company = getSelectedOrgInfo().getCompany();
        return ResponseHelper.buildResponse(tzsUserInfoService.subPostByUnitType(company, parentCode));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/historicalOperatorHandling")
    @ApiOperation(httpMethod = "GET", value = "【数据处理】【调用一次即可】需求3309 人员管理调整后：历史的维保人员（作业人员含电梯维修资质的刷入子类型：持证人员）", notes = "【数据处理】【调用一次即可】需求3309 人员管理调整后：历史的维保人员（作业人员含电梯维修资质的刷入子类型：持证人员）")
    public ResponseModel<Object> historicalOperatorHandling() {
        // userinfo表中旧的post字段保存了旧字典值6618（维保人员）
        List<Long> sesqNbrs = tzsUserInfoService.getBaseMapper()
                .selectList(new LambdaQueryWrapper<TzsUserInfo>()
                        .like(TzsUserInfo::getPost, "6618")
                        .select(TzsUserInfo::getSequenceNbr))
                .stream()
                .map(TzsUserInfo::getSequenceNbr)
                .collect(Collectors.toList());
        tzsUserInfoService.getBaseMapper().update(null, new LambdaUpdateWrapper<TzsUserInfo>()
                .set(TzsUserInfo::getSubPost, "[\"6713\"]")
                .set(TzsUserInfo::getSubPostName, "持证人员")
                .in(TzsUserInfo::getSequenceNbr, sesqNbrs));
        return ResponseHelper.buildResponse("更新数据：" + sesqNbrs.size() + "条");
    }

    /**
     * 需求3321 人员管理分类调整，删除部分人员子类型对应的历史数据
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "【数据处理】需求3321 人员管理分类调整，删除部分人员子类型对应的历史数据", notes = "【数据处理】需求3321 人员管理分类调整，删除部分人员子类型对应的历史数据")
    @GetMapping(value = "/deletePersonSubtypeHistoricalData")
    public ResponseModel<String> deletePersonSubtypeHistoricalData() {
        return ResponseHelper.buildResponse(tzsUserInfoService.deletePersonSubtypeHistoricalData());
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/refreshUserGroupInfo")
    @ApiOperation(httpMethod = "POST", value = "同步人员信息", notes = "同步人员信息")
    public ResponseModel<TzsUserInfoDto> refreshUserInfo(@RequestBody List<String> userIds) {
        tzsUserInfoServiceImpl.refreshUserGroupInfo(userIds);
        return ResponseHelper.buildResponse(null);
    }
}
