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.query.QueryWrapper;
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.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
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.enums.TwoStipulateGroupEnum;
import com.yeejoin.amos.boot.module.tcm.api.mapper.TzsUserInfoMapper;
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.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 java.util.*;

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

    @Autowired
    private TzsUserInfoServiceImpl tzsUserInfoServiceImpl;

    @Autowired
    private ITzsUserInfoService tzsUserInfoService;

    @Autowired
    private TzsUserInfoMapper tzsUserInfoMapper;

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

        LambdaQueryWrapper<TzsUserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TzsUserInfo::getCertificateType,tzsUserInfo.getCertificateType());
        queryWrapper.eq(TzsUserInfo::getCertificateNum,tzsUserInfo.getCertificateNum());
        queryWrapper.eq(TzsUserInfo::getIsDelete, false);
        TzsUserInfo certificateNum = tzsUserInfoMapper.selectOne(queryWrapper);
        if(!ObjectUtils.isEmpty(certificateNum)){
            throw new BadRequest("证件号码重复，请核对！");
        }

        LambdaQueryWrapper<TzsUserInfo> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(TzsUserInfo::getPhone,tzsUserInfo.getPhone());
        queryWrapper1.eq(TzsUserInfo::getIsDelete, false);
        TzsUserInfo phone = tzsUserInfoMapper.selectOne(queryWrapper1);
        if(!ObjectUtils.isEmpty(phone)){
            throw new BadRequest("联系电话重复，请核对！");
        }

        ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        if (ObjectUtils.isEmpty(reginParams)) {
            return null;
        }
        CompanyBo companyModel = reginParams.getCompany();
        if(ObjectUtils.isEmpty(companyModel)){
            throw new BadRequest("未指定人员归属单位信息");
        }
        tzsUserInfo.setUnitName(companyModel.getCompanyName());
        tzsUserInfo.setUnitCode(companyModel.getCompanyCode());
        tzsUserInfo.setAppointDoc(tzsUserInfo.getAppointDoc());
        tzsUserInfo.setRecDate(new Date());
        // 兼容前端只传一个值，并且非json类型的情况
        tzsUserInfo.setPost(tzsUserInfoServiceImpl.isJSONValid(tzsUserInfo.getPost()) ? tzsUserInfo.getPost() : "[\"" + tzsUserInfo.getPost() + "\"]");
        tzsUserInfo.setPostName(tzsUserInfoServiceImpl.setPostName(tzsUserInfo.getPost()));
        tzsUserInfo = tzsUserInfoServiceImpl.createWithModel(tzsUserInfo);
        return ResponseHelper.buildResponse(tzsUserInfo);
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/update")
    @ApiOperation(httpMethod = "POST", value = "修改人员信息", notes = "修改人员信息")
    public ResponseModel<TzsUserInfo> update(@RequestBody JSONObject map,
                                             @RequestParam Long rowId) {
        Map<String, Object> userInfo = (Map<String, Object>)map.get("userInfo");
        TzsUserInfo tzsUserInfo = JSON.parseObject(JSON.toJSONString(userInfo), TzsUserInfo.class);
        LambdaQueryWrapper<TzsUserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TzsUserInfo::getCertificateType,tzsUserInfo.getCertificateType());
        queryWrapper.eq(TzsUserInfo::getCertificateNum,tzsUserInfo.getCertificateNum());
        queryWrapper.ne(TzsUserInfo::getSequenceNbr,rowId);
        queryWrapper.eq(TzsUserInfo::getIsDelete, false);
        TzsUserInfo certificateNum = tzsUserInfoMapper.selectOne(queryWrapper);
        if(!ObjectUtils.isEmpty(certificateNum)){
            throw new BadRequest("证件号码重复，请核对！");
        }

        LambdaQueryWrapper<TzsUserInfo> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(TzsUserInfo::getPhone,tzsUserInfo.getPhone());
        queryWrapper1.ne(TzsUserInfo::getSequenceNbr,rowId);
        queryWrapper1.eq(TzsUserInfo::getIsDelete, false);
        TzsUserInfo phone = tzsUserInfoMapper.selectOne(queryWrapper1);
        if(!ObjectUtils.isEmpty(phone)){
            throw new BadRequest("联系电话重复，请核对！");
        }

        ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        if (ObjectUtils.isEmpty(reginParams)) {
            return null;
        }
        CompanyBo companyModel = reginParams.getCompany();
        if(ObjectUtils.isEmpty(companyModel)){
            throw new BadRequest("未指定人员归属单位信息");
        }

        //删除人员与组的关系
        QueryWrapper<TzsUserInfo> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("sequence_nbr",rowId);
        queryWrapper2.eq("is_delete",false);
        TzsUserInfo selectOne = tzsUserInfoMapper.selectOne(queryWrapper2);
        if(!ObjectUtils.isEmpty(selectOne.getAmosUserId())){
            tzsUserInfoServiceImpl.deleteGroupAndPersonRelation(selectOne.getPostName(),selectOne.getAmosUserId());
        }

        tzsUserInfo.setUnitName(companyModel.getCompanyName());
        tzsUserInfo.setUnitCode(companyModel.getCompanyCode());
        tzsUserInfo.setSequenceNbr(rowId);
        tzsUserInfo.setRecDate(new Date());
        // 兼容前端只传一个值，并且非json类型的情况
        tzsUserInfo.setPost(tzsUserInfoServiceImpl.isJSONValid(tzsUserInfo.getPost()) ? tzsUserInfo.getPost() : "[\"" + tzsUserInfo.getPost() + "\"]");
        String postName = tzsUserInfoServiceImpl.setPostName(tzsUserInfo.getPost());
        tzsUserInfo.setPostName(postName);
        if(!ObjectUtils.isEmpty(selectOne.getAmosUserId())){
            // 添加新的人员与组的关系
            String[] split = postName.split(",");
            List<String> ids = new ArrayList<>();
            ids.add(selectOne.getAmosUserId());
            for (String s : split) {
                if(!ObjectUtils.isEmpty(TwoStipulateGroupEnum.getId.get(s))){
                    Privilege.groupUserClient.create(TwoStipulateGroupEnum.getId.get(s), ids);
                }
            }
        }
        tzsUserInfoServiceImpl.updateById(tzsUserInfo);
        return ResponseHelper.buildResponse(tzsUserInfo);
    }



    @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 = "/getUserType")
    @ApiOperation(httpMethod = "GET", value = "根据单位类型获取人员类型", notes = "根据单位类型获取人员类型")
    public ResponseModel<List<Map<String, Object>>> getUserType(@RequestParam(value = "unitType") String unitType) {
        return ResponseHelper.buildResponse(tzsUserInfoService.getUserType(unitType));
    }

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