package com.wechat.service;

import com.google.common.collect.Maps;
import com.wechat.common.CommonHelper;
import com.wechat.common.Constants;
import com.wechat.common.utils.DateUtils;
import com.wechat.common.utils.LocalFileUtil;
import com.wechat.common.utils.Md5Utils;
import com.wechat.common.utils.StringsUtils;
import com.wechat.dao.*;
import com.wechat.global.CustomException;
import com.wechat.global.base.BaseService;
import com.wechat.global.base.dao.Pagination;
import com.wechat.global.base.dao.PagingResult;
import com.wechat.global.message.InfoMsg;
import com.wechat.model.dbEntity.*;
import com.wechat.model.dto.*;
import com.wechat.model.requestDto.*;
import com.wechat.model.responseDto.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * 个人中心 service类
 *
 * @author tangwc
 */
@Service
public class PersonCeneterService {

    // log 处理
    protected static final Log log = LogFactory.getLog(BaseService.class);
    @Value("#{configProperties['upload.base.path']}")
    private String basePackagePath;
    @Value("#{configProperties['upload.path.image']}")
    private String baseImagePackagePath;
    @Value("#{configProperties['upload.path.image.album']}")
    private String photoAlbumPath;
    //企业主页背景图
    @Value("#{configProperties['upload.path.image.centerBg']}")
    private String centerBgImages;
    @Value("#{configProperties['upload.path.card']}")
    private String baseCard;
    @Value("#{configProperties['upload.path.file']}")
    private String basePackagePathFile;
    @Value("#{configProperties['user.detail.myTrends.limitSize']}")
    private int myTrendsLimitSize;
    @Value("#{configProperties['compress.image.size']}")
    private int compressImageSize;
    @Resource
    private CommonService commonService;
    @Resource
    private CommonHelper commonHelper;
    @Autowired
    private WeiXinService weiXinService;
    @Resource
    private MdeUserDao userDao;
    @Resource
    private MdeTrendsDao trendsDao;
    @Resource
    private MdePhotoAlbumDao photoAlbumDao;
    @Resource
    private MdePositionCvRelDao positionCVRelDao;
    @Resource
    private MdeWorkExperienceService workExperienceService;
    @Resource
    private MdeEducationExperienceService educationExperienceService;
    @Autowired
    private MdeWorkExperienceDao mdeWorkExperienceDao;
    @Resource
    private MdeUserCvService userCvService;
    @Resource
    private MdeUserService userService;
    @Resource
    private MdeJobAdvertisedService jobAdvertisedService;
    @Resource
    private MdeFriendRelationService friendRelationService;
    @Resource
    private MdeOrdersDao mdeOrdersDao;
    @Autowired
    private MdeJobInvitationRelDao mdeJobInvitationRelDao;
    @Autowired
    private PositionService positionService;
    @Autowired
    private MdeInterestedAddsMapper interestAddDao;
    @Autowired
    private MdeSubscribedPositionsMapper subedPositionsDao;
    @Autowired
    private MdeSubscribedPrepareTypeMapper subedPrepareTypeDao;

