package com.mortals.xhx.modules.supplement.task;

import cn.hutool.core.date.DateTime;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.PageInfo;
import com.mortals.framework.service.ITask;
import com.mortals.framework.service.ITaskExcuteService;
import com.mortals.framework.util.DateUtils;
import com.mortals.xhx.common.code.ApplicantTypeEnums;
import com.mortals.xhx.common.code.NodeTypeEnum;
import com.mortals.xhx.common.utils.DateByAffairUtils;
import com.mortals.xhx.common.utils.FilterSuppDataUtils;
import com.mortals.xhx.common.utils.SnowFlakeUtil;
import com.mortals.xhx.modules.implementlist.model.ImplementlistEntity;
import com.mortals.xhx.modules.implementlist.service.ImplementlistService;
import com.mortals.xhx.modules.information.dao.InformationDao;
import com.mortals.xhx.modules.information.model.InformationEntity;
import com.mortals.xhx.modules.supplement.model.SupplementEntity;
import com.mortals.xhx.modules.supplement.model.SupplementQuery;
import com.mortals.xhx.modules.supplement.service.SupplementService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liaoxin
 * @Date: 2021-08-2021/8/2-10:44
 * @Description:数据清洗
 */
@Slf4j
@Component("supplementTaskImpl")
public class SupplementTaskImpl implements ITaskExcuteService {

    @Autowired
    private SupplementService supplementService;

    @Autowired
    private ImplementlistService implementlistService;

    @Autowired
    private InformationDao informationDao;

    @Override
    public void excuteTask(ITask task) throws AppException {
        //1.查询上月的表是否存在未清洗的数据
        List<SupplementEntity> supplementEntities = queryDataThatHasNotBeenPushed(task.getExcuteParam());
        //开始进行数据清洗
        this.dataCleaning(supplementEntities);
    }


    @Override
    public void stopTask(ITask task) throws AppException {

    }

    private void dataCleaning(List<SupplementEntity> supplementEntities) {
        if (!supplementEntities.isEmpty()) {
            List<InformationEntity> informationQueries = new ArrayList<>();
            List<SupplementEntity> collect = supplementEntities.parallelStream().map(e -> {
                //TODO：查询实施清单信息，通过事项编码查询有问题（但因数据库存储的事项数据是条件过滤后的，故暂时不改动查询），后期改动
                ImplementlistEntity thImplement = implementlistService.getThImplement(e.getImplCode());
                try {
                    InformationEntity informationQuery = new InformationEntity();
                    //组装第一次业务数据（清洗后的）
                    informationQuery = assemblyOfficeData(informationQuery, e);
                    if (null != thImplement) {
                        informationQuery.setDeptCode(thImplement.getDeptCode());
                        informationQuery.setAreaCode(thImplement.getAreaCode());
                        informationQuery.setEventCode(thImplement.getEventCode());
                        informationQuery.setEventName(thImplement.getEventName());
                        informationQuery.setIsCharge(thImplement.getIsCharges());
                        //是否转化成功：0默认 1成功
                        informationQuery.setIsSuccess("1");
                        //是否推送（0 否 1是）
                        informationQuery.setIsReport("0");
                        //设置 失败次数 默认为0
                        informationQuery.setFailTimes(0);
                        // 是否执行转化（0.未执行  1.已执行）
                        e.setIsExecute("1");
                        //是否转化成功（0默认 1成功）
                        e.setIsSuccess("1");
                    } else {
                        e.setFailReason(" Err:实施清单不存在");
                        // 是否执行转化（0.未执行  1.已执行）
                        e.setIsExecute("1");
                        //是否转化成功（0默认 1成功）
                        e.setIsSuccess("0");
                        informationQuery.setFailReason(" Err:实施清单不存在");
                        informationQuery.setIsSuccess("0");
                    }
                    e.setUpdateDate(DateTime.now());
                    informationQueries.add(informationQuery);
                    return e;
                } catch (Exception ex) {
                    log.error("转换失败:SupplementID:" + e.getId());
                    log.error("转换失败：失败原因" + ex.getMessage());
                    return e;
                }
            }).collect(Collectors.toList());
            supplementService.update(collect,null);
            informationDao.insertBatch(informationQueries);
        } else {
            log.info("没有从临时表中获取到需要清洗的数据");
        }
    }

