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

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.*;
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 io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
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 javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author fengwang
 * @date 2021-06-21.
 */
@RestController
@Api(tags = "人员Api")
@RequestMapping(value = "/org-person")
public class OrgPersonController {
    @Autowired
    OrgUsrServiceImpl iOrgUsrService;
    @Autowired
    EmqKeeper emqKeeper;
    @Value("${jcs.company.topic.delete}")
    private String airportDeleteTopic;

    /**
     * 新增人员信息
     *
     * @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);
        iOrgUsrService.saveOrgPerson(OrgPersonVo);
        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<?> deleteById(HttpServletRequest request, @PathVariable Long id) {
        // 删除时，只作逻辑删除
        iOrgUsrService.update(new UpdateWrapper<OrgUsr>().eq("sequence_nbr", id).set("is_delete",
                CommonConstant.IS_DELETE_01));
        try {
            emqKeeper.getMqttClient().publish(airportDeleteTopic, String.valueOf(id).getBytes(), 2, true);
        } catch (Exception e) {
            e.getMessage();
        }
        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);
        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 Long 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);
        return ResponseHelper.buildResponse(iOrgUsrService.listByMap(columnMap));
    }

    /**
     * 导出人员模板
     *
     * @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("系统异常！");
        }
    }
}
