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 org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.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.dto.ExcelDto;
import com.yeejoin.amos.boot.module.common.api.dto.OrgMenuDto;
import com.yeejoin.amos.boot.module.common.api.dto.OrgPersonDto;
import com.yeejoin.amos.boot.module.common.api.dto.OrgPersonExcelDto;
import com.yeejoin.amos.boot.module.common.api.dto.OrgPersonFormDto;
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 {
    @Autowired
    OrgUsrServiceImpl iOrgUsrService;

    /**
     * 新增人员信息
     *
     * @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());
        iOrgUsrService.updateByIdOrgPerson(OrgPersonVo, id);
        return ResponseHelper.buildResponse(null);
    }


    /**
     * 根据id查询人员
     *
     * @param request
     * @param id
     * @return
     * @throws Exception
     */
    @TycloudOperation(needAuth = false, 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 {
        return ResponseHelper.buildResponse(iOrgUsrService.selectPersonById(id));
    }

    /**
     * @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(needAuth = false, 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.get("pageNum").toString(),
                requestBody.get("pageSize").toString(), 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("系统异常！");
        }
    }
}
