package com.sunxung.factoring.service.customerinformation.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sunxung.factoring.component.exception.ValidatorException;
import com.sunxung.factoring.component.util.*;
import com.sunxung.factoring.dict.impl.FileModuleDict;
import com.sunxung.factoring.entity.GridPage;
import com.sunxung.factoring.entity.acceptance.AcceptanceSignConfirmationElectronicInfo;
import com.sunxung.factoring.entity.customerinformation.ElectronicSignaturePersonal;
import com.sunxung.factoring.entity.entprise.Enterprise;
import com.sunxung.factoring.entity.signconfirmation.SignConfirmationElectronicInfo;
import com.sunxung.factoring.entity.sys.Dictionary;
import com.sunxung.factoring.entity.sys.FileStorage;
import com.sunxung.factoring.mapper.customerinformation.ElectronicSignaturePersonalMapper;
import com.sunxung.factoring.service.acceptancesheet.IAcceptanceSignConfirmationElectronicInfoService;
import com.sunxung.factoring.service.customerinformation.IElectronicSignaturePersonalService;
import com.sunxung.factoring.service.signconfirmation.ISignConfirmationElectronicInfoService;
import com.sunxung.factoring.service.sys.DictionaryService;
import com.sunxung.factoring.service.sys.FileStorageService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * --电子签个人信息表 服务实现类
 * </p>
 *
 * @author liutao
 * @since 2023-05-13
 */
@Service
public class ElectronicSignaturePersonalServiceImpl extends ServiceImpl<ElectronicSignaturePersonalMapper, ElectronicSignaturePersonal> implements IElectronicSignaturePersonalService {

    @Autowired
    private IAcceptanceSignConfirmationElectronicInfoService acceptanceSignConfirmationElectronicInfoService;

    @Autowired
    private ISignConfirmationElectronicInfoService signConfirmationElectronicInfoService;

    @Autowired
    private ElectronicSignaturePersonalMapper  electronicSignaturePersonalMapper;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private DictionaryService dictionaryService;

    @Override
    public GridPage findByName(String name,Integer status, Integer page, Integer rows) {
        Page objectPage = PageHelper.startPage(page, rows);
        List<ElectronicSignaturePersonal> list  = electronicSignaturePersonalMapper.findByName(name,status);
        for (ElectronicSignaturePersonal personal : list){
            if (StringUtils.isNotEmpty(personal.getCardType())){
                Dictionary dictionary = dictionaryService.getByCode(personal.getCardType());
                personal.setCardTypeName(dictionary.getName());
            }
        }
        return new GridPage(rows,page,objectPage.getTotal(),list);
    }

    @Override
    public GridPage findByComName(String name,Integer status, Integer page, Integer rows) {
        Page objectPage = PageHelper.startPage(page, rows);
        List<Enterprise> list = electronicSignaturePersonalMapper.findByComName(name,status);
        return new GridPage(rows,page,objectPage.getTotal(),list);
    }

    @Override
    public void flush(Long id) {
        ElectronicSignaturePersonal electronicSignaturePersonal = getById(id);
        //获取认证状态
        String result = ElectronicSignatureUtil.getAuthInfo(electronicSignaturePersonal.getFddCustomerId(), "1");
        if ("1".equals(result)){
            electronicSignaturePersonal.setAuthStatus(1);
            updateById(electronicSignaturePersonal);
        }
    }

    @Override
    public ElectronicSignaturePersonal getDetail(Long id) {
        ElectronicSignaturePersonal electronicSignaturePersonal = getById(id);
        if (StringUtils.isNotEmpty(electronicSignaturePersonal.getCardType())){
            Dictionary dictionary = dictionaryService.getByCode(electronicSignaturePersonal.getCardType());
            electronicSignaturePersonal.setCardTypeName(dictionary.getName());
        }
        List<FileStorage> fileStorages = fileStorageService.findByBelongIdAndBelongType(id.toString(), FileModuleDict.ChildEnum.ENTERPRISE_CARD_PHOTO.getCode());
        if (CollectionUtil.isNotEmpty(fileStorages)){
            electronicSignaturePersonal.setCardPhotoFile(fileStorages.get(0));
        }
        List<FileStorage> list = fileStorageService.findByBelongIdAndBelongType(id.toString(), FileModuleDict.ChildEnum.ENTERPRISE_CARD_REV_PHOTO.getCode());
        if (CollectionUtil.isNotEmpty(list)){
            electronicSignaturePersonal.setCardRevPhotoFile(list.get(0));
        }
        return electronicSignaturePersonal;
    }

    @Override
    public void urlJob() {
        Date date = new Date();
        Date dateTime = DateUtil.offsetDay(date, -6);
        List<ElectronicSignaturePersonal> list = lambdaQuery().eq(ElectronicSignaturePersonal::getAuthStatus, 0).list();
        if(CollectionUtil.isNotEmpty(list)){
            for (ElectronicSignaturePersonal electronicSignaturePersonal : list) {
                if(electronicSignaturePersonal.getShortAuthUrlCreat() == null || StringUtil.isEmpty(electronicSignaturePersonal.getShortAuthUrl())){
                    String shortUrl = ElectronicSignatureUtil.shortUrl(null, electronicSignaturePersonal.getShortAuthUrl());
                    electronicSignaturePersonal.setShortAuthUrl(shortUrl);
                    electronicSignaturePersonal.setShortAuthUrlCreat(date);
                }else if(electronicSignaturePersonal.getShortAuthUrlCreat().compareTo(dateTime) < 1){
                    String shortUrl = ElectronicSignatureUtil.shortUrl(null, electronicSignaturePersonal.getShortAuthUrl());
                    electronicSignaturePersonal.setShortAuthUrl(shortUrl);
                    electronicSignaturePersonal.setShortAuthUrlCreat(date);
                }
                updateById(electronicSignaturePersonal);
            }
        }
    }