    public Map<String, Object> init(String userCode) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("topImage", commonService.getAdImages(Constants.PC_PERSONCENTER_TOP_AD));
        return map;
    }

    /**
     * 获取用户信息
     *
     * @param userCode
     * @param lang
     * @return
     */
    public MdeUser getPersonInformation(String userCode, String lang) {
        return commonService.getUserInfoWithLang(userCode, lang);
    }

    /**
     * 修改用户基本信息
     *
     * @param info
     * @return
     */
    @Transactional
    public ResultEntity<String> modifyBaseInfo(HttpServletRequest req) {
        try {
            String userCode = commonService.getUserCode(req);
            String name = req.getParameter("name");
            String foreignName = req.getParameter("foreignName");
            // 地址-省（中国）[企业-公司地址；个人-意向工作地]
            String addrProvince = req.getParameter("addrProvince");
            String addrCity = req.getParameter("addrCity");
            String addrArea = req.getParameter("addrArea");
            String addDetail = req.getParameter("addDetail");

            // 个人
            String firstWork = req.getParameter("firstWork");
            String birthday = req.getParameter("birthday");
            String email = req.getParameter("email");
            String workStatus = req.getParameter("workStatus");
            String privateFlag = req.getParameter("privateFlag");

            // 企业
            String website = req.getParameter("website");
            // 筹开标识
            String prepareFlag = req.getParameter("prepareFlag");
            // 筹开年份
            String prepareYear = req.getParameter("prepareYear");
            // 筹开季度
            String prepareQuarter = req.getParameter("prepareQuarter");

            MdeUser user = userService.getUserInfoByCode(userCode);
            // 个人
            if (user.getIdentityFlag().equals("0")) {
                if (StringsUtils.isEmpty(name)
                        || StringsUtils.isEmpty(workStatus)
                        || StringsUtils.isEmpty(birthday)
                        || StringsUtils.isEmpty(firstWork)) {
                    throw new CustomException(InfoMsg.ERROR_PARAMS_ERROR);
                }
                user.setName(name);
                user.setWorkStatus(Integer.valueOf(workStatus));
                user.setEmail(email);
                user.setFirstWork(DateUtils.stringToDate(firstWork, DateUtils.PATTEN_YMTOW));
                user.setBirthday(StringsUtils.isNotEmpty(birthday) ? birthday : "");
                user.setUpdateBy(userCode + "");
//				user.setAddrProvince(getRealValue(addrProvince));
                user.setPrivateFlag(privateFlag);
//				user.setAddrCity(getRealValue(addrCity));
                user.setForeignName(StringsUtils.isEmpty(foreignName) ? "" : foreignName); // 外文名称
            } else {
                if (StringsUtils.isEmpty(name)) {
                    throw new CustomException(InfoMsg.ERROR_PARAMS_ERROR);
                }
                // 企业用户
                user.setName(name);
                if (StringsUtils.isNotEmpty(website)) {
                    if (!StringUtils.startsWithIgnoreCase(website, "http")
                            && !StringUtils.startsWithIgnoreCase(website, "https")) {
                        return new ResultEntity<>(InfoMsg.ERROR_HTTPS_ERROR);
                    }
                }
                user.setWebsite(website);
                user.setAddrProvince(addrProvince);
                user.setAddrCity(addrCity);
                user.setAddrArea(addrArea);
                user.setAddDetail(getRealValue(addDetail));
                user.setForeignName(StringsUtils.isEmpty(foreignName) ? "" : foreignName);// 外文名称

                //记录筹开相关信息
                user.setPrepareFlag(prepareFlag);
                user.setPrepareYear(prepareYear);
                user.setPrepareQuarter(prepareQuarter);
            }
            userDao.updateUser(user);
            return new ResultEntity<>(InfoMsg.SUCCESS_REQUEST);
        } catch (Exception e) {
            log.error("更新用户信息失败", e);
            throw new CustomException(InfoMsg.ERROR_UPDATE_USER_FAIL);
        }
    }

    /**
     * 修改企业联系人
     *
     * @param info
     * @return
     */
    @Transactional
    public ResultEntity<String> modifyEntContacts(HttpServletRequest req) {
        try {
            List<MultipartFile> picture = ((MultipartHttpServletRequest) req).getFiles("picture");
            String userCode = commonService.getUserCode(req);
            // 企业联系电话
            String phoneNum = req.getParameter("entPhone");
            // 企业联系人
            String entContacts = req.getParameter("entContacts");

            MdeUser user = userService.getUserInfoByCode(userCode);
            if (user.getIdentityFlag().equals("1")) {
                // 企业用户
                String onjobImage = "";
                if (CollectionUtils.isNotEmpty(picture)) {
                    onjobImage = LocalFileUtil.transferHeadProtrait(picture.get(0), basePackagePath,
                            baseImagePackagePath, compressImageSize); // 上传联系人在职证明并压缩
                }
                if (StringsUtils.isNotEmpty(onjobImage)) {
                    user.setOnJobImage(onjobImage);
                }
                user.setEntContacts(entContacts);
                user.setEntPhone(phoneNum);
                userDao.updateUser(user);
                return new ResultEntity<>(InfoMsg.SUCCESS_REQUEST);
            } else {
                log.error("个人修改企业账号信息" + userCode);
                return new ResultEntity<>(InfoMsg.ERROR_PARAMS_ERROR);
            }
        } catch (Exception e) {
            log.error("更新用户信息失败", e);
            throw new CustomException(InfoMsg.ERROR_UPDATE_USER_FAIL);
        }
    }


    /**
     * 修改用户简介
     *
     * @param info
     * @return
     */
    @Transactional
    public ResultEntity<String> modifyIntroduction(HttpServletRequest req) {
        try {
            List<MultipartFile> picture = ((MultipartHttpServletRequest) req).getFiles("picture");
            String userCode = commonService.getUserCode(req);
            String introduction = req.getParameter("introduction");

            MdeUser user = userService.getUserInfoByCode(userCode);
            // 个人用户上传名片并压缩
            if (user.getIdentityFlag().equals("0")) {
                String cardUrl = "";
                if (CollectionUtils.isNotEmpty(picture)) {
                    String pictureName = "pCard_" + userCode + ".jpg";
                    cardUrl = LocalFileUtil.solvePictureUpload(picture.get(0), basePackagePath, baseCard, compressImageSize, 500, 0.9f, pictureName); // 上传名片并压缩
                }
                if (StringsUtils.isNotEmpty(cardUrl)) {
                    user.setImage(cardUrl);
                }
            }
            user.setUpdateBy(userCode + "");

            // 当简介不为空时才更新
            if (StringsUtils.isNotEmpty(introduction)) {
                user.setIntroduction(introduction);
            }

            userDao.updateUser(user);
            return new ResultEntity<>(InfoMsg.SUCCESS_REQUEST);
        } catch (Exception e) {
            log.error("更新用户信息失败", e);
            throw new CustomException(InfoMsg.ERROR_UPDATE_USER_FAIL);
        }
    }


    public String getRealValue(String str) {
        return StringsUtils.isEmpty(str) ? null : str;
    }

    /**
     * 职位投递进展 - 详情
     *
     * @param userCode
     * @return
     */
    public List<PositionCvHisDto> postPositionDetailInfo(String userCode, String status) {
        Map<String, Object> map = new HashMap<String, Object>();

        if (!StringsUtils.isEmpty(status) && status.contains("1")) {
            //临时解决方案----初始状态查询的时候增加“6-储备”状态
            status = status.trim().concat(",6");
        }

        map.put("userCode", userCode);
        map.put("cvStatus", status.trim().split(","));
        return positionCVRelDao.getPostCVDetailInfo(map);
    }

    /**
     * 我的互动 - 收到的评论列表
     *
     * @param userCode
     * @return
     */
    public List<TrendCommentInfo> myInteractionOfTrends(String userCode) {
        List<TrendCommentInfo> list = commonService.getCommentedTrendsInfo(userCode);
        // 清除评论信息
        commonService.resetCommentedTrendsInfo(userCode);
        return list;
    }

    /**
     * 我的互动 - 点赞列表
     *
     * @param userCode
     * @return
     */
