package com.sifang.modules.task;



import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.itextpdf.text.pdf.codec.Base64;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.alioss.AliyunOSSClientUtil;
import com.sifang.modules.customer.Service.CustomerEntryExtraService;
import com.sifang.modules.customer.Service.CustomerEntryService;
import com.sifang.modules.customer.entity.CrmAcceptingReport;
import com.sifang.modules.customer.entity.CustomerEntry;
import com.sifang.modules.customer.entity.CustomerEntryToExamine;
import com.sifang.modules.customer.pdf.PdfReport;
import com.sifang.modules.platform.utils.ReduceSize;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.common.utils.IdGen;
import com.sifang.modules.sys.common.utils.StringUtil;
import com.sifang.modules.sys.util.HttpsUtils;
import com.sifang.modules.sys.util.SqlBuilder;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
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.transaction.annotation.Transactional;
import sun.misc.BASE64Encoder;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

import static org.flowable.common.engine.impl.el.function.VariableBase64ExpressionFunction.base64;


@Component
public class TaskDemo {

    private static final String FILE_PATH_TEMPLATE = System.getProperty("java.io.tmpdir") + "/tempdf/%s";

    @Autowired
    private CustomerEntryService customerEntryService;

    @Autowired
    private CustomerEntryExtraService entryExtraService;

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

    //  @Scheduled(cron = "0 30 0 * * ?")
    void doSome(){

        logger.info("定时任务开始......");
        long begin = System.currentTimeMillis();

        //生成pdf...
        //获取所有未生成文档的 数据
        generatePdf(null);
        long end = System.currentTimeMillis();
        logger.info("定时任务结束，共耗时：[" + (end-begin) / 1000 + "]秒");

    }

    // @Scheduled(cron = "0 30 2 * * ?")
    void doSomeTwo(){

        logger.info("定时任务开始......");
        long begin = System.currentTimeMillis();

        //生成pdf...
        //获取所有未生成文档的 数据
        generatePdf(null);
        long end = System.currentTimeMillis();
        logger.info("定时任务结束，共耗时：[" + (end-begin) / 1000 + "]秒");

    }

    /**
     * 定时获取分包标准价生效日期
    */
    @Scheduled(cron = "0 10 1 * * ?")
    void checkS(){
        logger.info("定时任务开始......修改分包标准价设置");
        Db.update("UPDATE `crm_subconractor_settlement_scheme` SET status='1' WHERE  DATE(create_time) = CURDATE()");
        Db.update("UPDATE `crm_subconractor_settlement_scheme` SET status='4' WHERE  DATE(end_time) = CURDATE()");
    }



