package com.cool.store.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.ocr20191230.models.*;
import com.aliyun.ocr_api20210707.Client;
import com.aliyun.ocr_api20210707.models.RecognizeAdvancedRequest;
import com.aliyun.ocr_api20210707.models.RecognizeFoodManageLicenseRequest;
import com.aliyun.ocr_api20210707.models.RecognizeFoodManageLicenseResponse;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.http.MethodType;
import com.cool.store.enums.ErrorCodeEnum;
import com.cool.store.enums.IDCardSideEnum;
import com.cool.store.enums.SmsCodeTypeEnum;
import com.cool.store.exception.ApiException;
import com.cool.store.exception.ServiceException;
import com.cool.store.response.ResponseResult;
import com.cool.store.service.AliyunService;
import com.cool.store.utils.poi.StringUtils;
import com.cool.store.vo.BusinessLicenseInfoVO;
import com.cool.store.vo.FoodLicenseVO;
import com.cool.store.vo.IdentityCardInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
import java.util.Optional;

@Service
@Slf4j
public class AliyunServiceImpl implements AliyunService {

    @Value("${aliyun.accessKeyId:null}")
    private String accessKeyId;

    @Value("${aliyun.accessKeySecret:null}")
    private String accessKeySecret;

//    @Value("${aliyun.sms.domain}")
    private String smsDomain;



    @Override
    public IdentityCardInfoVO getIdentityCardInfo(String faceImageUrl,
                                                  IDCardSideEnum sideEnum)  throws ApiException {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "ocr.cn-shanghai.aliyuncs.com";
        try {
            com.aliyun.ocr20191230.Client client = new com.aliyun.ocr20191230.Client(config);
            URL url = new URL(faceImageUrl);
            InputStream inputStream = url.openConnection().getInputStream();
            com.aliyun.ocr20191230.models.RecognizeIdentityCardAdvanceRequest recognizeIdentityCardAdvanceRequest = new com.aliyun.ocr20191230.models.RecognizeIdentityCardAdvanceRequest()
                    .setImageURLObject(inputStream)
                    .setSide(sideEnum.getCode());
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
            RecognizeIdentityCardResponse idCardResponse = client.recognizeIdentityCardAdvance(recognizeIdentityCardAdvanceRequest, runtime);
            log.info("身份证解析结果：{}", JSONObject.toJSONString(idCardResponse));
            RecognizeIdentityCardResponseBody.RecognizeIdentityCardResponseBodyDataFrontResult frontResult = Optional.ofNullable(idCardResponse).map(o -> o.getBody()).map(o -> o.data).map(o -> o.frontResult).orElse(null);
            if(Objects.nonNull(frontResult)){
                String username = frontResult.name;
                String liveAddress = frontResult.address;
                String birthdate = frontResult.birthDate;
                if(StringUtils.isNotBlank(birthdate)){
                    birthdate = convertDate(birthdate, "yyyyMMdd");
                }
                String sex = frontResult.gender;
                String idCard = frontResult.IDNumber;
                String nation = frontResult.nationality;
                IdentityCardInfoVO result = new IdentityCardInfoVO(username, liveAddress, birthdate, sex, idCard, nation);
                log.info("身份证解析：{}", JSONObject.toJSONString(result));
                return result;
            }
            return null;
        } catch (com.aliyun.tea.TeaException e) {
            log.error("身份证解析报错TeaException：{}", e);
            throw new ApiException(e.getMessage());
        } catch (MalformedURLException e) {
            log.error("身份证解析报错MalformedURLException：{}", e);
            throw new ApiException(e.getMessage());
        } catch (IOException e) {
            log.error("身份证解析报错IOException：{}", e);
            throw new ApiException(e.getMessage());
        } catch (Exception e) {
            log.error("身份证解析报错Exception：{}", e);
            throw new ApiException(e.getMessage());
        }
    }

