package cn.timer.api.controller.zpgl;

import cn.hutool.core.util.StrUtil;
import cn.timer.api.bean.clazz.NationClass;
import cn.timer.api.bean.kqgl.UserEquiRelation;
import cn.timer.api.bean.kqmk.*;
import cn.timer.api.bean.qyzx.QyzxEmpEntAsso;
import cn.timer.api.bean.qyzx.QyzxEmpLogin;
import cn.timer.api.bean.qyzx.businessService.QyzxOrderRecord;
import cn.timer.api.bean.spmk.SpmkCustomApproval;
import cn.timer.api.bean.wechat.MessageTemplate;
import cn.timer.api.bean.yggl.YgglMainEmp;
import cn.timer.api.bean.zpgl.*;
import cn.timer.api.config.annotation.CurrentUser;
import cn.timer.api.config.annotation.UserBean;
import cn.timer.api.config.enuminterface.JxglEnumInterface;
import cn.timer.api.config.enums.CommonEnum;
import cn.timer.api.config.enums.SysRoleType;
import cn.timer.api.config.exception.CustomException;
import cn.timer.api.controller.kqgl.ClockInTool;
import cn.timer.api.controller.kqgl.atttimer.RealTimeUpdate;
import cn.timer.api.controller.zpgl.sevice.ZpglService;
import cn.timer.api.controller.zpgl.sevice.ZpglWxgzptService;
import cn.timer.api.dao.kqgl.UserEquiRelationMapper;
import cn.timer.api.dao.kqmk.KqglAssoKqzdkfsMapper;
import cn.timer.api.dao.qyzx.QyzxEmpLoginMapper;
import cn.timer.api.dao.yggl.YgglMainEmpMapper;
import cn.timer.api.dao.zpgl.ZpglRcxxMapper;
import cn.timer.api.dto.template.InterviewNotice;
import cn.timer.api.dto.zpgl.ImportCandidateDto;
import cn.timer.api.dto.zpgl.ZpglRcxxDto;
import cn.timer.api.dto.zpgl.ZpglRcxxEntryDto;
import cn.timer.api.utils.Md5;
import cn.timer.api.utils.Result;
import cn.timer.api.utils.ResultUtil;
import cn.timer.api.utils.ZpglMessageTemplate;
import cn.timer.api.utils.query.BaseQuery;
import cn.timer.api.config.enuminterface.YgEnumInterface.jobStatus;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.yulichang.query.MPJQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 招聘管理
 *
 * @author wuqingjun
 * @email 284718418@qq.com
 * @date 2022-03-08 15:14:40
 */
@Api(tags = "招聘管理")
@Transactional(rollbackOn = Exception.class)
@RestController
@RequestMapping(value = "/zpgl", produces = {"application/json"})
@Slf4j
public class ZpglController {

    @Value(value = "${config-8timer.init-password}")
    private String pwd;
    // 回调地址
    @Value("${config-8timer.machine8timerUrl}")
    public String mac_command;
    @Autowired
    private KqglAssoKqzdkfsMapper kqglassokqzdkfsmapper;
    @Autowired
    private QyzxEmpLoginMapper qyzxEmpLoginMapper;
    @Autowired
    private RealTimeUpdate realtimeupdate;
    @Autowired
    private UserEquiRelationMapper userequirelationmapper;
    @Autowired
    private YgglMainEmpMapper ygglMainEmpMapper;
    @Autowired
    private ZpglService zpglService;
    @Autowired
    private ZpglRcxxMapper zpglRcxxMapper;
    @Autowired
    private ZpglWxgzptService zpglWxgzptService;
    /**
     * 0应聘登记
     */
    public static final int APPLY_STATUS = 0;
    /**
     * 1测评
     */
    public static final int CP_STATUS = 1;
    @Value("${h5.url}")
    private String h5Url;