    @Scheduled(cron = "0 30 4 * * ?")
    void doSomeThree(){

        logger.info("定时任务开始......");
        long begin = System.currentTimeMillis();

        //生成pdf...
        //获取所有未生成文档的 数据
        generatePdf(null);
        long end = System.currentTimeMillis();
        logger.info("定时任务结束，共耗时：[" + (end-begin) / 1000 + "]秒");

    }
    public List<Record> findMaterialListByEntryId(String entryId){
        SqlBuilder sql  = new SqlBuilder();
        sql.line("SELECT p.*,m.`material_brand` FROM `crm_plan_material_entry` p");
        sql.line("LEFT JOIN `crm_supply_material` m ON m.`id`=p.`material_id`");
        sql.line("WHERE p.`entry_id`=? AND p.`status`='0'",entryId);

        return Db.find(sql.build(),sql.params());
    }
    public void generatePdf(List<Record>  list){
        if(list ==null){
            list = Db.find("SELECT * FROM crm_customer_entry WHERE STATUS IN('a') and (check_accept_imgs ='' or check_accept_imgs is null) LIMIT 2000  ");
        }

        for(Record rd:list){
            String id = rd.getStr("id");

            Date now = new Date();
            String sn = DateUtils.formatDate(now, "yyyyMMddHHmmss");

            long s1 = System.currentTimeMillis();
            CustomerEntry entry = new CustomerEntry();
            changeCustomrEntry(rd,entry);

            String reportId =rd.getStr("receiving_report_id");
            Record red = Db.findFirst("SELECT * FROM crm_accepting_report WHERE id=?",reportId);
            CrmAcceptingReport report = new CrmAcceptingReport();
            changeAcceptingReport(red,report);
            CustomerEntryToExamine examine =new CustomerEntryToExamine();
            Record record = Db.findFirst("SELECT * FROM `crm_customer_entry_to_examine` WHERE entry_id=?",id);
            setCustomerToExamine(examine,record);

            logger.info("generatePdf 电站编码 ：{}",rd.getStr("power_station_code"));
            String fileName = entry.getTraderName()+"-户用电站验收报告";

            String fileName1 = entry.getTraderName()+"-户用电站验收报告";

            String fileUrl = String.format(FILE_PATH_TEMPLATE, IdGen.uuid())+"/"+fileName+".pdf";
            //压缩有的文件路劲
            String filenewUrl = String.format(FILE_PATH_TEMPLATE, IdGen.uuid())+"/"+fileName1+".pdf";
            File file=null;
            File newfile=null;
            try {
                file = new File(fileUrl);
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                file.createNewFile();

                newfile = new File(filenewUrl);
                if (!newfile.getParentFile().exists()) {
                    newfile.getParentFile().mkdirs();
                }
                Map<String,Object> map = Maps.newHashMap();
                String brand = "";//组件品牌
                String nbqSpecOne = "";//逆变器一
                String nbqSpecTwo = "";//逆变器二
                String bwxBrand = "";//并网箱
                String zjBrand ="";
                List<Record> zhijialist = Lists.newArrayList();
                //获取使用的物料
                int bwxCOunt=0;
                int zujCOunt=0;
                List<Record> listma = findMaterialListByEntryId(entry.getId());
                for (Record re:listma){
                    if(StringUtil.equalsAny(re.getStr("type"),"组件")){
                        if(StringUtil.isBlank(brand)){
                            brand = re.getStr("material_brand");
                            map.put("zujBrand",brand);
                            map.put("zujSpec",re.getStr("spec"));
                            map.put("zujUnit", re.getStr("unit"));
                        }
                        zujCOunt++;
                    }
                    if(StringUtil.equalsAny(re.getStr("type"),"逆变器")){
                        if(StringUtil.isBlank(nbqSpecOne)){
                            nbqSpecOne=re.getStr("material_brand");
                            map.put("nbqBrandOne",nbqSpecOne);
                            map.put("nbqSpecOne",re.getStr("spec"));
                            map.put("nbqUnitOne", re.getStr("unit"));
                        }else{
                            nbqSpecTwo=re.getStr("material_brand");
                            map.put("nbqBrandTwo",nbqSpecTwo);
                            map.put("nbqSpecTwo",re.getStr("spec"));
                            map.put("nbqUnitTwo", re.getStr("unit"));
                        }
                    }
                    if(StringUtil.equalsAny(re.getStr("type"),"支架")){
                        if(StringUtil.isBlank(zjBrand)){
                            zjBrand=re.getStr("material_brand");
                            map.put("zjBrand",zjBrand);
                        }
                        zhijialist.add(re);
                    }
                    if(StringUtil.equalsAny(re.getStr("type"),"并网箱")){
                        bwxCOunt++;
                        if(StringUtil.isBlank(bwxBrand)) {
                            bwxBrand = re.getStr("material_brand");
                            map.put("bwxBrand", bwxBrand);
                            map.put("bwxSpec", re.getStr("spec"));
                            map.put("bwxUnit", re.getStr("unit"));
                        }
                    }

                }
                map.put("zhijialist", zhijialist);
                map.put("bwxCOunt", bwxCOunt);
                map.put("zujCOunt", zujCOunt);
                map.put("zjCount", zhijialist.size());

                if(entry.getSn().indexOf(",")>0){
                    String[] sns = entry.getSn().split(",");
                    if(sns.length>1){
                        map.put("snOne", sns[0]);
                        map.put("snTwo", sns[1]);
                    }else{
                        map.put("snOne", entry.getSn());
                    }
                }else{
                    map.put("snOne", entry.getSn());
                }
                if(StringUtil.isNotBlank(entry.getNbqSn()) && entry.getNbqSn().indexOf(",")>0){
                    String[] sns = entry.getNbqSn().split(",");
                    if(sns.length>1){
                        map.put("nbqSnOne", sns[0]);
                        map.put("nbqSnTwo", sns[1]);
                    }else{
                        map.put("nbqSnOne", entry.getNbqSn());
                    }
                }else{
                    map.put("nbqSnOne", entry.getNbqSn());
                }
                //生成pdf文件
                PdfReport.createBusinessInfoPDF(new FileOutputStream(file),report,entry,examine,map,zhijialist);
                logger.info("createEntryPdf 电站编码：{} 生成pdf文件 文件大小魏：{}",entry.getPowerStationCode(),FileUtils.sizeOf(file));
                //压缩pdf
                new ReduceSize().manipulatePdf(fileUrl,filenewUrl);
                logger.info("createEntryPdf 电站编码：{} 生成pdf文件 压缩后文件大小：{}",entry.getPowerStationCode(), FileUtils.sizeOf(newfile));
                //上传
                String fileInfo = AliyunOSSClientUtil.uploadImage(PdfReport.File2byte(newfile), "pdf", fileName);
                logger.info("返回路径信息"+fileInfo+fileInfo);

                String sql ="UPDATE crm_customer_entry SET check_accept_imgs=? WHERE id=?";
                Db.update(sql, StringUtil.convertBackSlant(fileInfo),id);
                long s2 = System.currentTimeMillis();
                logger.info(" >>下载验收报告 时间统计  [{}] end downLoadPDF use {}ms ", sn, (s2 - s1));
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("生成 PDF文件 generatePdf Exception：{}",e);
                continue;
            }  finally {
                file.delete();
                newfile.delete();
            }
        }
    }

