package com.jeeplus.business.humanResources.controller;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.google.common.collect.Lists;
import com.jeeplus.business.finance.util.EasyPoiUtil;
import com.jeeplus.business.humanResources.domain.RegularApply;
import com.jeeplus.business.humanResources.service.StaffUserInfoService;
import com.jeeplus.business.humanResources.service.dto.StaffUserInfoDTO;
import com.jeeplus.business.humanResources.service.dto.UserInfo;
import com.jeeplus.business.humanResources.utils.IdCardUtil;
import com.jeeplus.business.monthly.service.dto.MonthlyDTO;
import com.jeeplus.common.excel.EasyExcelUtils;
import com.jeeplus.common.excel.ExcelOptions;
import com.jeeplus.common.excel.annotation.ExportMode;
import com.jeeplus.common.utils.ResponseUtil;
import com.jeeplus.logging.annotation.ApiLog;
import com.jeeplus.logging.constant.enums.LogTypeEnum;
import com.jeeplus.sys.feign.IOfficeApi;
import com.jeeplus.sys.service.dto.OfficeDTO;


import com.jeeplus.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Api(tags ="员工入职")
@RestController
@RequestMapping(value = "/employeeEntry")
public class StaffUserInfoController {

    @Resource
    private StaffUserInfoService staffUserInfoService;


    /**
     * 列表
     */
    @ApiOperation(value = "入职列表")
    @GetMapping(value = "/findList")
    public ResponseEntity<IPage<StaffUserInfoDTO>> applyList(StaffUserInfoDTO userInfoDTO, Page<StaffUserInfoDTO> page) throws Exception {
        IPage<StaffUserInfoDTO> pageList=staffUserInfoService.findPageList(userInfoDTO,page);
        return ResponseEntity.ok(pageList);
    }


    /*
    根据id进行查询
     */
    @ApiOperation(value = "根据id查询数据")
    @GetMapping(value = "findById")
    public ResponseEntity<StaffUserInfoDTO> findById(@RequestParam String id){
        StaffUserInfoDTO userInfoDTO=staffUserInfoService.findById(id);
        return ResponseEntity.ok(userInfoDTO);
    }

    /**
     * 新增/修改入职
     */
    @ApiOperation(value = "新增/修改入职")
    @PostMapping(value = "/saveForm")
    public ResponseEntity saveForm(@RequestBody StaffUserInfoDTO staffUserInfoDTO) throws Exception{
        String id = staffUserInfoService.saveForm(staffUserInfoDTO);
        return ResponseUtil.newInstance().add("businessTable", "staff_user_info").add("businessId", id).ok ("操作成功");
    }

    /**
     * 根据id修改状态status
     * @param
     */
    @ApiOperation(value = "根据id修改状态status")
    @PostMapping(value = "/updateStatusById")
    public void updateStatusById(@RequestBody StaffUserInfoDTO staffUserInfoDTO) {
        staffUserInfoService.updateStatusById(staffUserInfoDTO);
    }

    /**
     * 根据id进行删除
     */
    @ApiOperation(value = "根据id进行删除")
    @DeleteMapping(value = "/delete")
    public ResponseEntity<String> deleteById(@RequestParam String id){
        String s = staffUserInfoService.deleteById(id);
        return ResponseEntity.ok(s);
    }

    /**
     * 下载导入用户数据模板
     *
     * @param response
     * @return
     */
    @GetMapping("import/template")
    @ApiOperation(value = "下载模板")
    public void importFileTemplate(HttpServletResponse response, HttpServletRequest request) throws IOException {
        String fileName = "用户数据导入模板.xlsx";
        List <UserInfo> list = Lists.newArrayList ( );
        EasyExcelUtils.newInstance ( ).exportExcel ( list, "用户数据", UserInfo.class, fileName, null, response );
    }

    /**
     * 导入用户数据
     */
    @PostMapping("import")
    @ApiOperation(value = "导入用户excel")
    public ResponseEntity importDetail(@RequestPart("file") MultipartFile file, HttpServletRequest request) {
        List<StaffUserInfoDTO> dtoArrayList = new ArrayList<>();
        //获取sheet
        dtoArrayList = EasyPoiUtil.importExcel(file, 0, 1, StaffUserInfoDTO.class);
        //去除excel中的空行
        dtoArrayList = getExcelList(dtoArrayList);
        ArrayList<StaffUserInfoDTO> list = new ArrayList<>();
        //根据用户身份证号获取用户年龄,性别,出生日期
        for (StaffUserInfoDTO staffUserInfoDTO : dtoArrayList) {
            if (StringUtils.isNotBlank(staffUserInfoDTO.getIdCard())){
                //获取年龄
                Integer age = IdCardUtil.getAge(staffUserInfoDTO.getIdCard());
                staffUserInfoDTO.setAge(age.toString());
                //获取性别
                String sex = IdCardUtil.getSex(staffUserInfoDTO.getIdCard());
                staffUserInfoDTO.setSex(sex);
                //获取出生日期
                String birthday = IdCardUtil.getBirthday(staffUserInfoDTO.getIdCard());
                staffUserInfoDTO.setBirthday(birthday);
            }
            staffUserInfoDTO.setOnJobStatus("2");
            //获取部门
            if (StringUtils.isNotBlank(staffUserInfoDTO.getDepartment())){
                OfficeDTO officeDTOByName = SpringUtil.getBean(IOfficeApi.class).getOfficeDTOByName(staffUserInfoDTO.getDepartment());
                staffUserInfoDTO.setDepartment(officeDTOByName.getId());
            }


            staffUserInfoService.saveForm(staffUserInfoDTO);
        }
        list.addAll(dtoArrayList);
        return ResponseEntity.ok(list);


    }

