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

import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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.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.interceptors.PermissionInterceptorContext;
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.core.framework.PersonIdentify;
import com.yeejoin.amos.boot.module.common.api.dto.*;
import com.yeejoin.amos.boot.module.common.api.entity.CompanyInfo;
import com.yeejoin.amos.boot.module.common.api.entity.FireTeam;
import com.yeejoin.amos.boot.module.common.api.mapper.FireTeamMapper;
import com.yeejoin.amos.boot.module.common.api.mapper.OrgUsrMapper;
import com.yeejoin.amos.boot.module.common.biz.service.impl.ESOrgUsrService;
import com.yeejoin.amos.boot.module.common.biz.service.impl.FireCompanyInfoServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.typroject.tyboot.component.emq.EmqKeeper;
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.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yeejoin.amos.boot.biz.common.constants.CommonConstant;
import com.yeejoin.amos.boot.module.common.api.entity.OrgUsr;
import com.yeejoin.amos.boot.module.common.api.excel.ExcelUtil;
import com.yeejoin.amos.boot.module.common.biz.service.impl.OrgUsrServiceImpl;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @author fengwang
 * @date 2021-06-21.
 */
@RestController
@Api(tags = "人员Api")
@RequestMapping(value = "/org-person")
public class OrgPersonController extends BaseController {
    @Autowired
    OrgUsrServiceImpl iOrgUsrService;
    @Autowired
    private RedisUtils redisUtils;
    @Value("${auth-key-org-user:org_user_info}")
    private String authKey;

    @Autowired
    FireCompanyInfoServiceImpl fireCompanyInfoServiceImpl;

    /**
     * 新增人员信息
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "新增人员信息", notes = "新增人员信息")
    public ResponseModel<?> saveOrgUsr(HttpServletRequest request, @RequestBody OrgPersonDto OrgPersonVo) throws Exception {
        OrgPersonVo.setBizOrgType(CommonConstant.BIZ_ORG_TYPE_PERSON);

        return ResponseHelper.buildResponse( iOrgUsrService.saveOrgPerson(OrgPersonVo));
    }

    /**
     * 根据id删除
     *
     * @param id
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除", notes = "根据id删除")
    public ResponseModel<?> deleteById(HttpServletRequest request, @PathVariable Long id) {
        // 删除时，只作逻辑删除
        iOrgUsrService.update(new UpdateWrapper<OrgUsr>().eq("sequence_nbr", id).set("is_delete",
                CommonConstant.IS_DELETE_01));
        return ResponseHelper.buildResponse(null);
    }

    /**
     * 更新人员数据
     *
     * @return
     */

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    @ApiOperation(httpMethod = "PUT", value = "更新人员数据", notes = "更新人员数据")
    public ResponseModel<?> updateByIdOrgUsr(HttpServletRequest request, @RequestBody OrgPersonDto OrgPersonVo,
                                             @PathVariable Long id) throws Exception {
        OrgPersonVo.setBizOrgType(CommonConstant.BIZ_ORG_TYPE_PERSON);
        /*同步修改关联账号用户名 chenzhao*/
        AgencyUserModel amosUser = Privilege.agencyUserClient.queryByUserId(OrgPersonVo.getAmosOrgId()).getResult();
        OrgPersonVo.setAmosOrgCode(amosUser.getRealName());

        return ResponseHelper.buildResponse(  iOrgUsrService.updateByIdOrgPerson(OrgPersonVo, id));
    }