    public void setCustomerToExamine(CustomerEntryToExamine examine,Record rd){
        examine.setId(rd.getStr("id"));
        examine.setEntryId(rd.getStr("entry_id"));
        examine.setExamineOne(rd.getStr("examine_one"));
        examine.setExamineTwo(rd.getStr("examine_two"));
        examine.setExamineThree(rd.getStr("examine_three"));
        examine.setExamineFour(rd.getStr("examine_four"));
        examine.setExamineFive(rd.getStr("examine_five"));
        examine.setExamineSix(rd.getStr("examine_six"));
        examine.setExamineSeven(rd.getStr("examine_seven"));
        examine.setExamineEight(rd.getStr("examine_eight"));
        examine.setExamineNine(rd.getStr("examine_nine"));
        examine.setOperatorOne(rd.getStr("operator_one"));
        examine.setOperatorTwo(rd.getStr("operator_two"));
        examine.setOperatorThree(rd.getStr("operator_three"));
        examine.setOperatorFour(rd.getStr("operator_four"));
        examine.setOperatorFive(rd.getStr("operator_five"));
        examine.setOperatorSix(rd.getStr("operator_six"));
        examine.setOperatorSeven(rd.getStr("operator_seven"));
        examine.setOperatorEight(rd.getStr("operator_eight"));
        examine.setOperatorNine(rd.getStr("operator_nine"));
        examine.setExamineTime(rd.getDate("examine_time"));
        examine.setExamineTimeTwo(rd.getDate("examine_time_two"));
        examine.setExamineTimeThree(rd.getDate("examine_time_three"));
        examine.setExamineTimeFour(rd.getDate("examine_time_four"));
        examine.setExamineTimeFive(rd.getDate("examine_time_five"));
        examine.setExamineTimeSix(rd.getDate("examine_time_six"));
        examine.setExamineTimeSeven(rd.getDate("examine_time_seven"));
        examine.setExamineTimeEight(rd.getDate("examine_time_eight"));
        examine.setExamineTimeNine(rd.getDate("examine_time_nine"));

    }

