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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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.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.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 io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.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.HttpServletResponse;
import java.util.*;

@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));
    }

    @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,
                                                             TzsUserInfoDto dto) {

        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));
    }


    @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>>> getUserType(@RequestParam(value = "unitType") String unitType,
                                                                @RequestParam(value = "formType", defaultValue = "add") String formType) {
        return ResponseHelper.buildResponse(tzsUserInfoService.getUserType(unitType, formType));
    }

    @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)
    @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(required = false, defaultValue = "all") String type,
                                                                      @RequestBody UserPermissionDto filter) {
        filter.setOrgCode(getSelectedOrgInfo().getCompany().getOrgCode());
        filter.setCityCode(getSelectedOrgInfo().getCompany().getCompanyCode());
        Page<UserPermissionDto> userPermissionDtos = tzsUserInfoServiceImpl.getUserByPermission(current, size, type, filter);
        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 = "/userTypeUnderMenu")
    public ResponseModel<List<DataDictionary>> userTypeUnderMenu(@RequestParam("menuType") String menuType) {
        List<DataDictionary> dataDictionaries = tzsUserInfoServiceImpl.userTypeUnderMenu(menuType);
        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(",")));
    }
}