    /**
     * 根据id查询人员
     *
     * @param request
     * @param id
     * @return
     * @throws Exception
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "获取人员详情", notes = "获取人员详情")
    public ResponseModel<OrgPersonFormDto> selectById(HttpServletRequest request, @PathVariable Long id) throws Exception {

        OrgPersonFormDto orgPersonFormDto=iOrgUsrService.selectPersonById(id);
        AgencyUserModel user = getUserInfo();
        orgPersonFormDto.setUserId(user.getUserId());
        return ResponseHelper.buildResponse(orgPersonFormDto);
    }

    /**
     * @param request
     * @param id
     * @return
     * @throws Exception
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/{id}/detail", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "获取人员详情", notes = "获取人员详情")
    public ResponseModel<OrgPersonFormDto> selectByIdDetail(HttpServletRequest request, @PathVariable Long id) throws Exception {
        return ResponseHelper.buildResponse(iOrgUsrService.selectPersonByIdDetail(id));
    }

    /**
     * 根据id查询人员
     *
     * @param id
     * @return
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/show/{id}", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "获取人员详情(map类型)", notes = "获取人员详情")
    public ResponseModel<Map<String, Object>> selectForShowById(HttpServletRequest request, @PathVariable Long id) throws Exception {
        OrgUsr orgUsr = iOrgUsrService.getById(id);
        Map<String, Object> result = iOrgUsrService.selectForShowById(orgUsr, id);
        return ResponseHelper.buildResponse(result);
    }


    /**
     * 获取人员树
     *
     * @param
     * @return
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/companyTree", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "获取人员树", notes = "获取人员树")
    public ResponseModel<List<OrgMenuDto>> selectPersonTree() throws Exception {
        return ResponseHelper.buildResponse(iOrgUsrService.selectPersonTree());
    }

    /**
     * 列表分页查询
     *
     * @return
     */
    @TycloudOperation( ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "列表分页查询", notes = "列表分页查询")
    public ResponseModel<Object> listPage(@RequestParam Map<String, Object> requestBody) {

        return ResponseHelper.buildResponse(iOrgUsrService.pagePerson(
                requestBody.containsKey("pageNum") ? requestBody.get("pageNum").toString()  :  null ,
                requestBody.containsKey("pageSize") ? requestBody.get("pageSize").toString()  :  null ,
                requestBody));
    }

    /**
     * 根据orgCode查询
     *
     * @param orgCode
     * @return
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/{orgCode}/users", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据orgCode查询", notes = "根据orgCode查询")
    public ResponseModel<Collection<OrgUsr>> selectUsersByOrgCode(HttpServletRequest request, String pageNum,
                                                                  String pageSize, @PathVariable String orgCode) {
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("is_delete", CommonConstant.IS_DELETE_00);
        columnMap.put("biz_org_code", orgCode);
        columnMap.put("biz_org_type", CommonConstant.BIZ_ORG_TYPE_PERSON);
        Collection<OrgUsr> temp = iOrgUsrService.listByMap(columnMap);
        temp.stream().forEach(t -> {
            // BUG2886 因为前期沟通 人员code 可能会发生改变 所以 现在接口code 不再保存，查询数据时通过接口重新赋值 by kongfm 2021-09-16
            if(StringUtils.isNotEmpty(t.getAmosOrgId())) {
                FeignClientResult<AgencyUserModel> result1 = Privilege.agencyUserClient.queryByUserId(t.getAmosOrgId());
                if(null !=result1.getResult()) {
                    t.setAmosOrgCode(result1.getResult().getRealName());
                }
            }
        });
        return ResponseHelper.buildResponse(temp);
    }

    /**
     * 导出人员模板
     *
     * @param response
     * @param
     * @return
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/download-template", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "导出人员模板", notes = "导出人员模板")
    public ResponseModel<?> downloadTemplate(HttpServletResponse response) throws UnsupportedEncodingException {
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
//        List<OrgUsrDownloadTemplateVO> OrgUsrDownloadTemplateVO = new ArrayList<OrgUsrDownloadTemplateVO>();
//        ExcelUtils.exportExcel(OrgUsrDownloadTemplateVO, "人员信息", "人员信息", OrgUsrDownloadTemplateVO.class,
//        simpleDateFormat.format(new Date()) + ".xls", response);
        return ResponseHelper.buildResponse(null);
    }

    /**
     * 导入人员信息
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/savePerson", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "导入人员信息", notes = "导入人员信息")
    public ResponseModel<?> savePerson(HttpServletRequest request, @RequestBody List<OrgPersonDto> OrgPersonVo) throws Exception {
        iOrgUsrService.savePersonList(OrgPersonVo);
        return ResponseHelper.buildResponse(null);
    }

    /**
     * 根据id查询人员
     *
     * @param ids
     * @return
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/showPersonList/{ids}", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "获取人员列表详情(map类型)", notes = "获取人员详情")
    public ResponseModel<List<Map<String, Object>>> selectForShowByListId(HttpServletRequest request,
                                                                          @PathVariable List<Long> ids) throws Exception {
        return ResponseHelper.buildResponse(iOrgUsrService.selectForShowByListId(ids)
        );
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "导入机场单位")
    @PostMapping("/import_batch")
    public void importByExcel(MultipartFile multipartFile) throws Exception {
        List<OrgPersonExcelDto> excelDtoList = ExcelUtil.readFirstSheetExcel(multipartFile, OrgPersonExcelDto.class, 1);
        iOrgUsrService.importByExcel(excelDtoList);
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @ApiOperation(value = "导出机场单位")
    @GetMapping("/export")
    public void exportToExcel(HttpServletResponse response, ExcelDto excelDto) {
        try {
            List<OrgPersonExcelDto> data = iOrgUsrService.queryOrgPersonDtoList(false);
            ExcelUtil.createTemplate(response, excelDto.getFileName(), excelDto.getSheetName(), data,
                    OrgPersonExcelDto.class, null, false);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("系统异常！");
        }
    }

//    /**
//     * 机场单位下 各单位下人员岗位不为空的人员
//     *
//     * @param id
//     * @return
//     */
//    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
//    @RequestMapping(value = "/companyId/{id}", method = RequestMethod.GET)
//    @ApiOperation(httpMethod = "GET", value = "获取人员岗位不为空的人员详情", notes = "获取人员岗位不为空的人员详情")
//    public ResponseModel<Object> queryCompanyId(HttpServletRequest request,
//                                                @PathVariable Long id) throws Exception {
//        return ResponseHelper.buildResponse(iOrgUsrService.queryCompanyId(id));
//    }

