package com.testor.module.partner.service.impl;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.testor.common.constant.StatusEnum;
import com.testor.module.partner.dao.TPartnerCertificateDao;
import com.testor.module.partner.model.domain.TPartnerCertificate;
import com.testor.module.partner.model.domain.TPartnerOrgRes;
import com.testor.module.partner.model.domain.TPartnerStaff;
import com.testor.module.partner.model.dto.TPartnerCertificateDTO;
import com.testor.module.partner.service.TPartnerCertificateService;
import com.testor.module.partner.service.TPartnerOrgResService;
import com.testor.module.partner.service.TPartnerStaffService;
import com.tongtech.tfw.backend.common.models.supers.SuperServiceImpl;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 相关方资质证书Service业务层处理
 *
 * @author testor-framework
 * @date 2022-06-01 14:12:52
 */
@Service
public class TPartnerCertificateServiceImpl extends SuperServiceImpl<TPartnerCertificateDao, TPartnerCertificate> implements TPartnerCertificateService {
    @Autowired(required = false)
    private TPartnerCertificateDao tPartnerCertificateDao;

    @Autowired(required = false)
    @Lazy
    private TPartnerOrgResService tPartnerOrgResService;

    @Autowired(required = false)
    @Lazy
    private TPartnerStaffService tPartnerStaffService;

    /**
     * 检测证书有效性
     *
     * @param Date
     * @return false- 未失效； true-失效
     */
    @Override
    public boolean checkValidity(Date date) {

        LocalDate localDate = DateUtil.toLocalDateTime(date).toLocalDate();

//        Date endDate = Date.from(dateTime.atZone(ZoneId.systemDefault()).toInstant());
        Date endDate = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
        Date nowDate = new Date();
        long diffVal = DateUtil.between(nowDate, endDate, DateUnit.DAY, false);
        if (diffVal <= 0) {
            return true;
        }
        return false;
    }

    /**
     * 检测 相关方机构/人员 证书 有效性
     *
     * @return false-异常   true- 正常
     */
    public boolean checkCertificateValidity(String bizId, List<String> certificateIds) {
        if (StrUtil.isBlank(bizId) && (certificateIds == null || certificateIds.size() == 0)) {
            return true;
        }
        QueryWrapper<TPartnerCertificate> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("state", "0");
        if (!StrUtil.isBlank(bizId)) {
            queryWrapper.eq("biz_id", bizId);
        }
        if (certificateIds != null && certificateIds.size() != 0) {
            queryWrapper.in("id", certificateIds);
        }
        int count = tPartnerCertificateDao.selectCount(queryWrapper);
        if (count > 0) {
            return false;
        }
        return true;
    }

    /**
     * 资质证书与业务id进行绑定
     *
     * @param bizId 业务id
     * @param ids   资质证书id
     */
    public boolean bindBizId(String bizId, List<String> ids) {
        if (StrUtil.isBlank(bizId) || ids == null || ids.size() == 0) {
            return false;
        }
        UpdateWrapper<TPartnerCertificate> updateWrapper = new UpdateWrapper();
        updateWrapper.in("id", ids);
        updateWrapper.set("biz_id", bizId);
        baseMapper.update(null, updateWrapper);
        return true;
    }

    /**
     * 定时任务： 每天检测证书是否过期
     */
    public void handleValidity() {
        LambdaQueryWrapper<TPartnerCertificate> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TPartnerCertificate::getState, "1");
        queryWrapper.eq(TPartnerCertificate::getStatus, StatusEnum.USE.getCode());
        queryWrapper.eq(TPartnerCertificate::getLongTerm,"2");
        List<TPartnerCertificate> certificateList = tPartnerCertificateDao.selectList(queryWrapper);
        if (certificateList == null || certificateList.size() == 0) {
            return;
        }

        List<TPartnerOrgRes> tPartnerOrgResList = new ArrayList<>();
        List<TPartnerStaff> tPartnerStaffList = new ArrayList<>();

        for (TPartnerCertificate certificate : certificateList) {
            Integer useType = certificate.getUseType();
            String bizId = certificate.getBizId();

            if (useType == 1) {
                TPartnerOrgRes tPartnerOrgRes = new TPartnerOrgRes();
                tPartnerOrgRes.setId(bizId);
                tPartnerOrgRes.setStatus("0");
                tPartnerOrgRes.setCertificateStatus(0);
                tPartnerOrgResList.add(tPartnerOrgRes);
            }

            if (useType == 2) {
                TPartnerStaff tPartnerStaff = new TPartnerStaff();
                tPartnerStaff.setId(bizId);
                tPartnerStaff.setStatus("0");
                tPartnerStaff.setCertificateStatus(0);
                tPartnerStaffList.add(tPartnerStaff);
            }
            certificate.setState("0");
        }
        // 修改资质证书 资质状态设为 0-过期
        updateBatchById(certificateList);
        tPartnerOrgResService.updateBatchById(tPartnerOrgResList);
        tPartnerStaffService.updateBatchById(tPartnerStaffList);
    }

    @Override
    public TPartnerCertificate editCertificate(TPartnerCertificateDTO addRequest) {
        if (ObjectHelper.isNotEmpty(addRequest)) {
            TPartnerCertificate data = BeanHelper.beanToBean(addRequest, TPartnerCertificate.class);
            String state = "1";
            //todo 参数校验，判断资质是否有效，资质是否长期有效
            if ("1".equals(addRequest.getLongTerm())) {
                state="1";
            }
            if ("2".equals(addRequest.getLongTerm())) {
                boolean checkResult = checkValidity( data.getValidEndDate() );
                if (checkResult) {
                    state = "0";
                }
            }
            data.setState(state);
            data.setId(null);
            boolean result = save(data);
            if (result) {
                return data;
            }
        }
        return null;
    }
}