    public void  changeCustomrEntry(Record rd,CustomerEntry entry){
        entry.setProjectId(rd.getStr("project_id"));
        entry.setProjectName(rd.getStr("project_name"));
        entry.setProjectCode(rd.getStr("project_code"));
        entry.setTraderName(rd.getStr("trader_name"));
        entry.setTraderTel(rd.getStr("trader_tel"));
        entry.setPowerStationCode(rd.getStr("power_station_code"));
        entry.setTenantName(rd.getStr("tenant_name"));
        entry.setIdCode(rd.getStr("id_code"));
        entry.setProvince(rd.getStr("province"));
        entry.setCity(rd.getStr("city"));
        entry.setArea(rd.getStr("area"));
        entry.setAddress(rd.getStr("address"));
        entry.setMobile(rd.getStr("mobile"));
        entry.setRoofType(rd.getStr("roof_type"));
        //entry.setDistance(rd.getBigDecimal("distance"));
        //entry.setAngle(rd.getStr("angle"));
//        entry.setMethod(rd.getStr("method"));
//        entry.setMethodName(rd.getStr("method_name"));
        entry.setRemarks(rd.getStr("remarks"));
    }

    //TODO 暂时屏蔽 验收报告需要重新调整 待处理
    public void  changeAcceptingReport(Record rd,CrmAcceptingReport report){

        report.setCreator(rd.getStr("creator"));
        report.setComponentSpec(rd.getStr("component_spec"));
        report.setComponentNum(rd.getInt("component_num"));
        report.setCapacity(rd.getBigDecimal("capacity"));
        report.setNbqPlateImg(rd.getStr("nbq_plate_img"));
//        report.setTxPlateImg(rd.getStr("tx_plate_img"));
        report.setZjPlateImg(rd.getStr("zj_plate_img"));
        report.setDqsbAnImgOne(rd.getStr("zj_plate_img"));
//        report.setDqsbAnImgTwo(rd.getStr("zj_plate_img"));
//        report.setNbqPlateTwoImg(rd.getStr("zj_plate_img"));
//        report.setTxPlateTwoImg(rd.getStr("zj_plate_img"));
        report.setZjImg4(rd.getStr("zj_plate_img"));
        report.setZjImg5(rd.getStr("zj_plate_img"));
        report.setComponentImg3(rd.getStr("zj_plate_img"));
        report.setComponentImg4(rd.getStr("zj_plate_img"));
        report.setNbqZbImg(rd.getStr("zj_plate_img"));
//        report.setZujianJdImg(rd.getStr("zj_plate_img"));
       /* report.setNbqBwxJdImg(rd.getStr("zj_plate_img"));
        report.setZcKlImg3(rd.getStr("zj_plate_img"));*/
        report.setZfFixConclusion(rd.getStr("zj_plate_img"));
        report.setZfMergeConclusion(rd.getStr("zj_plate_img"));
        report.setId(rd.getStr("id"));
        report.setCapacity(rd.getBigDecimal("zj_plate_img"));
        report.setNbqPlateImg(rd.getStr("zj_plate_img"));
//        report.setTxPlateImg(rd.getStr("zj_plate_img"));
        report.setZjPlateImg(rd.getStr("zj_plate_img"));
        report.setZjImg1(rd.getStr("zj_plate_img"));
        report.setZjImg2(rd.getStr("zj_plate_img"));
        report.setZjImg3(rd.getStr("zj_plate_img"));
        report.setComponentImg1(rd.getStr("zj_plate_img"));
        report.setComponentImg2(rd.getStr("zj_plate_img"));
        report.setFixOtherImg(rd.getStr("zj_plate_img"));
        report.setTotalImgs(rd.getStr("zj_plate_img"));
        report.setDcImgs(rd.getStr("zj_plate_img"));
        report.setBwInnerImg(rd.getStr("zj_plate_img"));
      /*  report.setZjJdImg(rd.getStr("zj_plate_img"));
        report.setJdjImg(rd.getStr("zj_plate_img"));
        report.setJdOtherImg(rd.getStr("zj_plate_img"));;
        report.setZcKlImg1(rd.getStr("zj_plate_img"));
        report.setZcKlImg2(rd.getStr("zj_plate_img"));
        report.setJdDzImg1(rd.getStr("zj_plate_img"));
        report.setJdDlImg2(rd.getStr("zj_plate_img"));
        report.setFinishImg1(rd.getStr("zj_plate_img"));
        report.setGfFzImg(rd.getStr("zj_plate_img"));
        report.setFinishOtherImg(rd.getStr("zj_plate_img"));*/
        report.setYxImg(rd.getStr("zj_plate_img"));
        report.setGebImg(rd.getStr("zj_plate_img"));
        report.setFixConclusion(rd.getStr("zj_plate_img"));
        report.setMergeConclusion(rd.getStr("zj_plate_img"));
        report.setFinalConclusion(rd.getStr("zj_plate_img"));
        report.setCreator(rd.getStr("creator"));
        report.setCreateTime(rd.getDate("creator"));
        report.setFixAcceptName(rd.getStr("creator"));
        report.setFixAcceptTime(rd.getDate("creator"));
        report.setMergeAcceptName(rd.getStr("creator"));
        report.setMergeAcceptTime(rd.getDate("creator"));
    }

