package com.yeejoin.amos.boot.module.common.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.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.constants.CommonConstant;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.utils.NameUtils;
import com.yeejoin.amos.boot.module.common.api.dto.*;
import com.yeejoin.amos.boot.module.common.api.entity.OrgUsr;
import com.yeejoin.amos.boot.module.common.api.feign.EquipFeignClient;
import com.yeejoin.amos.boot.module.common.biz.service.impl.ESOrgUsrService;
import com.yeejoin.amos.boot.module.common.biz.service.impl.OrgUsrServiceImpl;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.UserOrgTreeModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * 部门信息修改
 *
 * @author tb
 * @date 2021-06-18
 */
@RestController
@Api(tags = "单位Api")
@RequestMapping(value = "/org-usr")
public class OrgUsrController extends BaseController {

    @Autowired
    OrgUsrServiceImpl iOrgUsrService;
    @Autowired
    ESOrgUsrService eSOrgUsrService;
    @Autowired
    EmqKeeper emqKeeper;
    @Value("${jcs.company.topic.delete}")
    private String airportDeleteTopic;

    @Autowired
    EquipFeignClient equipFeignClient;

    /**
     * 新增单位信息
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "新增单位信息", notes = "新增单位信息")
    public ResponseModel<?> saveOrgUsr(HttpServletRequest request, @RequestBody OrgUsrDto OrgUsrVo) throws Exception {
        OrgUsrVo.setBizOrgType(CommonConstant.BIZ_ORG_TYPE_COMPANY);
        iOrgUsrService.saveOrgUsr(OrgUsrVo);
        return ResponseHelper.buildResponse(null);
    }

    /**
     * 根据id删除
     *
     * @param id
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除", notes = "根据id删除")
    public ResponseModel<String> deleteById(HttpServletRequest request, @PathVariable Long id) {
        // 删除时，只作逻辑删除
        // BUG 2741 首先判断是否为公司 如果公司底下有人员不可直接删除 bykongfm
        OrgUsr tempOrg = iOrgUsrService.getById(id.toString());
        if(tempOrg.getBizOrgType().equals("COMPANY")) {
            List<OrgUsr> tempList = iOrgUsrService.list(new LambdaQueryWrapper<OrgUsr>().eq(OrgUsr::getParentId,id).eq(OrgUsr::getIsDelete,false));
            if(tempList.size() > 0) {
                return ResponseHelper.buildResponse("-1");
            }
        }
        //bug 2882 判断是否为部门 如果部门底下有人员不可直接删除 chenzhao 2021-09-27 start
        if(tempOrg.getBizOrgType().equals("DEPARTMENT")) {
            List<OrgUsr> tempList = iOrgUsrService.list(new LambdaQueryWrapper<OrgUsr>().eq(OrgUsr::getParentId,id).eq(OrgUsr::getIsDelete,false));
            if(tempList.size() > 0) {
                return ResponseHelper.buildResponse("-1");
            }
        }
        //bug 2882 判断是否为部门 如果部门底下有人员不可直接删除 chenzhao 2021-09-27 end
//        iOrgUsrService.update(new UpdateWrapper<OrgUsr>().eq("sequence_nbr", id).set("is_delete", CommonConstant.IS_DELETE_01));
        /*bug 2812 一次删除多条数据  传入类型修改为string 问题解决 2021-09-09 陈召 开始*/
      iOrgUsrService.update(new UpdateWrapper<OrgUsr>().eq("sequence_nbr", String.valueOf(id)).set("is_delete", CommonConstant.IS_DELETE_01));
        /*bug 2812 一次删除多条数据  传入类型修改为string 问题解决 2021-09-09 陈召 结束*/
        try {
            eSOrgUsrService.deleteById(id);
            emqKeeper.getMqttClient().publish(airportDeleteTopic, JSON.toJSONString(id).getBytes(), 2, false);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
        return ResponseHelper.buildResponse("0");
    }