    /**
     * 招聘-招聘中
     *
     * @param
     * @return
     */
    @GetMapping(value = "/recruit")
    @ApiOperation(value = "1.招聘列表", httpMethod = "GET", notes = "招聘列表")
    @ApiOperationSupport(order = 1)
    public Result<Object> recruit(@CurrentUser UserBean userBean, BaseQuery baseQuery,
                                  @ApiParam("搜索关键字") @RequestParam(required = false) String query,
                                  @ApiParam("职位ID") @RequestParam(required = false) Integer zpglZwxxId,
                                  @ApiParam("状态") @RequestParam(required = false) Integer status) {
        try {
            Page<ZpglRcxx> page = new Page<ZpglRcxx>(baseQuery.getPageNum(), baseQuery.getPageSize());
            QueryWrapper<ZpglRcxx> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(ZpglRcxx::getOrgCode, userBean.getOrgCode()).eq(ZpglRcxx::getDeleteFlag, 0);
            if (!StringUtils.isEmpty(zpglZwxxId) && zpglZwxxId > 0) {
                queryWrapper.lambda().eq(ZpglRcxx::getZpglZwxxId, zpglZwxxId);
            }
            if (!StringUtils.isEmpty(query)) {
                queryWrapper.lambda().and(qw -> qw.like(ZpglRcxx::getName, query).or().eq(ZpglRcxx::getMobile, query).or().eq(ZpglRcxx::getMail, query));
            }
            queryWrapper.lambda().eq(ZpglRcxx::getStatus, status).orderByDesc(ZpglRcxx::getUpdateTime);
            IPage<ZpglRcxx> zpglRcxxPage = ZpglRcxx.builder().build().selectPage(page, queryWrapper);
            List<ZpglRcxx> zpglRcxxs = page.getRecords();
            zpglRcxxPage.getCurrent();
            zpglRcxxPage.getPages();
            zpglRcxxPage.getTotal();
            zpglRcxxPage.getSize();
            Map<String, Object> map = new HashMap<>(9);
            map.put("zpglRcxxs", zpglRcxxs);
            map.put("FILTERING", this.getNum(queryWrapper, JxglEnumInterface.ResumeStatus.FILTERING.getType(), userBean.getOrgCode()));
            map.put("FILTER_PASS", this.getNum(queryWrapper, JxglEnumInterface.ResumeStatus.FILTER_PASS.getType(), userBean.getOrgCode()));
            map.put("INTERVIEW", this.getNum(queryWrapper, JxglEnumInterface.ResumeStatus.INTERVIEW.getType(), userBean.getOrgCode()));
            map.put("INTERVIEWED", this.getNum(queryWrapper, JxglEnumInterface.ResumeStatus.INTERVIEWED.getType(), userBean.getOrgCode()));
            map.put("INTERVIEW_PASS", this.getNum(queryWrapper, JxglEnumInterface.ResumeStatus.INTERVIEW_PASS.getType(), userBean.getOrgCode()));
            map.put("EMPLOY", this.getNum(queryWrapper, JxglEnumInterface.ResumeStatus.EMPLOY.getType(), userBean.getOrgCode()));
            map.put("OFFER", this.getNum(queryWrapper, JxglEnumInterface.ResumeStatus.OFFER.getType(), userBean.getOrgCode()));
            map.put("ENTRYING", this.getNum(queryWrapper, JxglEnumInterface.ResumeStatus.ENTRYING.getType(), userBean.getOrgCode()));
            return ResultUtil.data(zpglRcxxPage, map, "搜索成功");

        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("招聘-招聘列表失败");
        }

    }

    /**
     * 招聘-招聘中-职位信息
     *
     * @param
     * @return
     */
    @GetMapping(value = "/zwxx/{deleteFlag}")
    @ApiOperation(value = "2.职位信息", httpMethod = "GET", notes = "职位信息deleteFlag:0")
    @ApiOperationSupport(order = 2)
    public Result<Object> zwxx(@CurrentUser UserBean userBean, @PathVariable Integer deleteFlag) {
        try {
            QueryWrapper<ZpglZwxx> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(ZpglZwxx::getOrgCode, userBean.getOrgCode());
            if (deleteFlag.intValue() == 1) {
                queryWrapper.lambda().eq(ZpglZwxx::getDeleteFlag, 0).gt(ZpglZwxx::getEndTime,new Date());
            }
            List<ZpglZwxx> zpglZwxxs = ZpglZwxx.builder().build().selectList(queryWrapper);
            return ResultUtil.data(zpglZwxxs, "查询成功");
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("招聘-职位信息失败");
        }
    }

    /**
     * 招聘-变更人才信息状态
     *
     * @param
     * @return
     */
    @PostMapping(value = "/operation")
    @ApiOperation(value = "3.招聘-变更人才信息状态", httpMethod = "POST", notes = "招聘-变更人才信息状态")
    @ApiOperationSupport(order = 3)
    public Result<Object> operation(@CurrentUser UserBean userBean, @RequestBody ZpglRcxxDto zpglRcxxDto) {
        try {
            return zpglService.updateZpglRcxx(userBean, zpglRcxxDto) ? ResultUtil.success() : ResultUtil.error();
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("招聘-变更状态失败");
        }
    }


