package com.sifang.modules.task;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.changes.dao.CustomerEntryChangeRecordDao;
import com.sifang.modules.changes.entity.CrmCustomerEntryChangeRecord;
import com.sifang.modules.customer.Service.CustomerEntryService;
import com.sifang.modules.customer.Service.GuangFaManagemnetService;
import com.sifang.modules.customer.constant.PartnerConstants;
import com.sifang.modules.customer.dao.CrmCustomerIncomingApplicationDao;
import com.sifang.modules.customer.dao.CustomerEntrySurveyRecordDao;
import com.sifang.modules.partner.service.GuangfaOperatingService;
import com.sifang.modules.partner.utils.GuangfaQryContractVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @title: GuangFaGetStatusTask
 * @Author Tan
 * @Date: 2024/7/19 15:57
 * @Version 1.0
 */
@Component
public class GuangFaGetStatusTask {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    CustomerEntryService customerEntryService;

    @Autowired
    CrmCustomerIncomingApplicationDao incomingApplicationDao;

    @Autowired
    private GuangfaOperatingService guangfaOperatingService;
    @Autowired
    private CustomerEntryChangeRecordDao changeRecordDao;
    @Autowired
    private GuangFaManagemnetService guangFaManagemnetService;

    @Scheduled(cron = "0 0/10 * * * ?")
    void getqueryGuangFaPreAuditState() {
        logger.info("getqueryGuangFaPreAuditState 获取商机注册状态");
        long begin = System.currentTimeMillis();
        String partnerId = "03";//广发资方id
        StringBuffer sf = new StringBuffer();
        sf.append(" select a.id AS entryId FROM crm_customer_entry a ");
        sf.append(" INNER JOIN `crm_customer_incoming_application` i on i.entry_id=a.id and i.if_delete<>'1'  ");
        sf.append(" WHERE a.apply_status = 1 and a.status<>'b' and a.partner_id = " +partnerId);
        List<Record> list = Db.find(sf.toString());
        logger.info("集合size"+list.size());
        if(list.size()>0){
            for(Record record : list){
                try {
                    customerEntryService.dealGfQueryData(record.getStr("entryId"));
                }catch (Exception e){
                    logger.error("getqueryGuangFaPreAuditState 获取商机注册状态异常",e);
                }
            }
        }
        long end = System.currentTimeMillis();
        logger.info("getqueryGuangFaPreAuditState 定时任务结束，共耗时：[" + (end-begin) / 1000 + "]秒");
    }

    @Scheduled(cron = "0 0/10 * * * ?")
    void getInputPieceStatus(){
        logger.info(">>>>>>>>getInputPieceStatus  定时任务开始");
        long begin = System.currentTimeMillis();
        List<Record> customerEntries = customerEntryService.getInputPieceInProgress(PartnerConstants.PARTNER_ID_GF);
        for (Record customerEntry : customerEntries) {
            customerEntryService.dealGfQueryData(customerEntry.getStr("id"));
        }
        long end = System.currentTimeMillis();
        logger.info("getInputPieceStatus 定时任务结束，共耗时：[" + (end-begin) / 1000 + "]秒");
    }


    @Scheduled(cron = "0 0/10 * * * ?")
    void queryContract(){
        logger.info(">>>>>>>>queryContract  定时任务开始");
        long begin = System.currentTimeMillis();

//        List<CrmCustomerIncomingApplication> applicationList = incomingApplicationDao.getInputPieceInProgress(PartnerConstants.PARTNER_ID_GF);
        StringBuffer sb=new StringBuffer();
        //查询需要同步合同信息的电站
        sb.append(" select cm.id as cid, cm.entry_id as entryId,  cm.status as cStatus, ca.input_piece_id as inputPieceId from crm_customer_incoming_application ca left join crm_customer_contract_management cm on cm.entry_id = ca.entry_id where ca.partner_id = '03' and ca.if_delete = 0 and cm.status in ('1','6' ,'b', 'c', 'd','l') ");
        List<Record> list=Db.find(sb.toString());
        List<String> inputPieceIds = list.stream().map(r -> r.getStr("inputPieceId")).collect(Collectors.toList());
        Map<String, String> kv = list.stream().collect(Collectors.toMap(r -> r.getStr("inputPieceId"), r -> r.getStr("entryId")));
        for (String inputPieceId : inputPieceIds) {
            List<String> idList = new ArrayList<>();
            idList.add(inputPieceId);
            if (!StringUtils.isEmpty(idList)){
                try {
                    List<GuangfaQryContractVO> result = guangfaOperatingService.queryContract(PartnerConstants.PARTNER_ID_GF, idList);
                    GuangfaQryContractVO v = result.get(0);
                    String status = v.getContractState();
                    customerEntryService.updateContractState(status,kv.get(v.getInputPieceId()),v.getContractNo(),v.getContractNormState());
                } catch (Exception e) {
                    logger.warn("queryContract fail for "+inputPieceId, e);
                }
            }
        }
        long end = System.currentTimeMillis();
        logger.info("queryContract 定时任务结束，共耗时：[" + (end-begin) / 1000 + "]秒");
    }

    @Scheduled(cron = "0 0/15 * * * ?")
    void getGuangFaThirdStatus(){
        logger.info(">>>>>>>>getGuangFaThirdStatus  定时任务开始");
        long begin = System.currentTimeMillis();
        List<Record> inputPiece = Db.find(" SELECT entry_id FROM crm_customer_incoming_application WHERE merge_Sate IN('20','25','60') " +
                "AND partner_id='03' AND input_piece_id IS NOT NULL AND input_piece_id<>'' ");
        if(inputPiece==null || inputPiece.isEmpty()){
            return;
        }
        for(Record record : inputPiece){
            customerEntryService.dealGfQueryData(record.getStr("entry_id"));
        }
        long end = System.currentTimeMillis();
        logger.info("getGuangFaThirdStatus 定时任务结束，共耗时：[" + (end-begin) / 1000 + "]秒");
    }

    @Scheduled(cron = "0 0/10 * * * ?")
    public void getChangeStatus(){
        List<Record> records = Db.find(" SELECT concat(change_number) as change_number FROM crm_customer_entry_change_record WHERE change_status in('15','20') ");
        if(records!=null&&!records.isEmpty()){
            for (Record record : records) {
                try {
                    String changeNumbers = record.getStr("change_number");
                    guangFaManagemnetService.getChangeStatus(changeNumbers);
                }catch (Exception e){
                    logger.warn("getChangeStatus fail for"+record.getStr("change_number"), e);
                }
            }
        }
    }

}