    /**
     * 更新单位数据
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    @ApiOperation(httpMethod = "PUT", value = "更新单位数据", notes = "更新单位数据")
    public ResponseModel<?> updateByIdOrgUsr(HttpServletRequest request, @RequestBody OrgUsrDto OrgUsrVo, @PathVariable Long id) throws Exception {

        OrgUsrVo.setBizOrgType(CommonConstant.BIZ_ORG_TYPE_COMPANY);
        iOrgUsrService.updateByIdOrgUsr(OrgUsrVo, id);
        return ResponseHelper.buildResponse(null);
    }


    /**
     * 根据id查询单位
     *
     * @param id
     * @return
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "获取单位详情", notes = "获取单位详情")
    public ResponseModel<OrgUsrFormDto> selectById(HttpServletRequest request, @PathVariable Long id) throws Exception {
        return ResponseHelper.buildResponse(iOrgUsrService.selectCompanyById(id));
    }


    /**
     * 根据bizOrgType分页查询
     *
     * @param bizOrgType
     * @return
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/selectByBizOrgType/{bizOrgType}", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据bizOrgType分页查询", notes = "根据bizOrgType分页查询")
    public ResponseModel<IPage<OrgUsr>> bizOrgTypeListPage(String pageNum, String pageSize, @PathVariable String bizOrgType) throws Exception {
        return ResponseHelper.buildResponse(iOrgUsrService.page(iOrgUsrService.bizOrgTypeListPage(pageNum, pageSize, bizOrgType)));
    }


    /**
     * 获取单位部门树
     *
     * @param
     * @return
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/companyTree", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "获取单位部门树(key为物理主键)", notes = "获取单位部门树(key为物理主键)\"")
    public ResponseModel<List<OrgMenuDto>> selectCompanyTree() throws Exception {
        List<OrgMenuDto> menus = iOrgUsrService.getTree(null, iOrgUsrService.selectCompanyDepartmentMsg(), OrgUsr.class.getName(), "getSequenceNbr", 2, "getBizOrgName", "getParentId", "getBizOrgType");
        return ResponseHelper.buildResponse(menus);
    }

    /**
     * 获取单位部门树
     *
     * @param
     * @return
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/orgTree", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "获取单位部门树(bizOrgCode为物理主键)", notes = "获取单位部门树(bizOrgCode为物理主键)\"")
    public ResponseModel<List<OrgMenuDto>> selectCompanyTreeCode() throws Exception {
        List<OrgMenuDto> menus = OrgUsrServiceImpl.buildTreeParallel(iOrgUsrService.selectCompanyDepartmentMsg());
        return ResponseHelper.buildResponse(menus);
    }

    /**
     * 获取单位部门树
     *
     * @param
     * @return
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/org/company/tree", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "获取单位树(bizOrgCode为物理主键)", notes = "获取单位树(bizOrgCode为物理主键)")
    public ResponseModel<List<OrgMenuDto>> getCompanyTree() {
        List<OrgMenuDto> menus = OrgUsrServiceImpl.buildTreeParallel(iOrgUsrService.selectCompanyList());
        return ResponseHelper.buildResponse(menus);
    }

    /**
     * 列表分页查询
     *
     * @return
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "列表分页查询", notes = "列表分页查询")
    public IPage<OrgUsr> listPage(String pageNum, String pageSize, OrgUsr orgUsr) {

        Page<OrgUsr> pageBean;
        QueryWrapper<OrgUsr> orgUsrQueryWrapper = new QueryWrapper<>();
        Class<? extends OrgUsr> aClass = orgUsr.getClass();
        Arrays.stream(aClass.getDeclaredFields()).forEach(field -> {
            try {
                field.setAccessible(true);
                Object o = field.get(orgUsr);
                if (o != null) {
                    Class<?> type = field.getType();
                    String name = NameUtils.camel2Underline(field.getName());
                    if (type.equals(Integer.class)) {
                        Integer fileValue = (Integer) field.get(orgUsr);
                        orgUsrQueryWrapper.eq(name, fileValue);
                    } else if (type.equals(Long.class)) {
                        Long fileValue = (Long) field.get(orgUsr);
                        orgUsrQueryWrapper.eq(name, fileValue);
                    } else if (type.equals(String.class)) {
                        String fileValue = (String) field.get(orgUsr);
                        orgUsrQueryWrapper.eq(name, fileValue);
                    } else {
                        String fileValue = (String) field.get(orgUsr);
                        orgUsrQueryWrapper.eq(name, fileValue);
                    }
                }
            } catch (Exception e) {
            }
        });
        IPage<OrgUsr> page;
        if (StringUtils.isBlank(pageNum) || StringUtils.isBlank(pageSize)) {
            pageBean = new Page<>(0, Long.MAX_VALUE);
        } else {
            pageBean = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        }
        page = iOrgUsrService.page(pageBean, orgUsrQueryWrapper);
        return page;
    }

    /**
     * 导入部门信息
     *
     * @return
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/saveDepartment", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "导入部门信息", notes = "导入部门信息")
    public ResponseModel<?> saveDepartment(HttpServletRequest request, @RequestBody List<OrgDepartmentDto> OrgDepartmentVo, @PathVariable Long id) throws Exception {
        iOrgUsrService.saveDepartment(OrgDepartmentVo, id);
        return ResponseHelper.buildResponse(null);
    }

    /**
     * 导入单位信息
     *
     * @return
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/saveCompany", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "导入单位信息", notes = "导入单位信息")
    public ResponseModel<?> saveCompany(HttpServletRequest request, @RequestBody List<OrgUsrDto> OrgUsrVo) throws Exception {
        iOrgUsrService.saveCompany(OrgUsrVo);
        return ResponseHelper.buildResponse(null);
    }

    /**
     * 根据id获取单位人员列表
     *
     * @param ids
     * @return
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/{ids}/users", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据id获取单位人员列表", notes = "根据id获取单位人员列表")
    public ResponseModel<List<Map<String, Object>>> selectUsersByOrgCode(HttpServletRequest request, @PathVariable List<Long> ids) throws Exception {
        return ResponseHelper.buildResponse(iOrgUsrService.returnCompanyPersonMsg(ids));
    }

    /**
     * 根据id获取单位人员列表
     *
     * @param ids
     * @return
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/company/{ids}/person", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据id获取单位人员列表", notes = "根据id获取单位人员列表")
    public ResponseModel<List<CompanyPerson>> selectCompanyPerson(@PathVariable List<Long> ids) throws Exception {
        return ResponseHelper.buildResponse(iOrgUsrService.returnCompanyPerson(ids));
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/company/person/{amosUserId}", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据amosUserId获取单位ID", notes = "根据amosUserId获取单位ID")
    public ResponseModel<String> selectPersonId(@PathVariable String amosUserId) throws Exception {
        return ResponseHelper.buildResponse(iOrgUsrService.getParentId(amosUserId));
    }


    /**
     * 根据id获取单位人员列表
     *
     * @param amosUserId
     * @return
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/company/{amosUserId}", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据amos userid获取单位", notes = "根据amos userid获取单位")
    public ResponseModel<OrgUsrDto> selectCompany(@PathVariable String amosUserId) throws Exception {
        return ResponseHelper.buildResponse(iOrgUsrService.getOrg(amosUserId));
    }

    /**
     * 根据名称模糊匹配
     *
     * @param name
     * @return
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/getList", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据名称模糊匹配", notes = "根据名称模糊匹配")
    public ResponseModel<List<ESOrgUsrDto>> selectById(HttpServletRequest request, String name) throws Exception {
        return ResponseHelper.buildResponse(eSOrgUsrService.queryByKeys(name));
    }

    /**
     * 根据名称模糊匹配
     *
     * @param name
     * @return
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/getListdata", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据名称模糊匹配单位", notes = "根据名称模糊匹配单位")
    public ResponseModel<List<ESOrgUsrDto>> selectByIddata(HttpServletRequest request, String name) throws Exception {
        return ResponseHelper.buildResponse(eSOrgUsrService.queryByKeys(name));
    }


    /**
     * 获取单位部门树
     *
     * @param
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/companyTreeByUser", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据登陆人获取单位部门树", notes = "根据登陆人获取单位部门树")
    public ResponseModel<List<OrgMenuDto>> selectCompanyTreeByUser() throws Exception {
        // 获取登陆人角色
        AgencyUserModel user = getUserInfo();
        List<OrgMenuDto> menus = iOrgUsrService.companyTreeByUser(user);
        return ResponseHelper.buildResponse(menus);
    }

    /**
     * 获取单位部门树
     *
     * @param
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/companyUserTreeByUser", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据登陆人获取单位部门用户树", notes = "根据登陆人获取单位部门用户树")
    public ResponseModel<List<OrgMenuDto>> companyUserTreeByUser() {
        // 获取登陆人角色
        AgencyUserModel user = getUserInfo();
        List<OrgMenuDto> menus = iOrgUsrService.companyUserTreeByUser(user);
        return ResponseHelper.buildResponse(menus);
    }

    /**
     * 获取单位列表
     *
     * @param
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/companyListByUser", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据登陆人获取单位列表", notes = "根据登陆人获取单位列表")
    public ResponseModel<List<CheckObjectDto>> companyListByUser() {
        // 获取登陆人角色
        AgencyUserModel user = getUserInfo();
        List<CheckObjectDto> menus = iOrgUsrService.companyListByUser(user);
        return ResponseHelper.buildResponse(menus);
    }


    /**
     * 获取用户单位归属
     *
     * @param userId
     * @return
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/{userId}/userUnit", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "获取用户单位归属", notes = "获取用户单位归属")
    public ResponseModel<UserUnitDto> getUserUnit(@PathVariable String userId) {
        return ResponseHelper.buildResponse(iOrgUsrService.getUserUnit(userId));
    }

    /**
     * 获取用户信息
     *
     * @param userId
     * @return
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/{userId}/userInfo", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "获取用户信息", notes = "获取用户信息")
    public ResponseModel<List<UserDto>> getUserInfo(@PathVariable String userId) {
        return ResponseHelper.buildResponse(iOrgUsrService.getUserInfo(userId));
    }

    /**
     * 获取登陆人绑定的人员关系
     *
     * @param
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = {"/getLoginUserDetails/{userId}", "/getLoginUserDetails"}, method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "获取登陆人绑定的人员关系", notes = "获取登陆人绑定的人员关系")
    public ResponseModel<List<Map<String, Object>>> getLoginUserDetails(@PathVariable(required=false) String userId) {
        AgencyUserModel user = getUserInfo();
        String userIds = userId;
        if (StringUtils.isEmpty(userIds)) {
            userIds =  user.getUserId();
        }
        List<Map<String, Object>> loginUserDetails = iOrgUsrService.getLoginUserDetails(userIds, user);
        return ResponseHelper.buildResponse(loginUserDetails);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/getParentBuilding/{id}", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "获取最上级station", notes = "获取最上级建筑信息")
    public ResponseModel<JSONObject> getBuliding(@PathVariable Long id) {
        JSONObject equipjSONObject = this.getBulid(id);
        return  ResponseHelper.buildResponse(equipjSONObject);
    }

    public JSONObject getBulid(Long id) {
        ResponseModel<Object> equipObj = equipFeignClient.getOne(id);
        JSONObject equipjSONObject = JSONObject.parseObject(JSONObject.toJSONString(equipObj.getResult()));
        if (!equipjSONObject.containsKey("parentId")) {
            return null;
        }
        if (!"0".equals(equipjSONObject.getString("parentId"))) {
            String parentId = equipjSONObject.getString("parentId");
            if (StringUtils.isNotBlank(parentId)) {
                return    getBulid(Long.parseLong(parentId));
            }
        }
        return equipjSONObject;
    }
    /**
     * 判断关联账户是否已关联
     *
     * @param
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/getAmosId/{amosId}", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "判断关联账户是否已关联", notes = "判断关联账户是否已关联")
    public  ResponseModel<Object> getAmosId(@PathVariable String amosId) {

        return ResponseHelper.buildResponse(iOrgUsrService.amosIdExist(amosId));
    }


}