//	public List<MdeTrends> myThumbUp(String userCode, String lang) {
//		String likeListStr = commonService.getUserInfo(userCode).getLikeList();
//		if (StringsUtils.isEmpty(likeListStr)) {
//			return null;
//		}
//		likeListStr = likeListStr.substring(0, likeListStr.length() - 1);
//		return commonService.addDomainUrl2TrendsImg(trendsDao.myThumbUp(likeListStr.split(",")), lang);
//	}

    /**
     * 获取 工作经历、教育经历、简历列表
     *
     * @param userCode
     * @param lang
     * @return
     */
    public Map<String, Object> getMyCVInfos(String userCode, String lang) {
        List<MdeWorkExperience> workExperience = workExperienceService.getAllWorkExperienceByUserCode(userCode);
        List<MdeEducationExperience> educationExperience = educationExperienceService
                .getEducationExperienceByUserCode(userCode, lang);
        List<MdeUserCv> userCV = commonService.addDomainUrl2UserCvImg(userCvService.getUserCVList(userCode));

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("workExperience", workExperience);
        map.put("educationExperience", educationExperience);
        map.put("userCV", userCV);
        return map;
    }

    /**
     * 新增(修改)工作履历
     *
     * @param workExperience
     * @return
     * @throws Exception
     */
    public ResultEntity<String> modefyWorkExperience(MdeWorkExperience workExperience, HttpServletRequest req)
            throws Exception {
        String userCode = commonService.getUserCode(req);
        workExperience.setUserCode(userCode);
        // 新增工作履历
        if (workExperience.getWorkId() == null) {
            // 离职时间为空 显示当前入职时间最近的头衔
            workExperience.setShowFlag("1");
            workExperience.setVersionNo(1);
            workExperience.setEnFlag("1");
            workExperience.setOnJob("0");
            workExperience.setDelFlag(0);
            insertMdeWorkExperience(workExperience);
        } else {
            // 修改工作履历
            workExperience.setShowFlag("1");
            workExperience.setEnFlag("1");
            workExperience.setOnJob("0");
            workExperience.setDelFlag(0);
            updateMdeWorkExperience(workExperience);
        }
        // 将该用户的职位头衔都置为不显示
        workExperienceService.resetPositionTitle(userCode);
        // 设置最近的工作履历为显示的职位头衔
        workExperienceService.setLatestWEShow(userCode);

//		List<MdeWorkExperience> quitDateIsNull = workExperienceService.getQuitDateIsNull(userCode);
//		 工作履历按离职时间降序
//		List<MdeWorkExperience> quitDateDesc = workExperienceService.getWorkExperienceAndQuitDateDesc(userCode);
//		 获取当前显示的头衔履历
//		MdeWorkExperience showExperience = workExperienceService.getWorkPositionTitleByUserCode(userCode);
//		if (CollectionUtils.isNotEmpty(quitDateIsNull)) {
//			if (quitDateIsNull.get(0).getShowFlag().equals("1")) {
//				quitDateIsNull.get(0).setShowFlag("0");
//				workExperienceService.update(quitDateIsNull.get(0));
//				if (showExperience != null) {
//					showExperience.setShowFlag("1");
//					workExperienceService.update(showExperience);
//				}
//			}
//		} else {
//			if (quitDateDesc.get(0).getShowFlag().equals("1")) {
//				quitDateDesc.get(0).setShowFlag("0");
//				workExperienceService.update(quitDateDesc.get(0));
//				if (showExperience != null) {
//					showExperience.setShowFlag("1");
//					workExperienceService.update(showExperience);
//				}
//			}
//		}

        return new ResultEntity<>(InfoMsg.SUCCESS_REQUEST);
    }

    @Transactional
    public int insertMdeWorkExperience(MdeWorkExperience mdeWorkExperience) {
        return workExperienceService.insert(mdeWorkExperience);
    }

    @Transactional
    public int updateMdeWorkExperience(MdeWorkExperience mdeWorkExperience) {
        return workExperienceService.update(mdeWorkExperience);
    }

    /**
     * 删除工作履历
     *
     * @param workId
     * @param userCode
     * @return
     */
    @Transactional
    public void deleteAndUpdatePositionTitle(Integer workId, HttpServletRequest req) {
        String userCode = commonService.getUserCode(req);
        if (workId == null) {
            throw new CustomException(InfoMsg.ERROR_PARAMS_ERROR);
        }
        MdeWorkExperience mdeWork = workExperienceService.getInfoById(workId);
        // 删除工作履历
        mdeWorkExperienceDao.delete(workId);

        //如果删除对象是显示中的title
        if (mdeWork != null && mdeWork.getShowFlag().equals("0")) {
            //设置最近的工作履历为职位头衔
            mdeWorkExperienceDao.setLatestWEShow(userCode);
        }

    }


    /**
     * 修改职位头衔
     *
     * @param integer
     * @return
     */
    public int modefyPositionTitle(Integer workId, String userCode) {
        MdeWorkExperience workExperience = new MdeWorkExperience();
        workExperience.setWorkId(workId);
        workExperience.setUserCode(userCode + "");
        workExperience.setUpdateBy(userCode + "");
        return workExperienceService.updatePositionTitle(workExperience);
    }

    /**
     * 修改教育经历
     *
     * @param educationExperience
     * @return
     */
    @Transactional
    public int modefyEducationExperience(MdeEducationExperience educationExperience, String lang) {
        educationExperience.setUpdateBy(educationExperience.getUserCode() + "");
        if (educationExperience.getEduId() == null) {
            List<MdeEducationExperience> list = educationExperienceService
                    .getEducationExperienceByUserCode(educationExperience.getUserCode(), lang);
            if (list != null && list.size() == 3) {
                throw new CustomException(InfoMsg.ERROR_EDUCATION_BEYOUND_LIMIT);
            }
            educationExperience.setCreateBy(educationExperience.getUserCode() + "");
            educationExperience.setDelFlag(0);
            educationExperience.setVersionNo(1);
            return educationExperienceService.insert(educationExperience);
        } else {
            return educationExperienceService.update(educationExperience);
        }
    }

    /**
     * 删除教育经历
     *
     * @param integer
     * @param userCode
     * @return
     */
    @Transactional
    public int deleteEducationExperience(Integer eduId, String userCode) {
        if (eduId == null) {
            throw new CustomException(InfoMsg.ERROR_EMPTY_REQUEST);
        }
        return educationExperienceService.delete(eduId, userCode);
    }

    /**
     * 删除简历
     *
     * @param cvId
     * @return
     */
    @Transactional
    public int deleteUserCv(Long cvId, String userCode) {
        List<UserCvInfo> userCvList = userCvService.getCvUsed(cvId, userCode);
        if (userCvList.size() == 1) {
            if (StringsUtils.isEmpty(userCvList.get(0).getCvUrlUsed())) {
                //当该简历附件未被使用的时候，删除源文件
                LocalFileUtil.deleteLocalFile(basePackagePath + userCvList.get(0).getCvUrl());
            }
        }

        return userCvService.deleteUserCv(cvId, userCode);
    }

    /**
     * 上传简历
     *
     * @param multipartFile
     * @return
     */
    @Transactional
    public int uploadUserCv(MultipartFile file, String userCode, String system) {
        String fileName = file.getOriginalFilename();
        int count = 0;
        if (fileName.length() >= 60) {
            throw new CustomException(InfoMsg.ERROR_FILE_TOOLONG_ERROR);
        }
        if (fileName.indexOf(".") > 0) {
            String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
            if (!checkFileType(fileType, system)) {
                throw new CustomException(InfoMsg.ERROR_FILE_TYPE_ERROR);
            }

            String path = "";
            try {
                path = LocalFileUtil.transferToFile(file, basePackagePath, basePackagePathFile);
            } catch (IOException e) {
                throw new CustomException(InfoMsg.ERROR_UPLOAD_FIELD);
            }
            MdeUserCv userCv = new MdeUserCv();
            userCv.setCvUrl(path);
            userCv.setUserCode(userCode);
            // String fileName = file.getName().substring(0, file.getName().indexOf("."));
            userCv.setCvTitle(fileName);
            userCv.setDelFlag(0);
            userCv.setVersionNo(1);
            userCv.setCreateBy(userCode);
            userCv.setUpdateBy(userCode);

            count = userCvService.insert(userCv);
        } else {
            throw new CustomException(InfoMsg.ERROR_FILE_TYPE_ERROR);
        }

        return count;
    }

    public boolean checkFileType(String fileName, String system) {
        // ========== 20230911 更改 【STORY】1000170 ==========
        if (fileName.equalsIgnoreCase("pdf")
                || fileName.equalsIgnoreCase("doc")
                || fileName.equalsIgnoreCase("docx")
                || fileName.equalsIgnoreCase("xls")
                || fileName.equalsIgnoreCase("xlsx")) {
            return true;
        }
        if (system.toLowerCase().contains("ios")) {
            if (fileName.equalsIgnoreCase("png")
                    || fileName.equalsIgnoreCase("jpg")
                    || fileName.equalsIgnoreCase("jpeg")) {
                return true;
            }
        }
        return false;
    }

    /**
     * 查看简历
     *
     * @param userCode
     * @return
     */
    public List<MdeUserCv> getUserCv(String userCode) {
        return commonService.addDomainUrl2UserCvImg(userCvService.getUserCVList(userCode));
    }

    /**
     * 收藏的职位列表
     *
     * @param userCode
     * @return
     */
    public List<JobAdvertisedRes> getCollectionJobList(String userCode, String lang) {
        String positionListStr = commonService.getUserInfo(userCode).getPositionList();
        if (StringsUtils.isEmpty(positionListStr)) {
            return null;
        }
        positionListStr = positionListStr.substring(0, positionListStr.length() - 1);
        // String[] likeList = likeListStr.split(",");
        // List<String> list = StringsUtils.stringArray2List(likeList);
        return jobAdvertisedService.getCollectionJobList(positionListStr.split(","), lang);
    }

    /**
     * 上传用户头像
     *
     * @param headProtrait
     * @param userCode
     * @return
     */
    public String changeUserHeadPortrait(MultipartFile headProtrait, String userCode) {
        String path = "";
        MdeUser u = commonService.getUserInfo(userCode);
        String name = getUserHeadPortraitName(u);
        try {
            path = LocalFileUtil.saveHeadProtrait(headProtrait, basePackagePath, baseImagePackagePath,
                    compressImageSize, name);
        } catch (IOException e) {
            throw new CustomException(InfoMsg.ERROR_UPLOAD_FIELD);
        }
        MdeUser user = userDao.getUserInfoByCode(userCode);
        user.setUserCode(userCode);
        user.setHeadPortrait(path);
        user.setUpdateBy(userCode.toString());
        user.setUpdateDate(new Date());
        int i = userService.updateUserPicture(user);
        if (i != 1)
            throw new CustomException(InfoMsg.ERROR_UPLOAD_FIELD);
        return commonService.addDomainAndTs(path);
    }

    private String getUserHeadPortraitName(MdeUser u) {
        return u.getCreateDate().getTime() + "_" + u.getUserCode() + ".jpg";
    }

    /**
     * 删除好友
     *
     * @param userCode  本人
     * @param userCode1 好友id
     * @return
     */
    public int delFriends(String userCode, String userCode1) {
        return friendRelationService.delFriends(userCode, userCode1);
    }

    /**
     * 删除动态
     *
     * @param userCode
     * @param trendId
     * @return
     */
    public int delTrends(String userCode, Long trendId) {
        MdeTrends trends = new MdeTrends();
        trends.setTrendId(new Long(trendId));
        trends.setUpdateBy(userCode + "");
        trends.setDelFlag(1);
        trendsDao.deleteTrendOrigin(trends);// 删除全部应用
        return trendsDao.delete(trends);
    }

    /**
     * 获取指定用户的动态
     *
     * @param beViewed  被查询的人
     * @param theSearch 查询人
     * @param pageParam
     * @return
     */
    public PagingResult<TrendsDto> getMyTrends(String beViewed, String theSearch, PageReq pageParam, String lang) {
        Pagination page = new Pagination(pageParam.getIndex(), pageParam.getSize());
        Map<Object, Object> param = new HashMap<Object, Object>();
        param.put("beViewed", beViewed);
        //不是查询自己动态的情况
        if (!beViewed.equals(theSearch)) {
            param.put("theSearch", theSearch);
        }
        page.setParams(param);
        PagingResult<TrendsDto> pageResult = trendsDao.getMyTrends(page);
        return pageResult;
    }

    /**
     * 修改密码
     *
     * @param req
     * @return
     */
    public int changePassword(ChangPReq req) {
        MdeUser checkUser = userService.getFullInfo(req.getUserCode());
        String oldPassword = req.getOldPassword();
        // md5加密
        oldPassword = Md5Utils.EncoderPassword(oldPassword);
        if (!StringsUtils.isEqual(oldPassword, checkUser.getPassword())) {
            throw new CustomException(InfoMsg.ERROR_LOGIN);
        }
        MdeUser user = new MdeUser();
        user.setUserCode(req.getUserCode());
        String newPassword = req.getNewPassword();
        // md5 加密
        newPassword = Md5Utils.EncoderPassword(newPassword);
        user.setPassword(newPassword);
        return userService.update(user);
    }

    /**
     * 购买记录
     *
     * @param lang
     * @param record
     * @return
     */
    public PagingResult<OrderListDto> buyRecord(BuyRecordReq param, String lang) {
        Pagination page = new Pagination(param.getIndex(), param.getSize());
        Map<Object, Object> pageParam = new HashMap<Object, Object>();
        pageParam.put("userCode", param.getUserCode());
        pageParam.put("lang", lang);
        page.setParams(pageParam);
        return mdeOrdersDao.getBuyRecord(page);
    }

    /**
     * 获取企业邀请信息
     *
     * @return
     */
    public PagingResult<HotelInvitationInfoResp> getRecievedHotelInvationInfo(Map<String, String> page,
                                                                              HttpServletRequest req) {
        String userCode = commonService.getUserCode(req);
        Pagination pagination = new Pagination(Integer.valueOf(page.get("index")), Integer.valueOf(page.get("size")));
        Map<Object, Object> params = Maps.newHashMap();
        params.put("userCode", userCode);
        pagination.setParams(params);
        PagingResult<HotelInvitationInfoResp> pageResult =
                mdeJobInvitationRelDao.getRecievedHotelInvationInfo(pagination);
        // 清除企业邀请记录
        // commonService.deleteHotelInvationInfoCounts(userCode);
        pageResult.setResultList(commonService.addDomainUrl2HotelInvitationImg(pageResult.getResultList()));
        return pageResult;
    }

    /**
     * 查看企业详情并更新职位状态
     *
     * @param jobId 职位id
     * @return
     */
    @Transactional
    public Map<String, Object> lookEnterPriseDetailAndUpdateStatus(String userCode, Integer jobId, String lang) {

        Map<String, Object> params = Maps.newHashMap();
        params.put("jobId", jobId);
        params.put("userCode", userCode);
        params.put("status", 1); // 1已读
        try {
            mdeJobInvitationRelDao.updateStatus(params);
            // 从redis中清除该职位Id
            ArrayList<String> invationInfo = commonService.getRecievedHotelInvationInfo(userCode);
            invationInfo.remove(jobId.toString());
            // 更新redis
            commonService.updateUserInvatedCvCount(userCode, invationInfo);
        } catch (Exception e) {
            throw new CustomException(InfoMsg.ERROR_UPDATE_USERCVSTATUS_FILE);
        }
        return positionService.getPositionDetail(jobId, userCode, lang, null);
    }

    /**
     * 获取用户主页基础信息
     *
     * @param userCode
     * @param lang
     * @return
     */
    public UserHomePageResp<JobAdvertisedResp> getHomePageInfo(String beViewed, String lang, String theSearch,
                                                               String currentUserIdentityFlag) {
        UserHomePageResp<JobAdvertisedResp> result = new UserHomePageResp<JobAdvertisedResp>();
        result.setTopImage(commonService.getAdImages(Constants.PC_USER_DETAIL_TOP_AD));// 顶部图片
        result.setRightAD(commonService.getAdImages(Constants.PC_MAINPAGE_RIGHT_AD1));// 右侧广告
        //获取用户好友关系和基础用户信息
        UserAndIsFriendDto user = getUserAndIsFriend(beViewed, theSearch, lang);
        // 处理查看用户名片
        user = solveLookOutUserImage(theSearch, user);
        // 返回用户信息
        user.setCreateDate(null); //去除敏感信息
        result.setUserInfo(user);

        // 好友动态
        PageReq pageParam = new PageReq();
        pageParam.setIndex(1);
        pageParam.setSize(myTrendsLimitSize);
        PagingResult<TrendsDto> trendsListPageResult = getMyTrends(beViewed, theSearch, pageParam, lang);
        result.setMyTrends(trendsListPageResult);

        //区分个人和企业
        if (user.getIdentityFlag().equalsIgnoreCase("0")) {
            List<WorkExperienceBaseDto> workExpriences = workExperienceService.getBaseWorkExperienceByUserCode(beViewed);
            result.setWorkExpriences(workExpriences);// 工作经验
            List<MdeEducationExperience> eduExperiences = educationExperienceService
                    .getEducationExperienceByUserCode(beViewed, lang);
            result.setEduExperiences(eduExperiences);// 教育经历
        } else {
            // 获取发布中的职位
            result.setPublishingJobs(jobAdvertisedService.getPublishingJobsByUserCode(beViewed, lang));
            // 获取首推数据
            result.setRecommendNums(jobAdvertisedService.getAvailableAndUsedCount(beViewed));
        }
        if (currentUserIdentityFlag != null) {
            if ("0".equals(currentUserIdentityFlag)) {
                result.setRecommentJob(commonService.getRecommentJobs());// 推荐职位
            }
            // 企业
            else {
                result.setRecommentPeople(commonService.getRecommentPeople(beViewed));// 推荐人才
            }
        }
        return result;
    }

    /**
     * 获取用户主页基础信息
     * 非登陆状态
     *
     * @param userCode
     * @param lang
     * @return
     */
    public UserHomePageResp<JobAdvertisedNologinResp> getHomePageNologin(String beViewed, String lang, String theSearch, String creatTime) {
        UserHomePageResp<JobAdvertisedNologinResp> result = new UserHomePageResp<JobAdvertisedNologinResp>();
        result.setTopImage(commonService.getAdImages(Constants.PC_USER_DETAIL_TOP_AD));// 顶部图片
        result.setRightAD(commonService.getAdImages(Constants.PC_MAINPAGE_RIGHT_AD1));// 右侧广告
        //获取用户好友关系和基础用户信息
        UserAndIsFriendDto user = getUserAndIsFriend(beViewed, theSearch, lang);

        //用户信息验证无误的情况下才做后续处理
        if (StringsUtils.isEqual(String.valueOf(user.getCreateDate().getTime()), creatTime)) {
            //去除敏感信息
            user.setCreateDate(null);
            user.setImage(null);
            // 返回用户信息
            result.setUserInfo(user);

            // 获取发布中的职位
            result.setPublishingJobs(jobAdvertisedService.getPublishingJobsByUserCodeNologin(beViewed, lang));
            // 获取首推数据
            result.setRecommendNums(jobAdvertisedService.getAvailableAndUsedCount(beViewed));
            // 推荐职位
            result.setRecommentJob(commonService.getRecommentJobs());
        }

        return result;
    }


    /**
     * 获取用户好友关系和基础用户信息
     *
     * @param userCode
     * @param lang
     * @return
     */
    private UserAndIsFriendDto getUserAndIsFriend(String beViewed, String theSearch, String lang) {
        //获取用户信息
        UserAndIsFriendDto user = userDao.getUserAndIsFriend(beViewed, theSearch, lang);
        if (user != null) {
            user.setHeadPortrait(commonService.addDomainAndTs(user.getHeadPortrait()));
            user.setImage(commonService.addDomainAndTs(user.getImage()));
            //aes加密分享用code
            user.setShareCode(commonHelper.getShareCodeAes(user.getUserCode(), user.getCreateDate()));
        }
        // 返回用户信息
        return user;

    }


    /**
     * 处理 查看个人用户名片
     *
     * @param currentUserCode
     * @param user
     * @return
     */
    private UserAndIsFriendDto solveLookOutUserImage(String currentUserCode, UserAndIsFriendDto user) {
        // 个人用户有名片
        if ("0".equals(user.getIdentityFlag())) {
            MdeUser currentUser = commonService.getUserInfo(currentUserCode);
            // 当前用户是会员
            if (!"0".equals(currentUser.getVipFlag())) {
                if (StringsUtils.isEmpty(user.getImage())) {
                    user.setImage("-1");
                }
            }
            // 当前用户 非会员
            else {
                if (StringsUtils.isEmpty(user.getImage())) {
                    user.setImage("-1");
                } else {
                    user.setImage("0");
                }
            }
        } else {
            // 企业用户营业执照脱敏
            user.setImage("");
        }
        return user;
    }


    /**
     * 上传用户相册
     *
     * @return
     */
    @Transactional
    public int uploadPhotoAlbum(String userCode, List<MultipartFile> pictureList) {
        String picPath = "";
        int count = 0;
        //获取当前排序
        Integer maxSort = photoAlbumDao.getSortByUserCode(userCode);
        if (maxSort == null) {
            maxSort = 0;
        }

        MdePhotoAlbum photoAlbum = new MdePhotoAlbum();
        photoAlbum.setUserCode(userCode);
        photoAlbum.setCreateBy(userCode);
        photoAlbum.setUpdateBy(userCode);

        if (pictureList.size() > 0) {
            try {
                for (MultipartFile pic : pictureList) {
                    //图片上传
                    picPath = LocalFileUtil.transferToImageFile(pic, basePackagePath, baseImagePackagePath + photoAlbumPath);
                    if (StringsUtils.isEmpty(picPath)) {
                        throw new CustomException(InfoMsg.ERROR_IMAGE_TYPE);
                    }
                    // 压缩图片到200k以下
                    LocalFileUtil.commpressPicCycle(basePackagePath + picPath, compressImageSize, 0.8f);
                    //保存数据
                    photoAlbum.setPhotoUrl(picPath);
                    maxSort = maxSort + 1;
                    photoAlbum.setSort(maxSort);
                    count = count + photoAlbumDao.insert(photoAlbum);
                }

            } catch (CustomException e) {
                throw e;
            } catch (Exception e) {
                throw new CustomException(InfoMsg.ERROR_UPLOAD_FIELD);
            }
        }
        return count;
    }


    /**
     * 上传用户相册 -手机端
     *
     * @return
     */
    @Transactional
    public int uploadPhotoAlbumMobile(String userCode, List<String> pictureIds) {
        String picPath = "";
        int count = 0;
        //获取当前排序
        Integer maxSort = photoAlbumDao.getSortByUserCode(userCode);
        if (maxSort == null) {
            maxSort = 0;
        }

        MdePhotoAlbum photoAlbum = new MdePhotoAlbum();
        photoAlbum.setUserCode(userCode);
        photoAlbum.setCreateBy(userCode);
        photoAlbum.setUpdateBy(userCode);

        for (String pId : pictureIds) {
            //上传图片
            try {
                picPath = weiXinService.saveImageToDisk(pId, photoAlbumPath);

                if (!StringsUtils.isEmpty(picPath)) {
                    //保存数据
                    photoAlbum.setPhotoUrl(picPath);
                    maxSort = maxSort + 1;
                    photoAlbum.setSort(maxSort);
                    count = count + photoAlbumDao.insert(photoAlbum);
                }
            } catch (Exception e) {
                throw new CustomException(InfoMsg.ERROR_UPLOAD_FIELD);
            }
        }
        return count;
    }


    /**
     * 删除相册照片
     *
     * @return
     */
    @Transactional
    public int delPhotoAlbum(String userCode, int pictureId) {
        MdePhotoAlbum photoAlbum = new MdePhotoAlbum();
        photoAlbum.setUserCode(userCode);
        photoAlbum.setPhoId(pictureId);
        photoAlbum.setDelFlag(1);

        return photoAlbumDao.update(photoAlbum);
    }


    /**
     * 修改相册照片排序
     *
     * @return
     */
    @Transactional
    public int updatePhotoSort(String userCode, List<PhotoAlbumReq> photoAlbumReqList) {
        MdePhotoAlbum photoAlbum = new MdePhotoAlbum();
        photoAlbum.setUserCode(userCode);

        int count = 0;
        if (photoAlbumReqList.size() > 0) {
            for (PhotoAlbumReq req : photoAlbumReqList) {
                photoAlbum.setPhoId(req.getPhoId());
                photoAlbum.setSort(req.getSort());
                photoAlbum.setPhotoDesc(req.getPhotoDesc());
                count = count + photoAlbumDao.update(photoAlbum);
            }
        }

        return count;
    }


    /**
     * 查询相册照片
     *
     * @return
     */
    @Transactional
    public List<PhotoAlbumResp> getPhotoAlbum(String userCode) {

        List<PhotoAlbumResp> list = photoAlbumDao.getPhotoAlbum(userCode);

        //封装域名
        if (CollectionUtils.isNotEmpty(list)) {
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setPhotoUrl(commonService.addDomain(list.get(i).getPhotoUrl()));
            }
        }
        return list;
    }

    /**
     * 修改意向工作地
     *
     * @param modifyInterestedAdds
     * @return
     */
    @Transactional
    public int modifyInterestedAdds(List<InterestedAddsReq> addsList, String userCode) {
        //整删整插
        interestAddDao.deleteByUsercode(userCode);
        int i = 0;
        for (InterestedAddsReq reqDto : addsList) {
            MdeInterestedAdds entity = new MdeInterestedAdds();
            //将entity和入参相同属性复制至entity中
            BeanUtils.copyProperties(reqDto, entity);
            //保存操作初始化
            entity.preInsert(userCode);
            entity.setUserCode(userCode);
            try {
                //信息保存
                i = i + interestAddDao.insert(entity);
            } catch (Exception e) {
                log.error("*********************意向工作地保存失败！" + userCode + "++" + entity.getIntdCity() + "*************************");
                throw new CustomException(InfoMsg.ERROR_DATA_UPDATE);
            }
        }
        return i;
    }


    /**
     * 修改职位订阅信息
     *
     * @param modifySubscribedPositions
     * @return
     */
    @Transactional
    public int modifySubscribedPositions(SubscribePositionReq subPositionReq, String userCode) {
        //整删整插
        //职位订阅删除
        subedPositionsDao.deleteByUserCode(userCode);
        //酒店筹开类型删除
        subedPrepareTypeDao.deleteByUserCode(userCode);
        int i = 0;
        List<SubscribedPositionsDto> positionList = subPositionReq.getPositions();

        //职位订阅存储
        for (SubscribedPositionsDto positionInfo : positionList) {
            //将entity和入参相同属性复制至entity中
            MdeSubscribedPositions entity = new MdeSubscribedPositions();
            BeanUtils.copyProperties(positionInfo, entity);
            //保存操作初始化
            entity.preInsert(userCode);
            entity.setUserCode(userCode);
            try {
                //信息保存
                i = i + subedPositionsDao.insert(entity);
            } catch (Exception e) {
                log.error("*********************意向职位保存失败！" + userCode + "++" + entity.getPositionId() + "*************************");
                continue;
            }
        }
        //数据存储0件的情况下，回滚操作
        if (i < 1) {
            throw new CustomException(InfoMsg.ERROR_DATA_UPDATE);
        }

        //酒店筹开类型存储
        for (String prepareFlag : subPositionReq.getPrepareFlags()) {
            //保存操作初始化
            MdeSubscribedPrepareType entity = new MdeSubscribedPrepareType();
            entity.setPrepareFlag(prepareFlag);
            entity.preInsert(userCode);
            entity.setUserCode(userCode);
            try {
                //信息保存
                subedPrepareTypeDao.insert(entity);
            } catch (Exception e) {
                log.error("*********************意向酒店筹开类型保存失败！" + userCode + "++" + prepareFlag + "*************************");
                continue;
            }
        }

        //修改职位订阅标志为--订阅[0-未订阅；1-订阅]
        userDao.modifySubscribedFlag(userCode, "1");

        return i;
    }


    /**
     * 获取意向工作地
     *
     * @return
     */
    @Transactional
    public List<InterestedAddsReq> getInterestedAdds(String userCode, String lang) {
        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("userCode", userCode);
        paramMap.put("lang", lang);
        List<InterestedAddsReq> list = interestAddDao.getIntAddsByUserCode(paramMap);

        return list;
    }

    /**
     * 获取意向职位
     *
     * @return
     */
    @Transactional
    public List<SubscribedPositionsDto> getSubscribedPositions(String userCode, String lang) {
        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("userCode", userCode);
        paramMap.put("lang", lang);
        List<SubscribedPositionsDto> list = subedPositionsDao.getSubscribedPositions(paramMap);

        return list;
    }

    /**
     * 获取意向筹开类型
     *
     * @return
     */
    @Transactional
    public List<String> getSubscribedPrepareType(String userCode) {

        List<String> list = subedPrepareTypeDao.getSubscribedPrepareType(userCode);

        return list;
    }


    /**
     * 修改个人中心背景图
     *
     * @return
     */