    // @Scheduled(cron = "0 0/15 * * * ?")
    public void updateEntryFile(){
        StringBuilder sf = new StringBuilder();

        sf.append("SELECT a.`img_upload`,b.id FROM `crm_customer_incoming_application` a ");
        sf.append("LEFT JOIN `crm_customer_entry` b ON a.`entry_id`=b.`id` ");
        sf.append("WHERE a.`img_upload`='0' and a.if_delete = '0' AND b.`apply_status`IN('QY','PR') AND b.`status` IN('6','7','8','9','a') AND b.`management_type`='2'");
        List<Record> list = Db.find(sf.toString());
        logger.info("定时获取第一次进件附件未上传的 数据  list :{}",list);
        if(list.size()>0){
            for(Record rd:list){
                logger.info("定时获取第一次进件附件未上传的 xiangmu id  entryId :{}",rd.getStr("id"));
                customerEntryService.uploadTwoAttachmentTh(rd.getStr("id"),"1","2");
            }
        }
    }

    // @Scheduled(cron = "0 0/21 * * * ?")
    public void updateEntryFileTwo(){
        StringBuilder sf = new StringBuilder();

        sf.append("SELECT a.`img_upload`,b.id FROM `crm_customer_incoming_application` a ");
        sf.append("LEFT JOIN `crm_customer_entry` b ON a.`entry_id`=b.`id` ");
        sf.append("WHERE a.`img_upload`='1' and a.if_delete = '0' AND b.`next_apply_status`='2' AND b.`status` IN('8','9','a') AND b.`management_type`='2'");
        List<Record> list = Db.find(sf.toString());
        logger.info("定时获取第二次进件附件未上传的 数据  list :{}",list);
        if(list.size()>0){
            for(Record rd:list){
                logger.info("定时推送二次进件附件================= id :{}",rd.getStr("id"));
                customerEntryService.uploadTwoAttachmentTh(rd.getStr("id"),"2","2");
            }
        }
    }

    // @Scheduled(cron = "0 0/5 * * * ?")
    public void updateEntryFileYSbg(){
        StringBuilder sf = new StringBuilder();

        sf.append("SELECT a.`img_upload`,b.id FROM `crm_customer_incoming_application` a ");
        sf.append("LEFT JOIN `crm_customer_entry` b ON a.`entry_id`=b.`id` ");
        sf.append("WHERE a.`img_upload`='2' and a.if_delete = '0' AND b.`next_apply_status`='2' AND b.`status` IN('8','9','a') AND b.`management_type`='2' LIMIT 10 ");
        List<Record> list = Db.find(sf.toString());
        logger.info("定时获取验收报告未上传的数据============  list :{}",list);
        if(list.size()>0){
            for(Record rd:list){
                customerEntryService.uploadAttachment(rd.getStr("id"),"");
            }
        }
        }

}
