package com.yd.api.practitioner.service.impl;

import com.yd.api.practitioner.service.PractitionerHiringService;
import com.yd.api.practitioner.vo.hiring.*;
import com.yd.api.result.CommonResult;
import com.yd.dal.entity.customer.*;
import com.yd.dal.mapper.customer.*;
import com.yd.rmi.ali.oss.service.OssService;

import com.yd.util.CommonUtil;
import com.yd.util.HttpUtil;
import com.yd.util.config.ZHBErrorConfig;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Service
public class PractitionerHiringServiceImpl implements PractitionerHiringService {

    @Autowired
    private OssService ossService;
    @Autowired
    private AclPractitionerHiringMembershipMapper membershipMapper;
    @Autowired
    private AclPractitionerHiringBasicInfoMapper basicInfoMapper;
    @Autowired
    private AclPractitionerHiringWorkingExperienceMapper workingExperienceMapper;
    @Autowired
    private AclPractitionerHiringPersonalStatementsMapper personalStatementsMapper;
    @Autowired
    private AclPractitionerHiringContractTermsConfirmsMapper contractTermsConfirmsMapper;

    @Override
    public SaveMembershipResponseVO saveMembership(SaveMembershipRequestVO requestVO) {
        SaveMembershipResponseVO resp = new SaveMembershipResponseVO();
        try {
            // 先保存ag_acl_practitioner_hiring_basic_info，获取hiringBasicInfoId
            AclPractitionerHiringBasicInfo basicInfo = new AclPractitionerHiringBasicInfo();
            basicInfo.setName(requestVO.getName());
            basicInfo.setPractitionerPotentialId(requestVO.getPractitionerPotentialId());
            basicInfoMapper.insertSelective(basicInfo);

            // 数据库实体
            AclPractitionerHiringMembership membership = new AclPractitionerHiringMembership();
            BeanUtils.copyProperties(requestVO, membership);
            membership.setHiringBasicInfoId(basicInfo.getId());
            membership.setIsActive(1);

            Date curDate = new Date();
            membership.setCreatedAt(curDate);
            membership.setUpdatedAt(curDate);

            Long loginId = requestVO.getLoginId();
            membership.setCreatedBy(loginId);
            membership.setUpdatedBy(loginId);

            membershipMapper.insertSelective(membership);

            resp.setHiringBasicInfoId(basicInfo.getId());
            resp.setCommonResult(new CommonResult(true, ZHBErrorConfig.getErrorInfo("800000")));
        } catch (Exception e) {
            e.printStackTrace();
            resp.setCommonResult(new CommonResult(false, e.getMessage()));
        }
        return resp;
    }

    @Override
    public SaveBasicInfoResponseVO saveBasicInfo(SaveBasicInfoRequestVO requestVO) {
        SaveBasicInfoResponseVO resp = new SaveBasicInfoResponseVO();
        try {
            // 数据库实体
            AclPractitionerHiringBasicInfo basicInfo = new AclPractitionerHiringBasicInfo();
            BeanUtils.copyProperties(requestVO, basicInfo);
            basicInfo.setIsActive(1);

            Date curDate = new Date();
            basicInfo.setCreatedAt(curDate);
            basicInfo.setUpdatedAt(curDate);

            basicInfo.setCreatedBy((long) -1);
            basicInfo.setUpdatedBy((long) -1);

            basicInfoMapper.updateByPrimaryKeySelective(basicInfo);

            resp.setCommonResult(new CommonResult(true, ZHBErrorConfig.getErrorInfo("800000")));

        } catch (Exception e) {
            e.printStackTrace();
            resp.setCommonResult(new CommonResult(false, e.getMessage()));
        }
        return resp;
    }

    @Override
    public QueryMembershipResponseVO queryMembership(QueryMembershipRequestVO requestVO) {
        QueryMembershipResponseVO resp = new QueryMembershipResponseVO();
        try {
            AclPractitionerHiringMembership membership = membershipMapper.queryByhiringBasicInfoId(requestVO);

            resp.setMembership(membership);
            resp.setCommonResult(new CommonResult(true, ZHBErrorConfig.getErrorInfo("800000")));

        } catch (Exception e) {
            e.printStackTrace();
            resp.setCommonResult(new CommonResult(false, e.getMessage()));
        }
        return resp;
    }