//	@Transactional
//	public int changeCenterBgImages(String userCode, MultipartFile portraitBackgroundPc,
//			MultipartFile portraitBackgroundMob,MultipartFile topBackgroundPc,
//			MultipartFile topBackgroundMob, EnterpriseBgImgsResp bgImgsResp) {
//		MdeUser user = new MdeUser();
//		
//		int count = 0;
//		//上传背景图并获取存储路径
//		String portraitBgPcPath=uploadBgImages(portraitBackgroundPc);
//		String portraitBgMobPath=uploadBgImages(portraitBackgroundMob);
//		String topBgPcPath=uploadBgImages(topBackgroundPc);
//		String topBgMobPath=uploadBgImages(topBackgroundMob);
//		if(!StringsUtils.isEmpty(portraitBgPcPath) || !StringsUtils.isEmpty(portraitBgMobPath) ||!StringsUtils.isEmpty(topBgPcPath) ||!StringsUtils.isEmpty(topBgMobPath)) {
//			//数据安装
//			user.setUserCode(userCode);
//			user.setPortraitBackgroundPc(portraitBgPcPath);
//			user.setPortraitBackgroundMbl(portraitBgMobPath);
//			user.setTopBackgroundPc(topBgPcPath);
//			user.setTopBackgroundMbl(topBgMobPath);
//			user.setUpdateBy(userCode);
//			user.setUpdateDate(new Date());
//			count = userDao.uploadBgImages(user);
//			//返回结果实装
//			bgImgsResp.setPortraitBackgroundPc(portraitBgPcPath);
//			bgImgsResp.setPortraitBackgroundMbl(portraitBgMobPath);
//			bgImgsResp.setTopBackgroundPc(topBgPcPath);
//			bgImgsResp.setTopBackgroundMbl(topBgMobPath);
//		}
//		
//		return count;
//	}
    private String uploadBgImages(MultipartFile pic) {
        String picPath = "";
        if (pic != null && !pic.isEmpty()) {
            try {
                //图片上传
                picPath = LocalFileUtil.transferToImageFile(pic, basePackagePath, baseImagePackagePath + centerBgImages);
                if (StringsUtils.isEmpty(picPath)) {
                    throw new CustomException(InfoMsg.ERROR_IMAGE_TYPE);
                }
                // 压缩图片到600k以下
                LocalFileUtil.commpressPicCycle(basePackagePath + picPath, compressImageSize, 0.8f);
            } catch (CustomException e) {
                throw e;
            } catch (Exception e) {
                throw new CustomException(InfoMsg.ERROR_UPLOAD_FIELD);
            }
        }
        return picPath;
    }

}