    /**
     * 去除excel中的空行
     * @param list
     * @return
     */
    public ArrayList<StaffUserInfoDTO> getExcelList(List<StaffUserInfoDTO> list){

        ArrayList<StaffUserInfoDTO> infoDTOS = new ArrayList<>();

        list.stream().forEach(item->{
            if(objectCheckIsNull(item)){
                infoDTOS.add(item);
            }
        });

        return infoDTOS;
    }


    public static boolean objectCheckIsNull(Object object) {
        boolean flag = false; //定义返回结果，默认为true

        if (Objects.isNull(object)) {
            flag = false;
        } else {
            Class clazz = (Class) object.getClass(); // 得到类对象
            Field fields[] = clazz.getDeclaredFields(); // 得到所有属性
            for (Field field : fields) {
                if("serialVersionUID".equals(field.getName()) || "BIZ_CODE".equalsIgnoreCase(field.getName())){
                    continue;
                }
                field.setAccessible(true);
                Object fieldValue = null;
                try {
                    fieldValue = field.get(object); //得到属性值
                    Type fieldType = field.getGenericType();//得到属性类型
                    String fieldName = field.getName(); // 得到属性名
                    log.info("属性类型：" + fieldType + ",属性名：" + fieldName + ",属性值：" + fieldValue);
                } catch (IllegalArgumentException e) {
                    log.error(e.getMessage(), e);
                } catch (IllegalAccessException e) {
                    log.error(e.getMessage(), e);
                }
                if (fieldValue != null && fieldValue != "") {  //只要有一个属性值不为null 就返回false 表示对象不为null
                    flag = true;
                    break;
                }
            }
        }

        return flag;
    }



    @ApiLog(value = "导出用户信息", type = LogTypeEnum.EXPORT)
    @GetMapping("export")
    //@PreAuthorize ("hasAuthority('cw_finance:invoice:export')")
    @ApiOperation(value = "导出用户信息")
    public void exportFile(StaffUserInfoDTO userInfoDTO, Page <StaffUserInfoDTO> page, ExcelOptions options, HttpServletResponse response) throws Exception {
        String fileName = options.getFilename();
        String sheetName = options.getSheetName();
        List<StaffUserInfoDTO> result = new ArrayList<>();
        if ( ExportMode.current.equals ( options.getMode() ) ) {
            result = staffUserInfoService.findPageList(userInfoDTO,page).getRecords();
        } else if (ExportMode.selected.equals ( options.getMode() )) {
            result = staffUserInfoService.findPageList(userInfoDTO,page).getRecords().stream ( ).filter ( item ->
                    options.getSelectIds ( ).contains ( item.getId ( ) )
            ).collect ( Collectors.toList ( ) );
        } else {
            page.setSize (-1);
            page.setCurrent (0);
            result = staffUserInfoService.findPageList(userInfoDTO,page).getRecords();
        }
        EasyPoiUtil.exportExcel ( result, sheetName,  sheetName, StaffUserInfoDTO.class, fileName, response );

    }

    /**
     * 根据id查询转正信息
     */
    @ApiOperation(value = "根据id查询转正信息")
    @GetMapping(value = "findByApplyId")
    public ResponseEntity<RegularApply> findByApplyId(@RequestParam String id){
        RegularApply regularApply =staffUserInfoService.findByApplyId(id);
        return ResponseEntity.ok(regularApply);
    }

    /**
     * 保存/修改  转正信息
     */
    @ApiOperation(value = "保存/修改  转正信息")
    @PostMapping(value = "/saveApplyForm")
    public ResponseEntity saveApplyForm(@RequestBody RegularApply regularApply) throws Exception{
        RegularApply apply= staffUserInfoService.saveApplyForm(regularApply);
        return ResponseUtil.newInstance().add("businessTable", "jy_regular_apply").add("businessId", apply.getId()).add("isPass",apply.getIsPass()).add("isEmploy",apply.getIsEmploy()).ok ("操作成功");
    }

    /**
     * 根据id修改转正状态status
     * @param
     */
    @ApiOperation(value = "根据id修改转正状态status")
    @PostMapping(value = "/updateStatusByApplyId")
    public void updateStatusByApplyId(@RequestBody RegularApply regularApply) {
        staffUserInfoService.updateStatusByApplyId(regularApply);
    }

    /**
     * 获取试用期的所有人员信息
     */
    @GetMapping(value = "/getList")
    public String getList() throws Exception {
        List<StaffUserInfoDTO> pageList=staffUserInfoService.getList();
        return JSON.toJSONString(pageList);
    }

    /**
     * 根据联系电话进行判重
     */
    @ApiOperation(value = "根据联系电话进行判重")
    @GetMapping(value = "/getByPhone")
    public boolean getByPhone(String mobilePhone) {
        boolean data=staffUserInfoService.getByPhone(mobilePhone);
        return data;
    }







}