    @Override
    public List<ElectronicSignaturePersonal> findByIdForC(Long id) {
        List<ElectronicSignaturePersonal> list ;
        if(id != null){
            list = lambdaQuery().eq(ElectronicSignaturePersonal::getId, id).list();
        }else {
            list = list();
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateInfo(ElectronicSignaturePersonal electronicSignaturePersonal) {
        ElectronicSignaturePersonal old = lambdaQuery().eq(ElectronicSignaturePersonal::getName, electronicSignaturePersonal.getName())
                .eq(ElectronicSignaturePersonal::getMobile, electronicSignaturePersonal.getMobile()).one();
        if(old!=null && !old.getId().equals(electronicSignaturePersonal.getId())){
            throw new ValidatorException(CodeUtil.FAIL,"已经存在相同名称，相同电话的个人信息!");
        }
        ElectronicSignaturePersonal oldInfo = getById(electronicSignaturePersonal.getId());
        if (oldInfo == null) {
            throw new ValidatorException(CodeUtil.FAIL, "要修改的数据不存在！");
        } else {
            electronicSignaturePersonal = getAuthInfo(electronicSignaturePersonal);
            //更新附件
            if (CollectionUtil.isNotEmpty(electronicSignaturePersonal.getDeleteIds())){
                for (Long id : electronicSignaturePersonal.getDeleteIds()){
                    fileStorageService.deleteFileStorage(id);
                }
            }
            if (CollectionUtil.isNotEmpty(electronicSignaturePersonal.getFileIds())){
                for (Long id : electronicSignaturePersonal.getFileIds()){
                    fileStorageService.updateBusinessId(id,electronicSignaturePersonal.getId());
                }
            }
            updateById(electronicSignaturePersonal);
        }
    }

    @Override
    public ElectronicSignaturePersonal getAuthInfo(ElectronicSignaturePersonal electronicSignaturePersonal) {
        String openId = UUID.randomUUID().toString().trim().replaceAll("-", "").toUpperCase();
        //法大大认证
        String name = electronicSignaturePersonal.getName();
        String mobile = electronicSignaturePersonal.getMobile();
        String customerId = ElectronicSignatureUtil.registerAccount(openId, "1");
        String authResult = ElectronicSignatureUtil.getAuthUrlPersonalFace(customerId,"1",name,mobile);
        JSONObject authJson = (JSONObject) JSONObject.parse(authResult);
        String authUrl = authJson.getString("data");
        if (authUrl == null || customerId == null) {
            throw new ValidatorException(CodeUtil.FAIL, "生成认证链接出错");
        }
        String shortUrl = ElectronicSignatureUtil.shortUrl(null, authUrl);
        electronicSignaturePersonal.setAuthStatus(0);
        electronicSignaturePersonal.setOpenId(openId);
        electronicSignaturePersonal.setAuthUrl(authUrl);
        electronicSignaturePersonal.setShortAuthUrl(shortUrl);
        electronicSignaturePersonal.setShortAuthUrlCreat(new Date());
        electronicSignaturePersonal.setFddCustomerId(customerId);
        return electronicSignaturePersonal;
    }

    @Override
    public String getAuthDeatil(String customerId) {
        ElectronicSignaturePersonal electronicSignaturePersonal = lambdaQuery().eq(ElectronicSignaturePersonal::getFddCustomerId, customerId).one();
        if (electronicSignaturePersonal == null) {
            throw new ValidatorException(CodeUtil.FAIL,"不存在该认证信息！");
        }
        String result = ElectronicSignatureUtil.getAuthInfoDetail(electronicSignaturePersonal.getFddCustomerId(), "1");
        return result;
    }

    @Override
    public void flushUrl(Long id) {
//        List<AcceptanceSignConfirmationElectronicInfo> acceptanceSignConfirmationElectronicInfos = acceptanceSignConfirmationElectronicInfoService.lambdaQuery().eq(AcceptanceSignConfirmationElectronicInfo::getElectronicSignaturePersonalId, id).eq(AcceptanceSignConfirmationElectronicInfo::getSignStatus, 0).list();
//        List<SignConfirmationElectronicInfo> signConfirmationElectronicInfos = signConfirmationElectronicInfoService.lambdaQuery().eq(SignConfirmationElectronicInfo::getElectronicSignaturePersonalId, id).eq(SignConfirmationElectronicInfo::getSignStatus, 0).list();
//        if(CollectionUtil.isNotEmpty(acceptanceSignConfirmationElectronicInfos)){
//            throw new ValidatorException(CodeUtil.FAIL,"该签署人有未签署的验收单签署确认信息，不能重新刷新认证链接！");
//        }
//        if(CollectionUtil.isNotEmpty(signConfirmationElectronicInfos)){
//            throw new ValidatorException(CodeUtil.FAIL,"该签署人有未签署的签署确认信息，不能重新刷新认证链接！");
//        }
        ElectronicSignaturePersonal electronicSignaturePersonal = getById(id);
        electronicSignaturePersonal = getAuthInfo(electronicSignaturePersonal);
        updateById(electronicSignaturePersonal);
    }

    @Override
    public void delete(Long id) {
        ElectronicSignaturePersonal electronicSignaturePersonal = getById(id);
        if(electronicSignaturePersonal.getAuthStatus().equals(1)){
            throw new ValidatorException(CodeUtil.FAIL,"已认证不支持删除！");
        }else {
            removeById(id);
        }
    }

}