    public static String convertDate(String date, String format) {
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
            LocalDate localDate = LocalDate.parse(date, formatter);
            return localDate.toString();
        } catch (Exception e) {
            throw new ServiceException(ErrorCodeEnum.DATA_CONVERT_ERROR);
        }
    }

    @Override
    public BusinessLicenseInfoVO getBusinessLicenseInfo(String imageUrl) throws ApiException {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        config.endpoint = "ocr.cn-shanghai.aliyuncs.com";
        try {
            com.aliyun.ocr20191230.Client client = new com.aliyun.ocr20191230.Client(config);
            //非上海区域OSS必须使用流转换后使用
            URL url = new URL(imageUrl);
            InputStream inputStream = url.openConnection().getInputStream();
            RecognizeBusinessLicenseAdvanceRequest recognizeBusinessLicenseRequest = new RecognizeBusinessLicenseAdvanceRequest()
                    .setImageURLObject(inputStream);
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
            RecognizeBusinessLicenseResponse recognizeBusinessLicenseResponse = client.recognizeBusinessLicenseAdvance(recognizeBusinessLicenseRequest, runtime);
            log.info("营业执照解析结果：{}", JSONObject.toJSONString(recognizeBusinessLicenseResponse));
            RecognizeBusinessLicenseResponseBody.RecognizeBusinessLicenseResponseBodyData result = Optional.ofNullable(recognizeBusinessLicenseResponse).map(o -> o.getBody()).map(o -> o.data).orElse(null);
            if (Objects.nonNull(result)){
                String address = result.address;//住所（经营场所）
                String registerNumber = result.registerNumber;
                String legalPerson = result.legalPerson;//法人
                String validPeriod = result.validPeriod;//有效期
                String establishDate = result.establishDate;
                String name = result.name;//营业执照名称
                String type = result.type;//类型
                BusinessLicenseInfoVO response = new  BusinessLicenseInfoVO(registerNumber,address,legalPerson,validPeriod,establishDate,name,type);
                return response;
            }
            return null;
        } catch (com.aliyun.tea.TeaException e) {
            log.error("营业执照解析报错TeaException：{}", e);
            throw new ApiException(e.getMessage());
        } catch (MalformedURLException e) {
            log.error("营业执照解析报错MalformedURLException：{}", e);
            throw new ApiException(e.getMessage());
        } catch (IOException e) {
            log.error("营业执照解析报错IOException：{}", e);
            throw new ApiException(e.getMessage());
        } catch (Exception e) {
            log.error("营业执照解析报错Exception：{}", e);
            throw new ApiException(e.getMessage());
        }
    }

    @Override
    public FoodLicenseVO getFoodLicense(String imageUrl) throws ApiException {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        config.endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
        try {
            com.aliyun.ocr_api20210707.Client  client = new com.aliyun.ocr_api20210707.Client(config);
            //非上海区域OSS必须使用流转换后使用
            URL url = new URL(imageUrl);
            InputStream inputStream = url.openConnection().getInputStream();
            com.aliyun.ocr_api20210707.models.RecognizeFoodManageLicenseRequest recognizeFoodManageLicenseRequest = new com.aliyun.ocr_api20210707.models.RecognizeFoodManageLicenseRequest();
//            recognizeFoodManageLicenseRequest.setBody(inputStream);
            recognizeFoodManageLicenseRequest.setUrl(imageUrl);
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
            RecognizeFoodManageLicenseResponse recognizeFoodManageLicenseResponse = client.recognizeFoodManageLicenseWithOptions(recognizeFoodManageLicenseRequest,runtime);
            log.info("食营解析结果：{}", JSONObject.toJSONString(recognizeFoodManageLicenseResponse));
            String result = Optional.ofNullable(recognizeFoodManageLicenseResponse).map(o -> o.getBody()).map(o -> o.data).orElse(null);
            if (StringUtils.isNotBlank(result)){
                JSONObject data = JSONObject.parseObject(JSON.parseObject(result).get("data").toString());
                String operatorName = data.getString("operatorName");//经营者名称
                String legalRepresentative = data.getString("legalRepresentative");//法人
                String businessAddress = data.getString("businessAddress");//经营场所
                String mainBusiness = data.getString("mainBusiness");//主体业态
                String businessScope = data.getString("businessScope");//经营项目
                String licenceNumber = data.getString("licenceNumber");//许可证编号
                FoodLicenseVO foodLicenseVO = new FoodLicenseVO();
                foodLicenseVO.setBusinessAddress(businessAddress);
                foodLicenseVO.setBusinessScope(businessScope);
                foodLicenseVO.setLegalRepresentative(legalRepresentative);
                foodLicenseVO.setMainBusiness(mainBusiness);
                foodLicenseVO.setLicenceNumber(licenceNumber);
                foodLicenseVO.setOperatorName(operatorName);
                return foodLicenseVO;
            }
            return null;
        } catch (com.aliyun.tea.TeaException e) {
            log.error("食营解析报错TeaException：{}", e);
            throw new ApiException(e.getMessage());
        } catch (MalformedURLException e) {
            log.error("食营解析报错MalformedURLException：{}", e);
            throw new ApiException(e.getMessage());
        } catch (IOException e) {
            log.error("食营解析报错IOException：{}", e);
            throw new ApiException(e.getMessage());
        } catch (Exception e) {
            log.error("食营解析报错Exception：{}", e);
            throw new ApiException(e.getMessage());
        }
    }

    @Override
    public ResponseResult sendMessage(String mobile, SmsCodeTypeEnum codeType) {
        String msgKey = codeType + ":" + mobile;
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(smsDomain);
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");

        return null;
    }
}