    @Override
    public SaveWorkingExperienceResponseVO saveWorkingExperience(SaveWorkingExperienceRequestVO requestVO) {
        SaveWorkingExperienceResponseVO resp = new SaveWorkingExperienceResponseVO();
        try {
            List<AclPractitionerHiringWorkingExperience> workingExperienceList = requestVO.getWorkingExperienceList();

            Date curDate = new Date();
            workingExperienceList.forEach(item -> {
                item.setIsActive(1);

                item.setCreatedAt(curDate);
                item.setUpdatedAt(curDate);

                item.setCreatedBy((long) -1);
                item.setUpdatedBy((long) -1);
            });

            if (workingExperienceList.size() > 0) {
                workingExperienceMapper.batchInsert(workingExperienceList);
            }

            resp.setCommonResult(new CommonResult(true, ZHBErrorConfig.getErrorInfo("800000")));

        } catch (Exception e) {
            e.printStackTrace();
            resp.setCommonResult(new CommonResult(false, e.getMessage()));
        }
        return resp;
    }

    @Override
    public SavePersonPictureResponseVO savePersonPicture(SavePersonPictureRequestVO requestVO) {
        SavePersonPictureResponseVO resp = new SavePersonPictureResponseVO();
        try {
            String mediaId = requestVO.getVxUrl();
            Long basicInfoId = requestVO.getHiringBasicInfoId();
            String imgUrl = this.uploadImageToOss(mediaId, basicInfoId, 2);

            if (imgUrl == null) {
                resp.setCommonResult(new CommonResult(false, ZHBErrorConfig.getErrorInfo("830024")));
            } else {
                AclPractitionerHiringBasicInfo basicInfo = new AclPractitionerHiringBasicInfo();
                basicInfo.setId(basicInfoId);
                basicInfo.setPersonerPictureOssPath(imgUrl);
                basicInfoMapper.updateByPrimaryKeySelective(basicInfo);

                resp.setCommonResult(new CommonResult(true, ZHBErrorConfig.getErrorInfo("800000")));
                resp.setImgUrl(imgUrl);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resp.setCommonResult(new CommonResult(false, e.getMessage()));
        }
        return resp;
    }

    @Override
    public SaveIDPictureResponseVO saveIDPicture(SaveIDPictureRequestVO requestVO) {
        SaveIDPictureResponseVO resp = new SaveIDPictureResponseVO();
        try {
            Long basicInfoId = requestVO.getHiringBasicInfoId();
            String frontVxUrl = requestVO.getFrontVxUrl();
            String backVxUrl = requestVO.getBackVxUrl();

            String frontImgUrl = this.uploadImageToOss(frontVxUrl, basicInfoId, 7);
            String backImgUrl = this.uploadImageToOss(backVxUrl, basicInfoId, 8);

            if (frontImgUrl != null && backImgUrl != null) {
                AclPractitionerHiringBasicInfo basicInfo = new AclPractitionerHiringBasicInfo();
                basicInfo.setId(basicInfoId);
                basicInfo.setIdFrontPageOssPath(frontImgUrl);
                basicInfo.setIdBackPageOssPath(backImgUrl);
                basicInfoMapper.updateByPrimaryKeySelective(basicInfo);

                resp.setCommonResult(new CommonResult(true, ZHBErrorConfig.getErrorInfo("800000")));
                resp.setFrontImgUrl(frontImgUrl);
                resp.setBackImgUrl(backImgUrl);
            } else {
                resp.setCommonResult(new CommonResult(false, ZHBErrorConfig.getErrorInfo("830024")));
            }

        } catch (Exception e) {
            e.printStackTrace();
            resp.setCommonResult(new CommonResult(false, e.getMessage()));
        }
        return resp;
    }

    @Override
    public SaveLastGraduateGradeResponseVO saveLastGraduateGrade(SaveLastGraduateGradeRequestVO requestVO) {
        SaveLastGraduateGradeResponseVO resp = new SaveLastGraduateGradeResponseVO();
        try {
            Long basicInfoId = requestVO.getHiringBasicInfoId();
            String grade = requestVO.getLastGraduateGrade();
            String school = requestVO.getLastGraduateSchool();
            String vxUrl = requestVO.getCertificationVxUrl();

            String imgUrl = this.uploadImageToOss(vxUrl, basicInfoId, 4);

            if (imgUrl != null) {
                AclPractitionerHiringBasicInfo basicInfo = new AclPractitionerHiringBasicInfo();
                basicInfo.setId(basicInfoId);
                basicInfo.setLastGraduateGrade(grade);
                basicInfo.setLastGraduateSchool(school);
                basicInfo.setLastGraduateCertificationOssPath(imgUrl);
                basicInfoMapper.updateByPrimaryKeySelective(basicInfo);

                resp.setCommonResult(new CommonResult(true, ZHBErrorConfig.getErrorInfo("800000")));
                resp.setImgUrl(imgUrl);
            } else {
                resp.setCommonResult(new CommonResult(false, ZHBErrorConfig.getErrorInfo("830024")));
            }

        } catch (Exception e) {
            e.printStackTrace();
            resp.setCommonResult(new CommonResult(false, e.getMessage()));
        }
        return resp;
    }

    @Override
    public SavePersonalStatementsResponseVO savePersonalStatements(SavePersonalStatementsRequestVO requestVO) {
        SavePersonalStatementsResponseVO resp = new SavePersonalStatementsResponseVO();
        try {
            List<AclPractitionerHiringPersonalStatements> personalStatementList = requestVO.getPersonalStatementList();

            Date curDate = new Date();
            personalStatementList.forEach(item -> {
                item.setIsActive(1);

                item.setCreatedAt(curDate);
                item.setUpdatedAt(curDate);

                item.setCreatedBy((long) -1);
                item.setUpdatedBy((long) -1);
            });

            if (personalStatementList.size() > 0) {
                personalStatementsMapper.batchInsert(personalStatementList);
            }

            resp.setCommonResult(new CommonResult(true, ZHBErrorConfig.getErrorInfo("800000")));

        } catch (Exception e) {
            e.printStackTrace();
            resp.setCommonResult(new CommonResult(false, e.getMessage()));
        }
        return resp;
    }

    @Override
    public SaveContractTermsConfirmsResponseVO saveContractTermsConfirms(SaveContractTermsConfirmsRequestVO requestVO) {
        SaveContractTermsConfirmsResponseVO resp = new SaveContractTermsConfirmsResponseVO();
        try {
            List<AclPractitionerHiringContractTermsConfirms> contractTermsConfirmsList = requestVO.getContractTermsConfirmsList();

            Date curDate = new Date();
            contractTermsConfirmsList.forEach(item -> {
                item.setIsActive(1);

                item.setCreatedAt(curDate);
                item.setUpdatedAt(curDate);

                item.setCreatedBy((long) -1);
                item.setUpdatedBy((long) -1);
            });

            if (contractTermsConfirmsList.size() > 0) {
                contractTermsConfirmsMapper.batchInsert(contractTermsConfirmsList);
            }

            resp.setCommonResult(new CommonResult(true, ZHBErrorConfig.getErrorInfo("800000")));

        } catch (Exception e) {
            e.printStackTrace();
            resp.setCommonResult(new CommonResult(false, e.getMessage()));
        }
        return resp;
    }

    private String uploadImageToOss(String imgUrl, Long hiringBasicInfoId, Integer targetUseFor) throws Exception {
        Map<String, Object> input = HttpUtil.getInput(imgUrl);
        if (!(boolean) input.get("success")) {
            throw new Exception(ZHBErrorConfig.getErrorInfo("830024"));
        }
        //获取头像流
        InputStream inputStream = (InputStream) input.get("is");
        //判断图像尺寸
        BufferedImage img = ImageIO.read(inputStream);

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(img, "jpg", os);
        inputStream = new ByteArrayInputStream(os.toByteArray());

        //上传图片至阿里云
        String prefix = "brokerHiring/" + hiringBasicInfoId + "/";
        String originalFilename = generateKey(targetUseFor);
        String key = prefix + originalFilename;
        String putFileToOss = ossService.putFileToOss(null, key, inputStream);

        return putFileToOss;
    }

    private String generateKey(int targetUseFor) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
        return targetUseFor+sdf.format(new Date()) + CommonUtil.getRandomNum(3)+".jpg";
    }
}
