package com.yn.bftl.thirdparty.modules.baiduai.service;

import com.yn.bftl.common.modules.base.vo.MetaFileVO;
import com.yn.bftl.common.modules.company.entity.Company;
import com.yn.bftl.common.modules.company.enums.RelationType;
import com.yn.bftl.common.modules.configuration.entity.SalesSet;
import com.yn.bftl.common.modules.meta.entity.MetaFile;
import com.yn.bftl.common.modules.relation.entity.CompanyRelation;
import com.yn.bftl.thirdparty.common.exception.YnceErrorException;
import com.yn.bftl.thirdparty.common.repository.CompanyRelationRepository;
import com.yn.bftl.thirdparty.common.repository.CompanyRepository;
import com.yn.bftl.thirdparty.common.repository.SalesSetRepository;
import com.yn.bftl.thirdparty.common.service.BaseMemberService;
import com.yn.bftl.thirdparty.modules.baiduai.dto.BusinessLicenseRequestDTO;
import com.yn.bftl.thirdparty.modules.baiduai.dto.IdcardRequestDTO;
import com.yn.bftl.thirdparty.modules.baiduai.util.BaiduaiUtil;
import com.yn.bftl.thirdparty.modules.baiduai.util.Base64Util;
import com.yn.bftl.thirdparty.modules.baiduai.util.FileUtil;
import com.yn.bftl.thirdparty.modules.baiduai.vo.*;
import com.yn.bftl.thirdparty.modules.business.service.MetaFileService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * @Author：Vance
 * @Description：卡证识别service
 * @Date：2022/12/20 11:19
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ClassCardService extends BaseMemberService {

    @Resource
    private final BaiduaiUtil baiduaiUtil;
    @Resource
    private final SalesSetRepository salesSetRepository;
    @Resource
    private final CompanyRelationRepository companyRelationRepository;
    @Resource
    private final MetaFileService metaFileService;
    @Resource
    private final CompanyRepository companyRepository;

    /**
     * 身份证识别
     *
     * @param file
     * @return
     */
    public IdcardInfoVO idcard(MultipartFile file, String idcardSide) {
        if (!this.isStart()) {
            return null;
        }

        IdcardRequestDTO requestDTO = IdcardRequestDTO.builder()
                .id_card_side(idcardSide)
                .detect_risk(false).build();
        try {
            byte[] imgData = FileUtil.readFileByBytes(file);
            String imgStr = Base64Util.encode(imgData);
            requestDTO.setImage(URLEncoder.encode(imgStr, "UTF-8"));
        } catch (Exception e) {
            throw new YnceErrorException("图片转base64异常");
        }
        IdcardResponseVO idcardResponseVO = baiduaiUtil.executeIdcardRequest(requestDTO);
        Map<String, Map<String, Object>> words_result = idcardResponseVO.getWords_result();
        IdcardInfoVO idcardInfoVO = new IdcardInfoVO();
        idcardInfoVO.setIdCardType("1");
        if ("front".equals(idcardSide)) {
            idcardInfoVO.setIdCardName(words_result.get("姓名").get("words").toString());
            idcardInfoVO.setIdCardNumber(words_result.get("公民身份号码").get("words").toString());
            idcardInfoVO.setGender(words_result.get("性别").get("words").toString().equals("男") ? "1" : "2");
            idcardInfoVO.setWorkAddress(words_result.get("住址").get("words").toString());
        } else if ("back".equals(idcardSide)) {
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
            String strStartTime = words_result.get("签发日期").get("words").toString();
            idcardInfoVO.setIdCardStartTime(LocalDateTime.of(LocalDate.parse(strStartTime, dateTimeFormatter), LocalTime.MIN));
            String strEndTime = words_result.get("失效日期").get("words").toString();
            if (!"长期".equals(strEndTime)) {
                idcardInfoVO.setIdCardEndTime(LocalDateTime.of(LocalDate.parse(strEndTime, dateTimeFormatter), LocalTime.MIN));
            }
            idcardInfoVO.setIdCardIssuingAuthority(words_result.get("签发机关").get("words").toString());
        }

        return idcardInfoVO;
    }

    /**
     * 营业执照识别
     *
     * @param file
     * @param flag 是否校验 开启卡证识别
     * @param isUpload 是否上传到企业
     * @return
     */
    public BusinessLicenseInfoVO businessLicense(MultipartFile file, boolean flag, boolean isUpload) {
        if (flag) {
            if (!this.isStart()) {
                return null;
            }
        }

        BusinessLicenseRequestDTO dto = new BusinessLicenseRequestDTO();
        dto.setRisk_warn(false);
        try {
            byte[] imgData = FileUtil.readFileByBytes(file);
            String imgStr = Base64Util.encode(imgData);
            dto.setImage(URLEncoder.encode(imgStr, "UTF-8"));
        } catch (Exception e) {
            throw new YnceErrorException("图片转base64异常");
        }
        BusinessLicenseResponseVO businessLicenseResponseVO = baiduaiUtil.executeBusinessLicenseRequest(dto);
        BusinessLicenseInfoVO businessLicenseInfoVO = new BusinessLicenseInfoVO();
        if (isUpload) {
            MetaFile metaFile = metaFileService.fileUpload(file);
            Company company = getUser().getCompany();
            company.setBusinessLicense(metaFile);
            companyRepository.save(company);
            MetaFileVO metaFileVO = metaFileService.getMetaFileVO(metaFile);
            businessLicenseInfoVO.setPath(metaFileVO.getPath());
        }
        Map<String, Map<String, Object>> words_result = businessLicenseResponseVO.getWords_result();
        businessLicenseInfoVO.setLegalPersonIdCardName(words_result.get("法人").get("words").toString());
        String companyName = words_result.get("单位名称").get("words").toString();
        if (!"无".equals(companyName)) {
            businessLicenseInfoVO.setBusinessLicenseCompanyName(companyName);
        }
        if ("个体工商户".equals(words_result.get("类型").get("words").toString())) {
            businessLicenseInfoVO.setOrganizationType("2");
            if ("无".equals(companyName)) {
                businessLicenseInfoVO.setBusinessLicenseCompanyName("个体户" + businessLicenseInfoVO.getLegalPersonIdCardName());
            }
        } else {
            businessLicenseInfoVO.setOrganizationType("1");
        }
        businessLicenseInfoVO.setBusinessLicenseNumber(words_result.get("社会信用代码").get("words").toString());
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        String strBusinessLicenseStartTime = words_result.get("成立日期").get("words").toString();
        businessLicenseInfoVO.setBusinessLicenseStartTime(
                LocalDateTime.of(LocalDate.parse(strBusinessLicenseStartTime, dateTimeFormatter), LocalTime.MIN)
        );
        String strBusinessLicenseEndTime = words_result.get("有效期").get("words").toString();
        if (!"无".equals(strBusinessLicenseEndTime) && !"年月日".equals(strBusinessLicenseEndTime) && !"长期".equals(strBusinessLicenseEndTime)) {
            businessLicenseInfoVO.setBusinessLicenseEndTime(
                    LocalDateTime.of(LocalDate.parse(strBusinessLicenseEndTime, dateTimeFormatter), LocalTime.MIN)
            );
        }
        businessLicenseInfoVO.setBusinessLicenseCompanyAddress(words_result.get("地址").get("words").toString());

        return businessLicenseInfoVO;
    }

    /**
     * 银行卡识别
     */
    public BankcardInfoVO bankcard(MultipartFile file) {
        if (!this.isStart()) {
            return null;
        }

        String imgStr;
        try {
            byte[] imgData = FileUtil.readFileByBytes(file);
            imgStr = URLEncoder.encode(Base64Util.encode(imgData), "UTF-8");
        } catch (Exception e) {
            throw new YnceErrorException("图片转base64异常");
        }

        BankcardResponseVO bankcardResponseVO = baiduaiUtil.executeBankcardRequest(imgStr);
        BankcardResponseVO.Result result = bankcardResponseVO.getResult();
        BankcardInfoVO bankcardInfoVO = new BankcardInfoVO();
        bankcardInfoVO.setSettleAcctBankAcctNo(result.getBank_card_number());
        return bankcardInfoVO;
    }

    /**
     * 是否开启识别
     *
     * @return
     */
    private boolean isStart() {
        Company company = getUser().getCompany();
        Long salesSetCompanyId = company.getId();
        CompanyRelation companyRelation = companyRelationRepository
                .findFirstByPartyBAndType(company, RelationType.SUPPLYMARKETING);
        if (companyRelation != null) {
            salesSetCompanyId = companyRelation.getPartyA().getId();
        }
        SalesSet salesSet = salesSetRepository.findFirstByCompanyId(salesSetCompanyId);
        return salesSet == null || salesSet.getIsClassCard();
    }
}