    /**
     * 根据userId查询人员
     *
     * @param request
     * @param userId
     * @return
     * @throws Exception
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/getPersonByUserId/{userId}", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据平台用户ID查询人员详情", notes = "根据平台用户ID查询人员详情")
    public ResponseModel<JSONObject> selectByUserId(HttpServletRequest request, @PathVariable Long userId) throws Exception {
        return ResponseHelper.buildResponse(iOrgUsrService.selectPersonByUserId(userId));
    }

    /**
     * 新增人员
     *
     * @return
     */
    @TycloudOperation(needAuth = true, ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/peopleSave", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "新增人员", notes = "新增人员默认创建消防人员")
    public ResponseModel<PeopleInfoDto> peopleSave(@RequestBody PeopleInfoDto peopleInfoDto) {
        return ResponseHelper.buildResponse( iOrgUsrService.peopleSave(peopleInfoDto));
    }

    /**
     * 根据id查询人员
     * @param id
     * @return
     * @throws Exception
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/people/{id}", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "获取人员详情", notes = "获取人员详情")
    public ResponseModel<PeopleInfoDto> selectPeopleById(@PathVariable Long id) {

        PeopleInfoDto peopleInfoDto =iOrgUsrService.selectPeopleById(id);
        return ResponseHelper.buildResponse(peopleInfoDto);
    }

    /**
     * 根据id删除
     *
     * @param id
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/people/{id}/{type}", method = RequestMethod.DELETE)
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除", notes = "根据id删除")
    public ResponseModel<String> deletePeopleById(@PathVariable Long id, @PathVariable String type) {
        AgencyUserModel user = getUserInfo();
        return ResponseHelper.buildResponse(iOrgUsrService.deletePeopleById(id, type, user));
    }

    /**
     * 查询身份证号码是否重复
     * @param certificatesNumber
     * @return 标志
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/people/checkCertificates/{certificatesNumber}", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "查询身份证号码是否重复", notes = "查询身份证号码是否重复")
    public ResponseModel<Boolean> checkCertificatesNumber(@PathVariable String certificatesNumber) {
        return ResponseHelper.buildResponse(iOrgUsrService.checkCertificatesNumber(certificatesNumber));
    }

    /**
     * 根据id删除
     * @param id
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @RequestMapping(value = "/people/firefighter/{id}", method = RequestMethod.DELETE)
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除", notes = "根据id删除")
    public ResponseModel<String> deleteFirefighterPeopleById(@PathVariable Long id) {
        return ResponseHelper.buildResponse(iOrgUsrService.deleteFirefighterPeopleById(id));
    }
}