    /**
     * 添加员工档案
     *
     * @param userBean
     * @param addygdaDto
     * @return
     */
    @PostMapping(value = "/addygda")
    @ApiOperation(value = "4.招聘-确认入职添加员工档案", httpMethod = "POST", notes = "接口发布说明")
    @ApiOperationSupport(order = 4)
    public Result<Object> addygda(@CurrentUser UserBean userBean, @Validated @RequestBody ZpglRcxxEntryDto addygdaDto) {
        try {
            ZpglRcxx zpglRcxx = ZpglRcxx.builder().id(addygdaDto.getId()).build().selectById();
            if (StringUtils.isEmpty(zpglRcxx)) {
                return ResultUtil.error("确认入职添加员工档案失败");
            }

            Integer orgCode = userBean.getOrgCode();
            //自定义工号
            String customNum = addygdaDto.getCustomNum();
            String name = addygdaDto.getName();
            String phone = zpglRcxx.getMobile();
            String zjNum = zpglRcxx.getIdCard();
            //考勤组id
            Integer attgroupid = addygdaDto.getAttgroupid();

            Integer jobType = addygdaDto.getJobType();
            Date rzTime = addygdaDto.getRzTime() == null ? new Date() : addygdaDto.getRzTime();
            Integer syq = addygdaDto.getSyq();
            Integer sex = addygdaDto.getSex();
            Integer bmgwId = addygdaDto.getBmgwId();
            ZpglRcxxDto zpglRcxxDto = new ZpglRcxxDto();
            zpglRcxxDto.setId(zpglRcxx.getId());
            zpglRcxxDto.setStatus(addygdaDto.getStatus());
            zpglRcxxDto.setZpglZwxxId(zpglRcxx.getZpglZwxxId());

            QyzxEmpLogin login = new LambdaQueryChainWrapper<QyzxEmpLogin>(qyzxEmpLoginMapper)
                    .eq(!StrUtil.hasBlank(phone), QyzxEmpLogin::getPhone, phone).one();
            if (login == null) {
                // 初始化密码 pwd
                login = QyzxEmpLogin.builder().phone(phone).pw(Md5.md5(pwd))
                        .sts(CommonEnum.U_STS_ON.getType()).orgId(userBean.getOrgCode()).username(name).build();
                if (!login.insert()) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return ResultUtil.error("添加员工登录表失败,请检查输入信息");
                }
            }

            YgglMainEmp ygglMainEmp = ygglMainEmpMapper.selectOne(new QueryWrapper<YgglMainEmp>().lambda()
                    .eq(YgglMainEmp::getPhone, phone).eq(YgglMainEmp::getOrgCode, orgCode));
            if (!StringUtils.isEmpty(ygglMainEmp)) {
                return ResultUtil.error("该手机号已被使用,请输入正确手机号");
            }
            QyzxEmpEntAsso.builder().empNum(login.getId()).orgCode(orgCode).userType(SysRoleType.U_TYPE_EMP.getType())
                    .status(CommonEnum.U_STS_ON.getType()).build().insert();
            ygglMainEmp = YgglMainEmp.builder().name(name).phone(phone).zjType(addygdaDto.getZjType()).zjNum(zjNum).jobType(jobType)
                    .jobStatus(jobStatus.SHIYONG.getType()).rzTime(rzTime).syq(syq).sex(sex)
                    .empNum(login.getId()).orgCode(orgCode).bmgwId(bmgwId).customNum(customNum).build();

            if (addygdaDto.getAttgroupid() != null) {
                KqglAssoYhkqz.builder().kqzid(attgroupid).userid(login.getId()).qyid(userBean.getOrgCode()).build().insert();

                List<KqglAssoKqzdkfs> kqjs = kqglassokqzdkfsmapper.selectList(new QueryWrapper<KqglAssoKqzdkfs>().lambda().eq(KqglAssoKqzdkfs::getKqzId, addygdaDto.getAttgroupid()).eq(KqglAssoKqzdkfs::getType, 1));

                for (KqglAssoKqzdkfs abp : kqjs) {
                    KqglAssoKqj kqj = KqglAssoKqj.builder().id(abp.getDkfsid()).build().selectById();
                    KqglAssoYhsb kqjry = KqglAssoYhsb.builder().build().selectOne(new QueryWrapper<KqglAssoYhsb>().lambda().eq(KqglAssoYhsb::getUserId, login.getId()).eq(KqglAssoYhsb::getKqjid, kqj.getId()));
                    if (kqjry == null) {
                        String url = mac_command + "/addUserName";
                        HttpHeaders headers = new HttpHeaders();
                        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
                        params.add("devId", kqj.getCode());
                        params.add("userId", login.getId());
                        params.add("userName", ygglMainEmp.getName());
                        RestTemplate restTemplate = new RestTemplate();
                        HttpEntity httpEntity = new HttpEntity(params, headers);
                        ResponseEntity<String> request = restTemplate.postForEntity(url, httpEntity, String.class);

                        KqglAssoYhsb.builder().build().delete(new QueryWrapper<KqglAssoYhsb>().lambda().eq(KqglAssoYhsb::getUserId, login.getId()).eq(KqglAssoYhsb::getKqjid, kqj.getId()));

                        KqglAssoYhsb uskqj = KqglAssoYhsb.builder().userId(login.getId()).kqjid(kqj.getId()).type(1).build();

                        UserEquiRelation isgly = userequirelationmapper.selectByuserId(login.getId());
                        if (isgly != null) {
                            uskqj.setIsGly(isgly.getIsGly());
                        } else {
                            uskqj.setIsGly(0);
                        }
                        if (!uskqj.insert()) {
                            return ResultUtil.error("操作失败--新增用户与设备关系");
                        }
                    }
                }

            }

            if (syq == 0) {
                ygglMainEmp.setZzTime(rzTime);
            } else {

                String sdf = new SimpleDateFormat("yyyy-MM-dd").format(rzTime);

                String zztime = ClockInTool.requires_extra_times(sdf, syq, 4, 1);

                ygglMainEmp.setZzTime(ClockInTool.strToDateLong(zztime));
            }
            // 人才信息同步至员工档案
            this.copyToYgglMainEmp(zpglRcxx,ygglMainEmp);

            ygglMainEmp.insert();

            //假期规则初始化
            String current_time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            List<KqglAssoLeaveRules> rul = KqglAssoLeaveRules.builder().build().selectList(new QueryWrapper<KqglAssoLeaveRules>().lambda().eq(KqglAssoLeaveRules::getOrgCode, orgCode));
            for (KqglAssoLeaveRules r : rul) {
                if (r.getLeaveBalance() == 0) {
                    KqglAssoLeaveEmployeeBalance.builder().leaveRulesId(r.getId()).userid(ygglMainEmp.getEmpNum()).balanceDays(-1).modifyUserid(userBean.getEmpNum()).modifyTimer(current_time).orgCode(userBean.getOrgCode()).build().insert();
                } else {
                    KqglAssoLeaveEmployeeBalance.builder().leaveRulesId(r.getId()).userid(ygglMainEmp.getEmpNum()).balanceDays(0.0).modifyUserid(userBean.getEmpNum()).modifyTimer(current_time).orgCode(userBean.getOrgCode()).build().insert();
                }
            }
            /**
             * 职位信息已入职人数+1
             * 招聘-变更人才信息状态
             * 添加面试流程记录
             * 维护微信公众平台表
             */
            zpglService.updateZpglOther(userBean, zpglRcxxDto, ygglMainEmp.getId());
            try {
                realtimeupdate.AttendanceTask(userBean.getOrgCode(), ygglMainEmp.getEmpNum(), 2, null);
            } catch (ParseException e) {
                e.printStackTrace();
            }

            return ResultUtil.success("确认入职成功!");

        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("招聘-确认入职失败");
        }

    }

    /**
     * 招聘-已淘汰
     *
     * @param
     * @return
     */
    @GetMapping(value = "/recruit/fail")
    @ApiOperation(value = "5.招聘-已淘汰列表", httpMethod = "GET", notes = "招聘-已淘汰列表")
    @ApiOperationSupport(order = 5)
    public Result<Object> recruitFail(@CurrentUser UserBean userBean, BaseQuery baseQuery,
                                      @ApiParam("搜索关键字") @RequestParam(required = false) String query,
                                      @ApiParam("职位ID") @RequestParam(required = false) Integer zpglZwxxId,
                                      @ApiParam("状态") @RequestParam(required = false) Integer status,
                                      @ApiParam("排序") @RequestParam(required = false) Integer orderBy) {
        try {
            Page<ZpglRcxx> page = new Page<ZpglRcxx>(baseQuery.getPageNum(), baseQuery.getPageSize());
            MPJQueryWrapper<ZpglRcxx> queryWrapper = new MPJQueryWrapper<>();
            queryWrapper.selectAll(ZpglRcxx.class).select("zf.fail_cause")
                    .leftJoin("zpgl_fail zf on t.zpgl_fail_id = zf.id");
            queryWrapper.eq("t.org_code", userBean.getOrgCode()).eq("t.delete_flag", 0).eq("zf.org_code", userBean.getOrgCode());
            if (!StringUtils.isEmpty(zpglZwxxId) && zpglZwxxId > 0) {
                queryWrapper.eq("t.zpgl_zwxx_id", zpglZwxxId);
            }
            if (!StringUtils.isEmpty(query)) {
                queryWrapper.and(qw -> qw.like("t.name", query).or().eq("t.mobile", query).or().eq("t.mail", query));
            }
            if (!StringUtils.isEmpty(status)) {
                queryWrapper.eq("t.status", 9);
                queryWrapper.eq("zf.zpgl_rcxx_status", status);
            } else {
                queryWrapper.eq("t.ifrck", 1);
            }
            if (!StringUtils.isEmpty(orderBy)) {
                // 排序 1最近跟进时间 2最近入库时间 3最早入库时间
                if (orderBy.intValue() == 1) {
                    queryWrapper.orderByDesc("t.update_time");
                } else if (orderBy.intValue() == 2) {
                    queryWrapper.orderByDesc("t.ifrck_time");
                } else if (orderBy.intValue() == 3) {
                    queryWrapper.orderByAsc("t.ifrck_time");
                }
            }

            IPage<ZpglRcxx> zpglRcxxPage = zpglRcxxMapper.selectJoinPage(page, ZpglRcxx.class, queryWrapper);
            List<ZpglRcxx> zpglRcxxs = page.getRecords();
            zpglRcxxPage.getCurrent();
            zpglRcxxPage.getPages();
            zpglRcxxPage.getTotal();
            zpglRcxxPage.getSize();
            return ResultUtil.data(zpglRcxxPage, zpglRcxxs, "搜索成功");

        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("招聘-已淘汰,人才库列表失败");
        }

    }

    /**
     * 招聘-移入/出人才库
     *
     * @param
     * @return
     */
    @PostMapping(value = "/remove/{id}/{ifrck}")
    @ApiOperation(value = "6.招聘-移入/出人才库", httpMethod = "GET", notes = "招聘-移入/出人才库")
    @ApiOperationSupport(order = 6)
    public Result<Object> remove(@CurrentUser UserBean userBean, @PathVariable Integer id, @PathVariable Integer ifrck) {
        try {
            return ZpglRcxx.builder().id(id).ifrck(ifrck).ifrckTime(new Date()).userId(userBean.getEmpNum()).build().updateById() ? ResultUtil.success("操作成功") : ResultUtil.error("操作失败");
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("招聘-删除人才信息失败");
        }

    }

    /**
     * 招聘-导入候选人简历
     *
     * @param userBean
     * @param file
     * @param request
     * @return
     */
    @ResponseBody
    @PostMapping("/resume_import_candidate")
    @ApiOperation(value = "7.招聘-导入候选人简历", httpMethod = "POST", notes = "招聘-导入候选人简历")
    @ApiOperationSupport(order = 7)
    public Result<Object> resumeImportCandidate(@CurrentUser UserBean userBean, @RequestParam(required = true) MultipartFile file,
                                                @ApiParam("招聘渠道ID") @RequestParam(required = false) Integer zpglZpqdId,
                                                @ApiParam("职位信息Id") @RequestParam(required = true) Integer zpglZwxxId,
                                                @ApiParam("状态") @RequestParam(required = true) Integer status, HttpServletRequest request) {
        try {
            ImportCandidateDto importCandidateDto = new ImportCandidateDto();
            importCandidateDto.setStatus(status);
            importCandidateDto.setZpglZpqdId(zpglZpqdId);
            importCandidateDto.setZpglZwxxId(zpglZwxxId);
            // 获取文件 文档类型,目前支持pdf,doc,docx,wps,txt,jpg,jpeg,png,bmp,tif格式
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
            if (StringUtils.isEmpty(suffix)) {
                return ResultUtil.error("导入简历失败,请检查是否为简历文件~");
            }
            if ("pdf,doc,docx,wps,txt,jpg,jpeg,png,bmp,tif".indexOf(suffix) == -1) {
                return ResultUtil.error("导入简历失败,目前支持pdf,doc,docx,wps,txt,jpg,jpeg,png,bmp,tif格式~");
            }
            importCandidateDto.setSuffix(suffix);
//             return zpglService.addResumeImportCandidate(userBean, file, importCandidateDto);
            return zpglService.addCandidateByResumeSDK(userBean, file, importCandidateDto);
        } catch (CustomException e) {
            e.printStackTrace();
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("招聘-导入候选人简历失败");
        }

    }

    /**
     * 招聘-更改招聘职位
     *
     * @param
     * @return
     */
    @PostMapping(value = "/edit/zwxx")
    @ApiOperation(value = "8.招聘-更改招聘职位", httpMethod = "POST", notes = "招聘-更改招聘职位")
    @ApiOperationSupport(order = 8)
    public Result<Object> deitZwxx(@CurrentUser UserBean userBean, @RequestBody ZpglRcxxDto zpglRcxxDto) {
        try {
            return zpglService.updateZpglRcxxZwxx(userBean, zpglRcxxDto) ? ResultUtil.success("更改招聘职位成功") : ResultUtil.error("更改招聘职位失败");
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("招聘-更改招聘职位失败");
        }
    }

    /**
     * 招聘-标准简历信息
     *
     * @param
     * @return
     */
    @GetMapping(value = "/standard/recruit")
    @ApiOperation(value = "9.招聘-标准简历信息", httpMethod = "GET", notes = "招聘-标准简历信息")
    @ApiOperationSupport(order = 9)
    public Result<Object> standardRecruit(@CurrentUser UserBean userBean,
                                          @ApiParam("人才信息ID") @RequestParam(required = false) Integer zpglRcxxId) {
        try {
            ZpglRcxx zpglRcxx = ZpglRcxx.builder().id(zpglRcxxId).build().selectById();
            zpglRcxx.setNationName(NationClass.builder().id(zpglRcxx.getNationClassId()).build().selectById().getName());
            // 工作经验
            List<ZpglRcxxExperience> zpglRcxxExperiences = ZpglRcxxExperience.builder().build().selectList(
                    new QueryWrapper<ZpglRcxxExperience>().lambda().eq(ZpglRcxxExperience::getZpglRcxxId, zpglRcxxId)
                            .eq(ZpglRcxxExperience::getIsDelete, 0).orderByDesc(ZpglRcxxExperience::getEndTime)
            );
            // 教育经历
            List<ZpglRcxxStudy> zpglRcxxStudys = ZpglRcxxStudy.builder().build().selectList(
                    new QueryWrapper<ZpglRcxxStudy>().lambda().eq(ZpglRcxxStudy::getZpglRcxxId, zpglRcxxId)
                            .eq(ZpglRcxxStudy::getIsDelete, 0).orderByDesc(ZpglRcxxStudy::getEndTime)
            );
            // 项目经历
            List<ZpglRcxxProject> zpglRcxxProjects = ZpglRcxxProject.builder().build().selectList(
                    new QueryWrapper<ZpglRcxxProject>().lambda().eq(ZpglRcxxProject::getZpglRcxxId, zpglRcxxId)
                            .eq(ZpglRcxxProject::getDeleteFlag, 0).orderByDesc(ZpglRcxxProject::getEndTime)
            );
            // 培训经验
            List<ZpglRcxxTrain> zpglRcxxTrains = ZpglRcxxTrain.builder().build().selectList(
                    new QueryWrapper<ZpglRcxxTrain>().lambda().eq(ZpglRcxxTrain::getZpglRcxxId, zpglRcxxId)
                            .eq(ZpglRcxxTrain::getIsDelete, 0).orderByDesc(ZpglRcxxTrain::getEndTime)
            );
            // 家庭资料
            List<ZpglRcxxJtzl> zpglRcxxJtzls = ZpglRcxxJtzl.builder().build().selectList(
                    new QueryWrapper<ZpglRcxxJtzl>().lambda().eq(ZpglRcxxJtzl::getZpglRcxxId, zpglRcxxId)
                            .eq(ZpglRcxxJtzl::getIsDelete, 0).orderByDesc(ZpglRcxxJtzl::getCreateTime)
            );

            // FPA性格测评数据
            ZpglDtk zpglDtk = ZpglDtk.builder().build().selectOne(new QueryWrapper<ZpglDtk>().lambda().eq(ZpglDtk::getZpglRcxxId, zpglRcxxId));

            // offer
            ZpglRcxxOffer zpglRcxxOffer = ZpglRcxxOffer.builder().build().selectOne(new QueryWrapper<ZpglRcxxOffer>().lambda().eq(ZpglRcxxOffer::getZpglRcxxId, zpglRcxxId).eq(ZpglRcxxOffer::getDeleteFlag, 0).orderByDesc(ZpglRcxxOffer::getCreateTime));

            Map<String, Object> map = new HashMap<>(7);
            map.put("zpglRcxx", zpglRcxx);
            map.put("zpglRcxxExperiences", zpglRcxxExperiences);
            map.put("zpglRcxxStudys", zpglRcxxStudys);
            map.put("zpglRcxxProjects", zpglRcxxProjects);
            map.put("zpglRcxxTrains", zpglRcxxTrains);
            map.put("zpglDtk", zpglDtk);
            map.put("zpglRcxxOffer", zpglRcxxOffer);
            map.put("zpglRcxxJtzls",zpglRcxxJtzls);
            return ResultUtil.data(map, "搜索成功");

        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("获取招聘-标准简历信息失败");
        }

    }

    /**
     * 招聘-发起录用审批选择
     *
     * @param
     * @return
     */
    @GetMapping(value = "/custom_approval")
    @ApiOperation(value = "10.招聘-发起录用审批选择", httpMethod = "GET", notes = "招聘-发起录用审批选择")
    @ApiOperationSupport(order = 10)
    public Result<Object> customApproval(@CurrentUser UserBean userBean) {
        try {
            List<SpmkCustomApproval> spmkCustomApprovals = SpmkCustomApproval.builder().build().selectList(
                    new QueryWrapper<SpmkCustomApproval>().select("id", "name")
                            .lambda().eq(SpmkCustomApproval::getOrgCode, userBean.getOrgCode())
                            .eq(SpmkCustomApproval::getAssoType, 10)
            );
            return ResultUtil.data(spmkCustomApprovals);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("获取招聘-发起录用审批选择信息失败");
        }

    }

    /**
     * 招聘-发起应聘登记或者测评 status:0应聘登记,1测评
     *
     * @param
     * @return
     */
    @GetMapping(value = "/send_apply_cp/{id}/{status}")
    @ApiOperation(value = "11.招聘-发起应聘登记或者测评", httpMethod = "GET", notes = "status:0应聘登记,1测评")
    @ApiOperationSupport(order = 11)
    public Result<Object> sendApplyOrCp(@CurrentUser UserBean userBean, @PathVariable Integer id, @PathVariable Integer status) {
        try {
            ZpglRcxx zpglRcxx = ZpglRcxx.builder().id(id).build().selectById();
            if (StringUtils.isEmpty(zpglRcxx)) {
                log.error("招聘-发起应聘登记或测评:id={} 空数据", id);
                return ResultUtil.error("操作失败~");
            }
            InterviewNotice interviewNotice = new InterviewNotice();
            ZpglZwxx zpglZwxx = ZpglZwxx.builder().id(zpglRcxx.getZpglZwxxId()).build().selectById();
            if (!StringUtils.isEmpty(zpglZwxx)) {
                interviewNotice.setZpglZwxxName(zpglZwxx.getName());
            }
            interviewNotice.setName(zpglRcxx.getName());
            interviewNotice.setEmail(zpglRcxx.getMail());
            //公众号类型 1:8小时企业管理 2:优领人才网
            interviewNotice.setWxgzhType(1);
            //0 即时发送,1 定时发送
            interviewNotice.setTiming(0);
            interviewNotice.setType(JxglEnumInterface.NoticeWay.WECHAT_PUBLIC.getType());
            interviewNotice.setInterviewTime(new Date());
            // 通知面试者
            interviewNotice.setZpglRcxxId(zpglRcxx.getId());
            interviewNotice.setMobile(zpglRcxx.getMobile());
            interviewNotice.setNoticeName(userBean.getQyzxEmpLogin().getUsername());
            interviewNotice.setRemark("请点击详情填写");
            interviewNotice.setTemplateId(MessageTemplate.TEMPLATE_ID_TO_INTERVIEWE);
            // 发送应聘登记表消息
            if (APPLY_STATUS == status.intValue()) {
                interviewNotice.setContentNotice(ZpglMessageTemplate.TO_APPLY);
                interviewNotice.setContentStr(ZpglMessageTemplate.print(ZpglMessageTemplate.THANKS, new String[]{zpglRcxx.getName(),interviewNotice.getZpglZwxxName()}));
                interviewNotice.setUrl(h5Url + "?zpglRcxxId="+zpglRcxx.getId()+"&mobile=" + zpglRcxx.getMobile() + "&orgId=" + userBean.getOrgCode() + "#/basicInfo");
            // 发送FPA测评消息
            } else {
                interviewNotice.setContentNotice(ZpglMessageTemplate.TO_CEPIN);
                interviewNotice.setContentStr(ZpglMessageTemplate.print(ZpglMessageTemplate.THANKS, new String[]{zpglRcxx.getName(),interviewNotice.getZpglZwxxName()}));
                interviewNotice.setUrl(h5Url + "/?zpglRcxxId=" + zpglRcxx.getId()+ "&orgId=" + userBean.getOrgCode() + "#/cpxt");
            }
            log.info("TO_INTERVIEWEE sendApplyOrCePin MessageQueue info:{}", zpglWxgzptService.sendApplyOrCePin(interviewNotice));
            return ResultUtil.success();
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("操作失败");
        }

    }
    /**
     * 招聘-逻辑删除人才信息
     *
     * @param
     * @return
     */
    @PostMapping(value = "/edit/{id}")
    @ApiOperation(value = "12.招聘-删除人才信息", httpMethod = "GET", notes = "删除人才信息")
    @ApiOperationSupport(order = 12)
    public Result<Object> edit(@CurrentUser UserBean userBean, @PathVariable Integer id) {
        try {
            return ZpglRcxx.builder().id(id).deleteFlag(1).userId(userBean.getEmpNum()).build().updateById() ? ResultUtil.success("操作成功") : ResultUtil.error("操作失败");
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("招聘-删除人才信息失败");
        }

    }
    /**
     * 招聘-人才库
     *
     * @param
     * @return
     */
    @GetMapping(value = "/recruit/envelope")
    @ApiOperation(value = "13.招聘-人才库列表", httpMethod = "GET", notes = "招聘-人才库列表")
    @ApiOperationSupport(order = 13)
    public Result<Object> envelope(@CurrentUser UserBean userBean, BaseQuery baseQuery,
                                   @ApiParam("搜索关键字") @RequestParam(required = false) String query,
                                   @ApiParam("职位ID") @RequestParam(required = false) Integer zpglZwxxId,
                                   @ApiParam("状态") @RequestParam(required = false) Integer status,
                                   @ApiParam("排序") @RequestParam(required = false) Integer orderBy) {
        try {
            Page<ZpglRcxx> page = new Page<ZpglRcxx>(baseQuery.getPageNum(), baseQuery.getPageSize());
            QueryWrapper<ZpglRcxx> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("org_code", userBean.getOrgCode()).eq("delete_flag", 0);
            if (!StringUtils.isEmpty(zpglZwxxId) && zpglZwxxId > 0) {
                queryWrapper.eq("zpgl_zwxx_id", zpglZwxxId);
            }
            if (!StringUtils.isEmpty(query)) {
                queryWrapper.and(qw -> qw.like("name", query).or().eq("mobile", query).or().eq("mail", query));
            }
            queryWrapper.eq("ifrck", 1);
            if (!StringUtils.isEmpty(orderBy)) {
                // 排序 1最近跟进时间 2最近入库时间 3最早入库时间
                if (orderBy.intValue() == 1) {
                    queryWrapper.orderByDesc("update_time");
                } else if (orderBy.intValue() == 2) {
                    queryWrapper.orderByDesc("ifrck_time");
                } else if (orderBy.intValue() == 3) {
                    queryWrapper.orderByAsc("ifrck_time");
                }
            }else {
                queryWrapper.orderByDesc("update_time");
            }

            IPage<ZpglRcxx> zpglRcxxPage = ZpglRcxx.builder().build().selectPage(page, queryWrapper);
            List<ZpglRcxx> zpglRcxxs = page.getRecords();
            for (ZpglRcxx entity : zpglRcxxs) {
                if(!StringUtils.isEmpty(entity.getZpglFailId()) && entity.getZpglFailId()>0){
                    ZpglFail fail = ZpglFail.builder().id(entity.getZpglFailId()).build().selectById();
                    entity.setFailCause(fail.getFailCause());
                }
            }
            zpglRcxxPage.getCurrent();
            zpglRcxxPage.getPages();
            zpglRcxxPage.getTotal();
            zpglRcxxPage.getSize();
            return ResultUtil.data(zpglRcxxPage, zpglRcxxs, "搜索成功");

        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("招聘-已淘汰,人才库列表失败");
        }

    }

    /**
     * 获取统计数据
     *
     * @param queryWrapper
     * @param status
     * @param orgCode
     * @return
     */
    private Integer getNum(QueryWrapper<ZpglRcxx> queryWrapper, Integer status, Integer orgCode) {
        queryWrapper.clear();
        queryWrapper.lambda().eq(ZpglRcxx::getOrgCode, orgCode).eq(ZpglRcxx::getDeleteFlag, 0);
        return ZpglRcxx.builder().build().selectCount(queryWrapper.lambda().eq(ZpglRcxx::getStatus, status));
    }

    /**
     * 人才信息同步至员工档案
     * @param source
     * @param target
     */
    private void copyToYgglMainEmp(ZpglRcxx source,YgglMainEmp target){
        if(!StringUtils.isEmpty(source.getMail())){
            target.setWorkEmail(source.getMail());
        }
        if(!StringUtils.isEmpty(source.getDatebirth())){
            target.setBirthday(source.getDatebirth());
        }
        if(!StringUtils.isEmpty(source.getBmgwId())){
            target.setBmgwId(source.getBmgwId());
        }
        if(!StringUtils.isEmpty(source.getProvinceId())){
            target.setProvinceId(source.getProvinceId());
        }
        if(!StringUtils.isEmpty(source.getProvince())){
            target.setProvince(source.getProvince());
        }
        if(!StringUtils.isEmpty(source.getDistrictId())){
            target.setDistrictId(source.getDistrictId());
        }
        if(!StringUtils.isEmpty(source.getDistrict())){
            target.setDistrict(source.getDistrict());
        }

        if(!StringUtils.isEmpty(source.getCityId())){
            target.setCityId(source.getCityId());
        }
        if(!StringUtils.isEmpty(source.getCity())){
            target.setCityId(source.getCity());
        }
        if(!StringUtils.isEmpty(source.getAddress())){

        }
        if(!StringUtils.isEmpty(source.getHighesteducation())){
            target.setEdu(Integer.parseInt(source.getHighesteducation()));
        }
        if(!StringUtils.isEmpty(source.getSex())){
            target.setSex(source.getSex());
        }
        if(!StringUtils.isEmpty(source.getZpglCompanyId())){
            target.setZpglCompanyId(source.getZpglCompanyId());
        }
        if(!StringUtils.isEmpty(source.getZpglZjId())){
            target.setZpglZjId(source.getZpglZjId());
        }
        if(!StringUtils.isEmpty(source.getZpglGzddId())){
            target.setZpglGzddId(source.getZpglGzddId());
        }
        if(!StringUtils.isEmpty(source.getWeixin())){
            target.setWechat(source.getWeixin());
        }

    }
    @PostMapping(value = "/editInfo")
    @ApiOperation(value = "14.招聘-变更基础信息", httpMethod = "POST", notes = "招聘-变更人才信息状态")
    @ApiOperationSupport(order = 3)
    public Result<Object> editInfo(@CurrentUser UserBean userBean, @RequestBody ZpglRcxxDto zpglRcxxDto) {
        try {
           boolean re = ZpglRcxx.builder().name(zpglRcxxDto.getName()).mobile(zpglRcxxDto.getMobile()).mail(zpglRcxxDto.getMail()).build().update(new LambdaUpdateWrapper<ZpglRcxx>().eq(ZpglRcxx::getId, zpglRcxxDto.getId()));
            return re?ResultUtil.success("修改成功"):ResultUtil.error("修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("招聘-修改成功");
        }
    }

}