    private InformationEntity assemblyOfficeData(InformationEntity informationQuery, SupplementEntity supplementEntity) throws Exception {
        //流程时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date randomDate = DateByAffairUtils.getDayWorkingTimeByRandom(sdf.parse(supplementEntity.getApplyTime()), 9, 17);
        informationQuery.setId(SnowFlakeUtil.get().nextId());
        //默认为0：网络办件
        informationQuery.setApplyType("0");
        informationQuery.setAffairName(supplementEntity.getImplName() + DateUtils.getDateTimeStr(randomDate, null));
        //申请人属性,1：法人 2：自然人
        informationQuery.setApplicantAttributes(Integer.valueOf(supplementEntity.getApplicationType()));
        //申请人证件类型
        informationQuery.setApplicantCardType(supplementEntity.getApplicationCardType());
        //申请人证件号码
        informationQuery.setApplicantCardNumbe(supplementEntity.getApplicationId().trim());
        //申请人手机号码
        informationQuery.setApplicantPhoneNumber(supplementEntity.getApplicationPhone().trim());
        //申请人姓名
        informationQuery.setApplicantName(supplementEntity.getApplicationName().trim());
        //申请人性别
        informationQuery.setApplicantSex(FilterSuppDataUtils.parseGender(supplementEntity.getApplicationId().trim()));
        //无论是否是自然人还是都直接将申请人copy到联系人
        informationQuery.setContactCardType(supplementEntity.getApplicationCardType());
        informationQuery.setContactIdCard(supplementEntity.getApplicationId().trim());
        informationQuery.setContactName(supplementEntity.getApplicationName().trim());
        informationQuery.setContactPhone(supplementEntity.getApplicationPhone().trim());
        //TODO 时间这里可以修改下，最好在一段区间范围内
        informationQuery.setGenTime(randomDate);
        informationQuery.setCompleteTime(DateByAffairUtils.getTimeByAddRandom(randomDate, 6));
        if (String.valueOf(supplementEntity.getApplicationType()).equals(ApplicantTypeEnums.LEGAL.getCode())) {
            //设置法人
            informationQuery.setLegalPerson(supplementEntity.getLegalPerson());
            informationQuery.setOrganizationCardNumber(supplementEntity.getMechanismId());
            //设置联系人
            informationQuery.setContactName(supplementEntity.getLegalPerson().trim());
            informationQuery.setContactIdCard(supplementEntity.getApplicationCardType().trim());
            informationQuery.setContactCardType(supplementEntity.getApplicationId());
            informationQuery.setContactPhone(supplementEntity.getApplicationPhone().trim());
            informationQuery.setApplyNum(supplementEntity.getMechanismType()); //临时征用  机构性质
        }
        //设置受理人
        informationQuery.setAcceptId(supplementEntity.getAcceptId());
        informationQuery.setAcceptName(supplementEntity.getAcceptName());
        informationQuery.setAcceptPhone(supplementEntity.getAcceptPhone());
        informationQuery.setCurHandlerName(supplementEntity.getAcceptName());
        informationQuery.setIsReport("0");
        informationQuery.setIsCharge("0");


        informationQuery.setSystemCode(supplementEntity.getSysCode());
        //测试暂时写死
        informationQuery.setNodeType(NodeTypeEnum.受理.getCode());
        informationQuery.setBizStatus(NodeTypeEnum.受理.getDesc());
        informationQuery.setProcessStatusName("申请并受理");
        informationQuery.setDoThingProperty("0");
        informationQuery.setApplyNum("1");
        informationQuery.setPickupType("3");

        informationQuery.setCreateTime(DateTime.now());
        informationQuery.setUpdateTime(informationQuery.getCreateTime());
        return informationQuery;
    }

    private List<SupplementEntity> queryDataThatHasNotBeenPushed(String excuteParam) {
        List<SupplementEntity> supplementEntities;
        SupplementQuery supplementQuery = new SupplementQuery();
        supplementQuery.setIsExecute("0");
        supplementQuery.setIsSuccess("0");
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPrePageResult(Integer.parseInt(excuteParam));
        //TODO： 条数限制
        //本月第一天
        String theFirstDayOfTheMonth = new SimpleDateFormat("yyyy-MM-dd").format(DateByAffairUtils.getMonthFirstDate(new Date()));
        //当月第几天
        String theDayOfTheMonth = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        //每月第一天，去查询上月的数据是否存在未处理的数据
        if (theFirstDayOfTheMonth.equals(theDayOfTheMonth)){
            //获取上月第一天的开始时间
            supplementQuery.setCreateDateStart(
                    DateByAffairUtils.getLastMonthFirstDate(new Date(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").toPattern()));
            //获取上月最后一天的结束时间
            supplementQuery.setCreateDateEnd(
                    DateByAffairUtils.getLastMonthLastDate(new Date(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").toPattern()));
            try {
                supplementEntities = supplementService.find(supplementQuery, pageInfo,null).getList();
            } catch (Exception e) {
                log.info("报错属于业务正常，查询当月表数据");
                supplementEntities = queryCurrentMonthTableData(supplementQuery, pageInfo);
                return supplementEntities;
            }
            if (supplementEntities.size() <= 0) {
                supplementEntities = queryCurrentMonthTableData(supplementQuery, pageInfo);
            }
        }else {
            //上月未存在未处理的数据，则查询当月数据
            supplementEntities = queryCurrentMonthTableData(supplementQuery,pageInfo);
        }


        return supplementEntities;
    }

    private List<SupplementEntity> queryCurrentMonthTableData(SupplementQuery supplementQuery, PageInfo pageInfo) {
        //获取当月的开始时间
        supplementQuery.setCreateDateStart(
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(DateByAffairUtils.getMonthFirstDate(new Date())));
        //获取当前时间
        supplementQuery.setCreateDateEnd(
                DateUtils.convertTime2Str(new Date().getTime(), DateUtils.P_yyyy_MM_dd_HH_mm_ss));
        return supplementService.find(supplementQuery, pageInfo,null).getList();
    }

}
