package com.zfire.jiasm.syncdata.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.zfire.jiasm.syncdata.base.BaseService;
import com.zfire.jiasm.syncdata.gree.GreeLogic;
import com.zfire.jiasm.syncdata.helper.GreeFileResponseHelper;
import com.zfire.jiasm.syncdata.helper.GreeFileSaveHelper;
import com.zfire.jiasm.syncdata.http.PostObjectSample;
import com.zfire.jiasm.syncdata.plus.entity.*;
import com.zfire.jiasm.syncdata.plus.service.*;
import com.zfire.jiasm.syncdata.response.ResultData;
import com.zfire.jiasm.syncdata.service.PublicService;
import com.zfire.jiasm.syncdata.service.UploadWorkeCertificateService;
import com.zfire.jiasm.syncdata.utils.oss.OSSUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@Slf4j
@Service
public class UploadWorkeCertificateServiceImpl implements UploadWorkeCertificateService {
    @Resource
    OSSUtil ossUtil;
    @Resource
    GreeLogic greeLogic;
    @Resource
    WorkerCertService workerCertService;
    @Resource
    WorkerBrandAccountService workerBrandAccountService;
    @Resource
    BaseService baseService;
    @Resource
    PublicService publicService;
    @Resource
    InsureWorkerRecordService insureWorkerRecordService;
    @Resource
    InsureWorkerCommercialService insureWorkerCommercialService;
    @Resource
    InsureWorkerCommercialFileService insureWorkerCommercialFileService;
    @Resource
    WorkerMrbxService workerMrbxService;
    @Resource
    WebsitWorkerService websitWorkerService;
    @Resource
    InsureWorkerInitService insureWorkerInitService;
    @Resource
    WorkerCertGreeService workerCertGreeService;
    @Resource
    WorkerService workerService;



    @Override
    public void procesUploadWorkeCert() {
        List<WorkerCert> recs = new ArrayList<>();
        List<WorkerBrandAccount> workerWdnos = new ArrayList<>();
        String filePatho ="";
        String filePatht ="";
        String fileIdo ="";
        String fileIdt ="";
        Integer count = 0;
        Boolean upf=Boolean.TRUE;
        String outFile="";
        String outFilet="";
        List<WorkerCertGree> wcgs = new ArrayList<>();
        Map<String,String> wcgids = new HashMap<>();

        // 提取品牌信息 用于多品牌数据同步目前仅格力，可以先不用做
        Brand brand = baseService.getBrand();
        if (brand == null) {
            return;
        }


        List<WorkerCertGree> wcgsold = workerCertGreeService.lambdaQuery().list();
        if (CollectionUtils.isNotEmpty(wcgsold)){
            wcgsold.stream().forEach(event->{
                wcgids.put(event.getWorkerId() + event.getBrandWebsitId() + event.getCertName(),event.getWorkerCertGreeId());
            });
            wcgsold.clear();
        }


        // 获取待同步到格力总部师傅的证件信息
        recs = getWorkerUploads();

        // 测试用
        // recs =  getWorkerUploadstest();

        for (WorkerCert item:recs){
            count = 0;

            try{
                // 无证件不需要同步
                if (StringUtils.isEmpty(item.getFileUrl()) && StringUtils.isEmpty(item.getFileUrl2())){
                    continue;
                }
                // 证件已同步无需再次同步或是更新
                if ((StringUtils.isNotEmpty(item.getFileUrl()) && (StringUtils.isNotEmpty(item.getOutFileUrl()))) &&
                        (StringUtils.isNotEmpty(item.getFileUrl2()) && (StringUtils.isNotEmpty(item.getOutFileUrl2())))){
                    continue;
                }
                //  查看师傅是否已选中品牌商网点(这里只提取选中格力品牌商的师傅数据)
                workerWdnos = workerBrandAccountService.lambdaQuery()
                        .eq(WorkerBrandAccount::getWorkerId, item.getWorkerId())
                        .eq(WorkerBrandAccount::getBrandWorkerStatus,"ON")
                        .eq(WorkerBrandAccount::getDel,0)
                        .eq(WorkerBrandAccount::getGroupCompanyId, brand.getBrandId()).list();

                // 未选择品牌商
                if (workerWdnos.size()<1){
                    updateWorkCertificateerror(item,"师傅未选择格力品牌商信息");
                    continue;
                }

                //  判断师傅入驻的商户网点
                count = getCount(workerWdnos, count);
                if (count.equals(workerWdnos.size())){
                    updateWorkCertificateerror(item,"师傅未入驻品牌商网点");
                    continue;
                }

                // 生成图片 System.getProperty("java.io.tmpdir")
                if (StringUtils.isNotEmpty(item.getFileUrl()) && (StringUtils.isEmpty(item.getOutFileUrl()))){
                    fileIdo = IdWorker.getIdStr() + ".jpeg";
                    filePatho = publicService.pathToGree(fileIdo);
                    File nFile = publicService.createf(filePatho);
                    // 下载文件生成新文件 fid1
                    baseService.saveToFile(ossUtil.getUrlWw(item.getFileUrl()),nFile);

                }
                if (StringUtils.isNotEmpty(item.getFileUrl2()) && (StringUtils.isEmpty(item.getOutFileUrl2()))){
                    fileIdt = IdWorker.getIdStr() + ".jpeg";
                    filePatht = publicService.pathToGree(fileIdt);
                    File nFile = publicService.createf(filePatht);
                    // 下载文件生成新文件 fid2
                    baseService.saveToFile(ossUtil.getUrlWw(item.getFileUrl2()),nFile);
                }

                // 上传图片 按网点上传
                for (WorkerBrandAccount wdno: workerWdnos){
                    outFile="";
                    outFilet="";
                    upf=Boolean.TRUE;

                    if (StringUtils.isEmpty(wdno.getBrandWebsitId())){
                        continue;
                    }

                    if (StringUtils.isNotEmpty(filePatho)){
                        outFile = uploadWdnoFile(wdno.getBrandWebsitId(), item, filePatho, fileIdo);
                        if (StringUtils.isEmpty(outFile)){
                            upf=Boolean.FALSE;
                        }
                    }

                    if (StringUtils.isNotEmpty(filePatht)){
                        outFilet = uploadWdnoFile(wdno.getBrandWebsitId(), item, filePatht, fileIdt);
                        if (StringUtils.isEmpty(outFilet)){
                            upf=Boolean.FALSE;
                        }
                    }
                    // 网点上传成功 生成对像
                    if (upf){
                        getWorkerCertGreeInfo(outFile, outFilet, wcgs, item, wdno, wcgids);
                    }
                }
                // 上传完后师傅所在网点的证件保存，并写入更新表待师傅证件修改
                // 最后保存网点图，目的下次无需再同步图片
                extractedEnd(wcgs, item, outFile, outFilet);

                // 文件清除
                delfile(filePatho, filePatht, "");
            } catch (Exception ex) {
                ex.printStackTrace();
                log.info("同步师傅证件失败：【" + item.getId() + "】");
                String msg = "同步师傅证件失败：";
                if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotEmpty(ex.getMessage())){
                    msg = msg + ex.getMessage();
                }
                updateWorkCertificateerror(item,msg);
            }
        }
    }


    @Override
    public void procesUploadWorkeFace() {
        List<WorkerBrandAccount> workerWdnos = new ArrayList<>();
        String filePatho ="";
        String fileIdo ="";
        Integer count = 0;
        Boolean upf = Boolean.TRUE;
        String outFile="";
        List<WorkerCertGree> wcgs = new ArrayList<>();
        Map<String,String> wcgids = new HashMap<>();
        List<Worker> workers = new ArrayList<>();

        // 提取品牌信息 用于多品牌数据同步目前仅格力，可以先不用做
        Brand brand = baseService.getBrand();
        if (brand == null) {
            return;
        }

        List<WorkerCertGree> wcgsold = workerCertGreeService.lambdaQuery().list();
        if (CollectionUtils.isNotEmpty(wcgsold)){
            wcgsold.stream().forEach(event->{
                wcgids.put(event.getWorkerId() + event.getBrandWebsitId() + event.getCertName(),event.getWorkerCertGreeId());
            });
            wcgsold.clear();
        }

        // 提取需同步的人脸面像数据
        workers = getWorkers();

        for (Worker item:workers){
            count = 0;
            try{
                //  查看师傅是否已选中品牌商网点(这里只提取选中格力品牌商的师傅数据)
                workerWdnos = workerBrandAccountService.lambdaQuery()
                        .eq(WorkerBrandAccount::getWorkerId, item.getWorkerId())
                        .eq(WorkerBrandAccount::getBrandWorkerStatus,"ON")
                        .eq(WorkerBrandAccount::getDel,0)
                        .eq(WorkerBrandAccount::getGroupCompanyId, brand.getBrandId()).list();

                // 未选择品牌商
                if (workerWdnos.size()<1){
                    updateWorkFaceError(item,"师傅未选择格力品牌商信息");
                    continue;
                }

                //  判断师傅入驻的商户网点
                count = getCount(workerWdnos, count);
                if (count.equals(workerWdnos.size())){
                    updateWorkFaceError(item,"师傅未入驻品牌商网点");
                    continue;
                }

                // 生成图片 System.getProperty("java.io.tmpdir")
                fileIdo = IdWorker.getIdStr() + ".jpeg";
                filePatho = publicService.pathToGree(fileIdo);
                File nFile = publicService.createf(filePatho);
                // 下载文件生成新文件 fid1
                baseService.saveToFile(ossUtil.getUrlWw(item.getAuthHeadImage()),nFile);

                // 上传图片 按网点上传
                for (WorkerBrandAccount wdno: workerWdnos){
                    outFile="";
                    upf=Boolean.TRUE;

                    if (StringUtils.isEmpty(wdno.getBrandWebsitId())){
                        continue;
                    }

                    if (StringUtils.isNotEmpty(filePatho)){
                        outFile = uploadWdnoFaceFile(wdno.getBrandWebsitId(), item, filePatho, fileIdo);
                        if (StringUtils.isEmpty(outFile)){
                            upf=Boolean.FALSE;
                        }
                    }
                    // 网点上传成功 生成对像
                    if (upf){
                        getWorkerFaceGreeInfo(outFile, wcgs, wdno, wcgids);
                    }
                }
                // 上传完后师傅所在网点的证件保存，并写入更新表待师傅证件修改
                // 最后保存网点图，目的下次无需再同步图片
                extractedFeceEnd(wcgs, item, outFile);

                // 文件清除
                delfile(filePatho, "", "");

            } catch (Exception ex) {
                ex.printStackTrace();
                log.info("同步师傅人脸面像失败：【" + item.getWorkerId() + "】");
                log.info("同步师傅人脸面像失败：{}",JSONObject.toJSONString(wcgs));
                String msg = "同步师傅人脸面像失败：";
                if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotEmpty(ex.getMessage())){
                    msg = msg + ex.getMessage();
                }
                updateWorkFaceError(item,msg);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void extractedEnd(List<WorkerCertGree> wcgs, WorkerCert item, String file, String filet) throws Exception {
        try{
            if (wcgs.size()>0){
                workerCertGreeService.saveOrUpdateBatch(wcgs);
                wcgs.clear();
            }
            updateWorkCertSyncStat(item, file, filet);

        } catch (Exception ex) {
            ex.printStackTrace();
            // 抛异常目的是把前期的数据操作回滚
            throw new Exception(ex);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void extractedFeceEnd(List<WorkerCertGree> wcgs, Worker item, String file ) throws Exception {
        try{
            if (wcgs.size()>0){
                workerCertGreeService.saveOrUpdateBatch(wcgs);
                wcgs.clear();
            }
            updateWorkFaceSyncStat(item, file);

        } catch (Exception ex) {
            ex.printStackTrace();
            // 抛异常目的是把前期的数据操作回滚
            throw new Exception(ex);
        }
    }

    private void getWorkerCertGreeInfo(String outFile, String outFilet,
                                       List<WorkerCertGree> wcgs, WorkerCert item,
                                       WorkerBrandAccount wdno, Map<String,String> wcgids) {
        WorkerCertGree  awc = new WorkerCertGree();
        awc.setWorkerCertGreeId(IdWorker.getIdStr());
        awc.setWorkerId(wdno.getWorkerId());
        awc.setBrandWebsitId(wdno.getBrandWebsitId());
        awc.setCertName(item.getCertName());
        awc.setCertNo(item.getCertNo());
        awc.setStartTime(item.getStartTime());
        awc.setExpireTime(item.getExpireTime());
        awc.setReviewTime(item.getReviewTime());
        awc.setCreateTime(new Date());
        awc.setOutFileUrl(outFile);
        awc.setOutFileUrl2(outFilet);
        publicService.setCertFlag(item.getCertName(), awc);
        // 存在进行修改
        publicService.setWorkerCertGreeId(awc, wcgids);
        wcgs.add(awc);
    }

    private void getWorkerFaceGreeInfo(String outFile,
                                       List<WorkerCertGree> wcgs,
                                       WorkerBrandAccount wdno, Map<String,String> wcgids) {
        WorkerCertGree  awc = new WorkerCertGree();
        awc.setWorkerCertGreeId(IdWorker.getIdStr());
        awc.setWorkerId(wdno.getWorkerId());
        awc.setBrandWebsitId(wdno.getBrandWebsitId());
        awc.setCertName("人脸面像");
        awc.setCertNo("");
        awc.setCreateTime(new Date());
        awc.setOutFileUrl(outFile);
        publicService.setCertFlag(awc.getCertName(), awc);
        // 存在进行修改
        publicService.setWorkerCertGreeId(awc, wcgids);
        wcgs.add(awc);
    }

    private void getWorkerCertGreeOtherInfo(String outFile, String outFilet,
                                       List<WorkerCertGree> wcgs, WorkerCert item,
                                            OutWorkerUpload owu) {
        WorkerCertGree  awc = new WorkerCertGree();
        awc.setWorkerCertGreeId(IdWorker.getIdStr());
        awc.setWorkerId(owu.getWorkerId());
        awc.setBrandWebsitId(owu.getBrandWebsitId());
        awc.setCertName(item.getCertName());
        awc.setCertNo(item.getCertNo());
        awc.setStartTime(item.getStartTime());
        awc.setExpireTime(item.getExpireTime());
        awc.setReviewTime(item.getReviewTime());
        awc.setCreateTime(new Date());
        if (StringUtils.isNotEmpty(outFile)){
            awc.setOutFileUrl(outFile);
        }
        if (StringUtils.isNotEmpty(outFilet)){
            awc.setOutFileUrl2(outFilet);
        }
        publicService.setCertFlag(item.getCertName(), awc);
        wcgs.add(awc);
    }

    private void setWorkerCertGreeIdbak(WorkerBrandAccount wdno, WorkerCertGree awc) {
        WorkerCertGree wcg = workerCertGreeService.lambdaQuery()
                .eq(WorkerCertGree::getWorkerId, wdno.getWorkerId())
                .eq(WorkerCertGree::getBrandWebsitId, wdno.getBrandWebsitId())
                .eq(WorkerCertGree::getCertFlag, awc.getCertFlag())
                .last("limit 1").one();
        if (wcg != null) {
            awc.setWorkerCertGreeId(wcg.getWorkerCertGreeId());
        }
    }


    @Override
    public Boolean uploadWorkeBx(OutWorkerUpload owu){
        List<WorkerCertGree> wcgs = new ArrayList<>();
        String fileo = "";

        // 查看指定网点、师傅的保险数据是否已生成
        WorkerCertGree workerbx = workerCertGreeService.lambdaQuery()
                .eq(WorkerCertGree::getWorkerId,owu.getWorkerId())
                .eq(WorkerCertGree::getBrandWebsitId,owu.getBrandWebsitId())
                .eq(WorkerCertGree::getCertFlag,2)
                .last("limit 1").one();
        // 已存在 无需再同步保险数据
        if (workerbx != null){
            return Boolean.TRUE;
        }

        // 提取品牌信息 用于多品牌数据同步目前仅格力，可以先不用做
        Brand brand = baseService.getBrand();
        if (brand == null) {
            updateOutWorkerUploadError(owu,"格力品牌信息不存在");
            return Boolean.FALSE;
        }


        // 获取指定师傅、网点的保险证
        WebsitWorker item = websitWorkerService.lambdaQuery()
                .eq(WebsitWorker::getWorkerId,owu.getWorkerId())
                .eq(WebsitWorker::getWebsitId,owu.getWebsitId())
                .one();

        if (item == null){
            updateOutWorkerUploadError(owu,"无保险信息请核实websit_worker");
            return Boolean.FALSE;
        }

        // 若未同步生成三方文件不处理，等待其他定时任务处理 processUploadTask
        if (StringUtils.isEmpty(item.getOutInsureCert())){
            if (StringUtils.isEmpty(item.getInsureFiles())){
                updateOutWorkerUploadError(owu,"师傅未购买保险或保险未生效【"+owu.getWebsitId() + "】");
            } else {
                updateOutWorkerUploadError(owu,"等待同步保险信息");
            }

            return Boolean.FALSE;
        }

        fileo ="";
        try{
            // 存在保险才同步
            if (StringUtils.isEmpty(item.getInsureFiles())){
                owu.setSyncStatus(99);
                updateOutWorkerUploadError(owu,"师傅保险信息不存在或保险未生效【"+owu.getWebsitId() + "】");
                return Boolean.FALSE;
            }

            //  查看师傅是否已选中品牌商网点(这里只提取选中格力品牌商的师傅数据)
            WorkerBrandAccount wbaRecord = workerBrandAccountService.lambdaQuery()
                    .eq(WorkerBrandAccount::getWorkerId, owu.getWorkerId())
                    .eq(WorkerBrandAccount::getBrandWebsitId, owu.getBrandWebsitId())
                    .eq(WorkerBrandAccount::getGroupCompanyId, brand.getBrandId()).last("limit 1").one();

            // 未选择品牌商
            if (wbaRecord ==null ){
                updateOutWorkerUploadError(owu,"师傅未选择格力品牌商信息");
                return Boolean.FALSE;
            }


            // 上传图片 按师傅所在网点上传保险证数据
            delfilet(fileo);
            // 上传保险
            fileo = uploadInsureBx(item,wbaRecord);
            // 同步失败
            if (StringUtils.isEmpty(fileo)){
                updateOutWorkerUploadError(owu,"同步师傅保险证件失败【"+owu.getWebsitId() + "】");
                return Boolean.FALSE;
            }
            // 生成网点保险数据实体
            getWorkerCertBxGree(wcgs, item, wbaRecord);

            // 保存本地表
            extractedUploadBxEnd(wcgs);
            // 文件清除
            delfile("", "", fileo);
        } catch (Exception ex) {
            ex.printStackTrace();
            log.info("同步师傅保险证件失败：【" + item.getWebsitWorkerId() + "】");
            String msg = "同步师傅保险证件失败：";
            if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotEmpty(ex.getMessage())){
                msg = msg + ex.getMessage();
            }
            updateOutWorkerUploadError(owu,msg);
            return Boolean.FALSE;
        }

        return Boolean.TRUE;
    }

    @Override
    public Boolean uploadWorkeFace(OutWorkerUpload owu){
        List<WorkerCertGree> wcgs = new ArrayList<>();
        String fileo = "";

        // 查看指定网点、师傅的人脸面像数据是否已生成
        WorkerCertGree workerbx = workerCertGreeService.lambdaQuery()
                .eq(WorkerCertGree::getWorkerId,owu.getWorkerId())
                .eq(WorkerCertGree::getBrandWebsitId,owu.getBrandWebsitId())
                .eq(WorkerCertGree::getCertFlag,9)
                .last("limit 1").one();
        // 已存在 无需再同步
        if (workerbx != null){
            return Boolean.TRUE;
        }

        // 提取品牌信息 用于多品牌数据同步目前仅格力，可以先不用做
        Brand brand = baseService.getBrand();
        if (brand == null) {
            updateOutWorkerUploadError(owu,"格力品牌信息不存在");
            return Boolean.FALSE;
        }

        // 获取指定师傅、网点的人脸面像
        Worker item = workerService.lambdaQuery()
                .eq(Worker::getWorkerId,owu.getWorkerId())
                .one();

        if (item == null){
            updateOutWorkerUploadError(owu,"无人脸面像信息请核实Worker");
            return Boolean.FALSE;
        }
        // 无人脸面像数据不处理
        if (StringUtils.isEmpty(item.getOutAuthHeadImage())){
            updateOutWorkerUploadError(owu,"师傅未人脸面像实名认证");
            return Boolean.FALSE;
        }
        // 若存在待同步的暂不处理
        if (StringUtils.isNotEmpty(item.getAuthHeadImage()) &&
                StringUtils.isEmpty(item.getOutAuthHeadImage())){
            updateOutWorkerUploadError(owu,"等待同步人脸面像信息信息");
            return Boolean.FALSE;
        }

        try{
            //  查看师傅是否已选中品牌商网点(这里只提取选中格力品牌商的师傅数据)
            WorkerBrandAccount wbaRecord = workerBrandAccountService.lambdaQuery()
                    .eq(WorkerBrandAccount::getWorkerId, owu.getWorkerId())
                    .eq(WorkerBrandAccount::getBrandWebsitId, owu.getBrandWebsitId())
                    .eq(WorkerBrandAccount::getGroupCompanyId, brand.getBrandId()).last("limit 1").one();

            // 未选择品牌商
            if (wbaRecord ==null ){
                updateOutWorkerUploadError(owu,"师傅未选择格力品牌商信息");
                return Boolean.FALSE;
            }
            // 上传
            fileo = uploadInsureFace(item,wbaRecord);
            // 同步失败
            if (StringUtils.isEmpty(fileo)){
                updateOutWorkerUploadError(owu,"同步师傅人脸面像失败【"+owu.getWebsitId() + "】");
                return Boolean.FALSE;
            }
            // 生成网点保险数据实体
            getWorkerCertFaceGree(wcgs, item, wbaRecord);

            // 保存本地表
            extractedUploadBxEnd(wcgs);
            // 文件清除
            delfile("", "", fileo);
        } catch (Exception ex) {
            ex.printStackTrace();
            log.info("同步师傅人脸面像失败：【" + item.getWorkerId() + "】");
            String msg = "同步师傅人脸面像失败：";
            if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotEmpty(ex.getMessage())){
                msg = msg + ex.getMessage();
            }
            updateOutWorkerUploadError(owu,msg);
            return Boolean.FALSE;
        }

        return Boolean.TRUE;
    }

    @Override
    public Boolean UploadWorkeCert(OutWorkerUpload owu){
        List<WorkerCertGree> workerbx = new ArrayList<>();
        List<String> workerbxList = new ArrayList<>();
        List<WorkerCertGree> wcgs = new ArrayList<>();

        // 提取师傅的证件数据
        List<WorkerCert> recs = workerCertService.lambdaQuery()
                .eq(WorkerCert::getWorkerId,owu.getWorkerId()).list();
        if (CollectionUtils.isEmpty(recs)){
            updateOutWorkerUploadError(owu,"师傅证件信息不存在-WorkerCert");
            return Boolean.FALSE;
        }

        // 提取指定网点、师傅的证件数据
        workerbx =  workerCertGreeService.lambdaQuery()
                .eq(WorkerCertGree::getWorkerId,owu.getWorkerId())
                .eq(WorkerCertGree::getBrandWebsitId,owu.getBrandWebsitId())
                .list();
        if (CollectionUtils.isNotEmpty(workerbx)) {
            workerbx.stream().forEach(even -> {
                workerbxList.add(even.getBrandWebsitId() + even.getWorkerId() + even.getCertName());
            });
            workerbx.clear();
        }

        for (WorkerCert item :recs){
            // 证件已同步无需再次同步或是更新

            // 若存在待同步的暂不处理
            if ((StringUtils.isNotEmpty(item.getFileUrl()) && (StringUtils.isEmpty(item.getOutFileUrl()))) ||
                    (StringUtils.isNotEmpty(item.getFileUrl2()) && (StringUtils.isEmpty(item.getOutFileUrl2())))){
                updateOutWorkerUploadError(owu,"等待同步证件信息");
                return Boolean.FALSE;
            }

            // 查看证件数据是否已生成 已生成不再处理
            if (workerbxList.contains(owu.getBrandWebsitId() + owu.getWorkerId() + item.getCertName())){
                continue;
            }

            // 证件同步到总部对应的网点
            if (!extractedUpCert(owu, wcgs, item)){
                return Boolean.FALSE;
            }
        }
        return Boolean.TRUE;
    }

    private Boolean extractedUpCert(OutWorkerUpload owu, List<WorkerCertGree> wcgs, WorkerCert item) {
        String filePatho ="";
        String filePatht ="";
        String fileIdo ="";
        String fileIdt ="";
        Boolean upf=Boolean.TRUE;
        String outFile="";
        String outFilet="";

        try{

            // 生成图片 System.getProperty("java.io.tmpdir")
            if (StringUtils.isNotEmpty(item.getFileUrl())){
                fileIdo = IdWorker.getIdStr() + ".jpeg";
                filePatho = publicService.pathToGree(fileIdo);
                File nFile = publicService.createf(filePatho);
                // 下载文件生成新文件 fid1
                baseService.saveToFile(ossUtil.getUrlWw(item.getFileUrl()),nFile);

            }
            if (StringUtils.isNotEmpty(item.getFileUrl2())){
                fileIdt = IdWorker.getIdStr() + ".jpeg";
                filePatht = publicService.pathToGree(fileIdt);
                File nFile = publicService.createf(filePatht);
                // 下载文件生成新文件 fid2
                baseService.saveToFile(ossUtil.getUrlWw(item.getFileUrl2()),nFile);
            }


            // 上传图片 按网点上传
            if (StringUtils.isNotEmpty(filePatho)){
                outFile = uploadWdnoFile(owu.getBrandWebsitId(), item, filePatho, fileIdo);
                if (StringUtils.isEmpty(outFile)){
                    upf=Boolean.FALSE;
                }
            }

            if (StringUtils.isNotEmpty(filePatht)){
                outFilet = uploadWdnoFile(owu.getBrandWebsitId(), item, filePatht, fileIdt);
                if (StringUtils.isEmpty(outFilet)){
                    upf=Boolean.FALSE;
                }
            }

            // 网点上传成功 生成对像
            if (upf){
                getWorkerCertGreeOtherInfo(outFile, outFilet, wcgs, item, owu);
            }
            // 保存网点证件，目的下次无需再同步图片
            if (wcgs.size()>0){
                workerCertGreeService.saveOrUpdateBatch(wcgs);
                wcgs.clear();
            }

            // 文件清除
            delfile(filePatho, filePatht, "");

        } catch (Exception ex) {
            ex.printStackTrace();
            log.info("同步师傅入驻新网点证件失败：【" + item.getId() + "】");
            String msg = "同步师傅入驻新网点证件失败：";
            if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotEmpty(ex.getMessage())){
                msg = msg + ex.getMessage();
            }
            updateOutWorkerUploadError(owu,msg);
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }

    @Override
    public void procesUploadWorkeBx() {
        List<WebsitWorker> wws = new ArrayList<>();
        List<WorkerBrandAccount> workerWdnos = new ArrayList<>();
        List<WorkerCertGree> wcgs = new ArrayList<>();
        String fileo ="";
        String filet ="";
        String fid3 = "";
        Integer count = 0;
        Map<String,String> wcgids = new HashMap<>();

        // 提取品牌信息 用于多品牌数据同步目前仅格力，可以先不用做
        Brand brand = baseService.getBrand();
        if (brand == null) {
            return;
        }

        List<WorkerCertGree> wcgsold = workerCertGreeService.lambdaQuery().list();
        if (CollectionUtils.isNotEmpty(wcgsold)){
            wcgsold.stream().forEach(event->{
                wcgids.put(event.getWorkerId() + event.getBrandWebsitId() + event.getCertName(),event.getWorkerCertGreeId());
            });
            wcgsold.clear();
        }

        // 获取待同步到格力总部师傅的保除证件信息 WebsitWorker.getInsureStatus=2取已生效的
        wws = getWorkerUploadsBx();

        // 测试使用
        // wws = getWorkerUploadsBxtext();

        for (WebsitWorker item:wws){
            fileo ="";
            filet ="";
            count = 0;
            try{
                // 已同步不处理
                if (StringUtils.isNotEmpty(item.getOutInsureCert()) &&
                        StringUtils.isNotEmpty(item.getOutInsureCert().trim())){
                    continue;
                }

                // 存在保险才同步
                if (StringUtils.isEmpty(item.getInsureFiles())){
                    continue;
                }


                //  查看师傅是否已选中品牌商网点(这里只提取选中格力品牌商的师傅数据)
                workerWdnos = workerBrandAccountService.lambdaQuery()
                        .eq(WorkerBrandAccount::getWorkerId, item.getWorkerId())
                        .eq(WorkerBrandAccount::getWebsitWorkerId, item.getWebsitWorkerId())
                        .eq(WorkerBrandAccount::getWebsitId, item.getWebsitId())
                        .eq(WorkerBrandAccount::getBrandWorkerStatus,"ON")
                        .eq(WorkerBrandAccount::getDel,0)
                        .eq(WorkerBrandAccount::getGroupCompanyId, brand.getBrandId()).list();

                // 未选择品牌商
                if (workerWdnos.size()<1){
                    updateWebsitWorkererror(item,"师傅未选择格力品牌商信息");
                    continue;
                }

                //  判断师傅入驻的商户网点
                count = getCount(workerWdnos, count);
                if (count.equals(workerWdnos.size())){
                    updateWebsitWorkererror(item,"师傅未入驻品牌商网点");
                    continue;
                }

                // 上传图片 按师傅所在网点上传保险证数据
                for (WorkerBrandAccount wdno: workerWdnos){
                    delfilet(fid3);
                    if (StringUtils.isEmpty(wdno.getBrandWebsitId())){
                        continue;
                    }
                    // 上传保险
                    fid3 = uploadInsureBx(item,wdno);
                    // 同步失败
                    if (StringUtils.isEmpty(fid3)){
                        continue;
                    }
                    // 生成网点保险数据
                    getWorkerCertGree(wcgs, item, wdno, wcgids);
                }
                // 保存本地表
                extractedBxEnd(wcgs, item);
                // 文件清除
                delfile(fileo, filet, fid3);
            } catch (Exception ex) {
                ex.printStackTrace();
                log.info("同步师傅保险证件失败：【" + item.getWebsitWorkerId() + "】");
                String msg = "同步师傅保险证件失败：";
                if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotEmpty(ex.getMessage())){
                    msg = msg + ex.getMessage();
                }
                updateWebsitWorkererror(item,msg);
            }
        }
    }

    private void getWorkerCertGree(List<WorkerCertGree> wcgs, WebsitWorker item, WorkerBrandAccount wdno,
                                   Map<String,String> wcgids) {
        WorkerCertGree  awc = new WorkerCertGree();
        awc.setWorkerCertGreeId(IdWorker.getIdStr());
        awc.setWorkerId(wdno.getWorkerId());
        awc.setBrandWebsitId(wdno.getBrandWebsitId());
        awc.setCertName("保险证");
        awc.setCertNo(item.getSafeNo());
        awc.setStartTime(item.getInsureStartTime());
        awc.setExpireTime(item.getGmbxyxq());
        awc.setReviewTime(item.getGmbxyxq());
        awc.setCreateTime(new Date());
        awc.setOutFileUrl(item.getOutInsureCert());
        awc.setSafeCompany("人保");
        publicService.setCertFlag("保险证", awc);
        // 存在进行修改
        publicService.setWorkerCertGreeId(awc, wcgids);
        wcgs.add(awc);
    }

    private void getWorkerCertBxGree(List<WorkerCertGree> wcgs, WebsitWorker item, WorkerBrandAccount wdno) {
        WorkerCertGree  awc = new WorkerCertGree();
        awc.setWorkerCertGreeId(IdWorker.getIdStr());
        awc.setWorkerId(wdno.getWorkerId());
        awc.setBrandWebsitId(wdno.getBrandWebsitId());
        awc.setCertName("保险证");
        awc.setCertNo(item.getSafeNo());
        awc.setStartTime(item.getInsureStartTime());
        awc.setExpireTime(item.getGmbxyxq());
        awc.setReviewTime(item.getGmbxyxq());
        awc.setCreateTime(new Date());
        awc.setOutFileUrl(item.getOutInsureCert());
        awc.setSafeCompany("人保");
        publicService.setCertFlag("保险证", awc);
        wcgs.add(awc);
    }

    private void getWorkerCertFaceGree(List<WorkerCertGree> wcgs, Worker item, WorkerBrandAccount wdno) {
        WorkerCertGree  awc = new WorkerCertGree();
        awc.setWorkerCertGreeId(IdWorker.getIdStr());
        awc.setWorkerId(wdno.getWorkerId());
        awc.setBrandWebsitId(wdno.getBrandWebsitId());
        awc.setCertName("人脸面像");
        awc.setCertNo(item.getSafeNo());
        awc.setCreateTime(new Date());
        awc.setOutFileUrl(item.getOutAuthHeadImage());
        publicService.setCertFlag(awc.getCertName(), awc);
        wcgs.add(awc);
    }

    @Transactional(rollbackFor = Exception.class)
    public void extractedBxEnd(List<WorkerCertGree> wcgs, WebsitWorker item) throws Exception {
        try{
            if (wcgs.size()>0){
                workerCertGreeService.saveOrUpdateBatch(wcgs);
                wcgs.clear();
            }
            item.updateById();

        } catch (Exception ex) {
            ex.printStackTrace();
            // 抛异常目的是把前期的数据操作回滚
            throw new Exception(ex);
        }
    }

    public void extractedUploadBxEnd(List<WorkerCertGree> wcgs) throws Exception {
        try{
            if (wcgs.size()>0){
                workerCertGreeService.saveOrUpdateBatch(wcgs);
                wcgs.clear();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            // 抛异常目的是把前期的数据操作回滚
            throw new Exception(ex);
        }
    }

    @Override
    public void procesInitWorkeBx() throws IOException, ParseException {
        String fileo ="";
        String fid1 = "";

        // 看是否存在
        InsureWorkerInit init = insureWorkerInitService.lambdaQuery()
                .le(InsureWorkerInit::getStartTime,publicService.getYearFirstDay(new Date()))
                .ge(InsureWorkerInit::getEndTime,publicService.getYearLastDay(new Date()))
                .last("limit 1").one();
        if (init == null){
            // 上传保险数据
            fid1 = publicService.path("bx.jpg");
            File nFile = publicService.createf(fid1);

            baseService.initFile(nFile);

            fileo = fid1;

            // uploadInitFileexc(fileo, fid1, wdno.getBrandWebsitId(),wk);




            // uploadInsureCert();


        }

    }


    private void delfile(String fileo,String filet,String file3) {
        if (StringUtils.isNotEmpty(fileo)){
            new File(fileo).delete();
        }
        if (StringUtils.isNotEmpty(filet)){
            new File(filet).delete();
        }
        if (StringUtils.isNotEmpty(file3)){
            new File(file3).delete();
        }
    }

    private void delfiletow(String fid1, String fid2) {
        if (StringUtils.isNotEmpty(fid1)){
            new File(fid1).delete();
        }
        if (StringUtils.isNotEmpty(fid2)){
            new File(fid2).delete();
        }
    }

    private void delfilet(String file3) {
        if (StringUtils.isNotEmpty(file3)){
            new File(file3).delete();
        }
    }

    /**
     * 初始化保险数据(可以不买保险)
     * out_insure_cert 总部保证凭证 为空时
     *    insure_cert为空  初始化生成
     *               不为空正常生成
     */
    private String uploadInsureCert(WorkerBrandAccount wdno) throws Exception {
        String fileo ="";
        String fid1 = "";
        InsureWorkerRecord wk = insureWorkerRecordService.lambdaQuery()
                .eq(InsureWorkerRecord::getWebsitWorkerId, wdno.getWebsitWorkerId())
                .eq(InsureWorkerRecord::getStatus, "ON")
                .ne(InsureWorkerRecord::getVoucher, "").last("limit 1").one();
        if (StringUtils.isEmpty(wk.getOutVoucher())){
            // 生成图片
            if (StringUtils.isEmpty(wk.getVoucher())){
                fid1 = publicService.path("bx.jpg");
                File nFile = publicService.createf(fid1);
                baseService.initFile(nFile);
            } else {
                fid1 = publicService.path(wk.getVoucher());
                File nFile = publicService.createf(fid1);
                baseService.saveToFile(ossUtil.getUrlWw(wk.getVoucher()),nFile);
            }
            fileo = fid1;
            uploadInitFileexc(fileo, fid1, wdno.getBrandWebsitId(),wk);
        }
        return fid1;
    }


    private String uploadInsureBxBak(WorkerBrandAccount wdno) throws Exception {
        String fileo ="";
        String fid1 = "";

        InsureWorkerCommercial iwc = insureWorkerCommercialService.lambdaQuery()
                .eq(InsureWorkerCommercial::getWorkerId, wdno.getWorkerId())
                .eq(InsureWorkerCommercial::getWebsitId, wdno.getWebsitId())
                .last("limit 1").one();
        if (iwc != null){
            InsureWorkerCommercialFile iwcf = insureWorkerCommercialFileService.lambdaQuery()
                    .eq(InsureWorkerCommercialFile::getInsureWorkerCommercialId,iwc.getId())
                    .last("limit 1").one();
            if (iwcf !=null){
                if (StringUtils.isNotEmpty(iwcf.getOutZjlj())){
                    // 已上传就不需要再上传
                    return fid1;
                }
                if (StringUtils.isNotEmpty(iwcf.getFileUrl())){
                    // 上传
                    fid1 = publicService.path(iwcf.getFileUrl());
                    File nFile = publicService.createf(fid1);
                    baseService.saveToFile(ossUtil.getUrlWw(iwcf.getFileUrl()),nFile);
                    fileo = fid1;
                    uploadInitFile(fileo, fid1, wdno.getBrandWebsitId(),iwcf);
                    return fid1;
                }
            }
        }
        // 查家用保险
        InsureWorkerRecord wk = insureWorkerRecordService.lambdaQuery()
                .eq(InsureWorkerRecord::getWorkerId, wdno.getWorkerId())
                .eq(InsureWorkerRecord::getWebsitId, wdno.getWebsitId())
                .last("limit 1").one();
        if (wk !=null){
            if (StringUtils.isNotEmpty(wk.getOutVoucher())){
                // 已上传就不需要再上传
                return fid1;
            }
            if (StringUtils.isNotEmpty(wk.getVoucher())){
                // 上传
                fid1 = publicService.path(wk.getVoucher());
                File nFile = publicService.createf(fid1);
                baseService.saveToFile(ossUtil.getUrlWw(wk.getVoucher()),nFile);
                fileo = fid1;
                uploadInitFileexc(fileo, fid1, wdno.getBrandWebsitId(),wk);
                return fid1;
            }
        }


        // 加上getWebsitId条件找不到时，去掉getWebsitId条件
        InsureWorkerCommercial iwcc = insureWorkerCommercialService.lambdaQuery()
                .eq(InsureWorkerCommercial::getWorkerId, wdno.getWorkerId())
                // .eq(InsureWorkerCommercial::getWebsitId, wdno.getWebsitId())
                .orderByDesc(InsureWorkerCommercial::getEndTime)
                .last("limit 1").one();
        if (iwcc != null){
            InsureWorkerCommercialFile iwcf = insureWorkerCommercialFileService.lambdaQuery()
                    .eq(InsureWorkerCommercialFile::getInsureWorkerCommercialId,iwcc.getId())
                    .last("limit 1").one();
            if (iwcf !=null){
                if (StringUtils.isNotEmpty(iwcf.getOutZjlj())){
                    // 已上传就不需要再上传
                    return fid1;
                }
                if (StringUtils.isNotEmpty(iwcf.getFileUrl())){
                    // 上传
                    fid1 = publicService.path(iwcf.getFileUrl());
                    File nFile = publicService.createf(fid1);
                    baseService.saveToFile(ossUtil.getUrlWw(iwcf.getFileUrl()),nFile);
                    fileo = fid1;
                    uploadInitFile(fileo, fid1, wdno.getBrandWebsitId(),iwcf);
                    return fid1;
                }
            }
        }
        // 查家用保险
        InsureWorkerRecord wkk = insureWorkerRecordService.lambdaQuery()
                .eq(InsureWorkerRecord::getWorkerId, wdno.getWorkerId())
                // .eq(InsureWorkerRecord::getWebsitId, wdno.getWebsitId())
                .orderByDesc(InsureWorkerRecord::getEndTime)
                .last("limit 1").one();
        if (wkk !=null){
            if (StringUtils.isNotEmpty(wkk.getOutVoucher())){
                // 已上传就不需要再上传
                return fid1;
            }
            if (StringUtils.isNotEmpty(wkk.getVoucher())){
                // 上传
                fid1 = publicService.path(wkk.getVoucher());
                File nFile = publicService.createf(fid1);
                baseService.saveToFile(ossUtil.getUrlWw(wkk.getVoucher()),nFile);
                fileo = fid1;
                uploadInitFileexc(fileo, fid1, wdno.getBrandWebsitId(),wkk);
                return fid1;
            }
        }




        // 师傅必买保险，所以不会不存在
        return fid1;

        /*// 增加一个已上传过的表判断
        WorkerMrbx mbx = workerMrbxService.lambdaQuery()
                .eq(WorkerMrbx::getWorkerId, wdno.getWorkerId())
                .eq(WorkerMrbx::getWebsitId, wdno.getWebsitId())
                .isNotNull(WorkerMrbx::getOutZjlj)
                .last("limit 1").one();
        if (mbx != null){
            // 存在上传过的默认就不再上传 无论传的是哪一个师傅的 统一使用一个默认的
            return fid1;
        }

        // 都没有时上传 默认
        WorkerMrbx wmrbx = new WorkerMrbx();
        wmrbx.setId(IdWorker.getIdStr());
        wmrbx.setWorkerId(wdno.getWorkerId());
        wmrbx.setWebsitId(wdno.getWebsitId());
        fid1 = publicService.path("bx.jpg");
        baseService.initFile(fid1);
        fileo = fid1;
        uploadInitMRFileexc(fileo, fid1, wdno.getBrandWebsitId(),wmrbx);

        return fid1;*/
    }

    private String uploadInsureBx(WebsitWorker item,WorkerBrandAccount wdno) throws Exception {
        String fileAdnPath = "";
        String outInsureCert = "";
        String bxf="";
        String fileId = "";

        // 上传
        if (item.getInsureFiles().contains(",")){
            int num=0;

            List<String> result = Arrays.asList(item.getInsureFiles().split(","));
            for (String p:result){
                // 路径
                fileId = IdWorker.getIdStr() + ".jpeg";
                fileAdnPath = publicService.pathToGree(fileId);
                File nFile = publicService.createf(fileAdnPath);
                baseService.saveToFile(ossUtil.getUrlWw(p),nFile);
                bxf = uploadInitFileBx(fileAdnPath, fileId, wdno.getBrandWebsitId());
                if (StringUtils.isEmpty(bxf)){
                    return bxf;
                }

                if (num == 0){
                    outInsureCert = bxf;
                } else {
                    outInsureCert= outInsureCert +","+bxf;
                }
                nFile.delete();
                num = num +1 ;
            }
        } else {
            // 路径
            fileId = IdWorker.getIdStr() + ".jpeg";
            fileAdnPath = publicService.pathToGree(fileId);
            // 新文件 方便写入
            File nFile = publicService.createf(fileAdnPath);
            baseService.saveToFile(ossUtil.getUrlWw(item.getInsureFiles()),nFile);
            bxf = uploadInitFileBx(fileAdnPath, fileId, wdno.getBrandWebsitId());
            if (StringUtils.isEmpty(bxf)){
                return bxf;
            }
            outInsureCert = bxf;
            nFile.delete();
        }
        item.setOutInsureCert(outInsureCert);
        // 师傅必买保险，所以不会不存在
        return fileAdnPath;
    }

    private String uploadInsureFace(Worker item,WorkerBrandAccount wdno) throws Exception {
        String fileAdnPath = "";
        String outInsureCert = "";
        String bxf="";
        String fileId = "";

        // 路径
        fileId = IdWorker.getIdStr() + ".jpeg";
        fileAdnPath = publicService.pathToGree(fileId);
        // 新文件 方便写入
        File nFile = publicService.createf(fileAdnPath);
        baseService.saveToFile(ossUtil.getUrlWw(item.getAuthHeadImage()),nFile);
        bxf = uploadInitFileFace(fileAdnPath, fileId, wdno.getBrandWebsitId());
        if (StringUtils.isEmpty(bxf)){
            return bxf;
        }
        outInsureCert = bxf;
        nFile.delete();

        item.setOutAuthHeadImage(outInsureCert);
        return fileAdnPath;
    }

    private Boolean uploadFileexc(String fileo, String filet, String wdno,WorkerCert item) throws Exception {
        Boolean uploadfile = Boolean.TRUE;
        Boolean onlyone = Boolean.FALSE;
        String msg = "";

        if (StringUtils.isEmpty(wdno)){
            return Boolean.TRUE;
        }

        // 先上传第一个图片
        if (StringUtils.isNotEmpty(fileo)){
            // 1: 获取签名信息
            GreeFileResponseHelper response =  greeLogic.ossGetSignt(wdno,"GET");
            if (response.getStatusCode() == 200){
                ResultData resultData = JSONObject.parseObject(response.getData().toString(), ResultData.class);
                resultData.getExtData().setDir(resultData.getExtData().getDir()+"/"+fileo);
                // 2:文件上传
                PostObjectSample ossPostObject = new PostObjectSample();
                String result = ossPostObject.PostObject(fileo, resultData.getExtData());

                // 3: 保存文件
                if (StringUtils.isEmpty(result.trim())){
                    Map<String,String> req = new HashMap<>();
                    // 生成对象
                    getSaveFileInfo(fileo, resultData, req);
                    GreeFileSaveHelper responses = greeLogic.greePostSaveFile(req);
                    if (responses.getStatusCode() == 200){
                        // 保存文件ID   responses.getData().getId()
                        if (StringUtils.isEmpty(filet)){
                            // 说明只有第一个图片
                            onlyone = Boolean.TRUE;
                        }
                        updateWorkCertificatesave(item,responses.getData().getId(),1,uploadfile,onlyone);
                    } else {
                        // 失败
                        uploadfile = Boolean.FALSE;
                        msg = "保存证件正面文件到格力总部失败";
                        if (StringUtils.isNotEmpty(responses.getMsg())){
                            msg = msg + responses.getMsg();
                        }
                        updateWorkCertificateerror(item,msg);
                    }
                } else {
                    updateWorkCertificateerror(item,"上传图片到OSS失败");
                }
            } else {
                updateWorkCertificateerror(item,"获取签名信息失败");
                return Boolean.TRUE;
            }
        }

        if (StringUtils.isNotEmpty(filet)){
            // 1: 获取签名信息
            GreeFileResponseHelper response =  greeLogic.ossGetSignt(wdno,"GET");
            if (response.getStatusCode() == 200){
                ResultData resultData = JSONObject.parseObject(response.getData().toString(), ResultData.class);
                resultData.getExtData().setDir(resultData.getExtData().getDir()+"/"+filet);
                // 2:文件上传
                PostObjectSample ossPostObject = new PostObjectSample();
                String result = ossPostObject.PostObject(filet, resultData.getExtData());
                // 3: 保存文件
                if (StringUtils.isEmpty(result.trim())){
                    Map<String,String>req = new HashMap<>();
                    // 生成对象
                    getSaveFileInfo(filet, resultData, req);
                    GreeFileSaveHelper responses = greeLogic.greePostSaveFile(req);

                    if (responses.getStatusCode() == 200){
                        // 保存文件ID   responses.getData().getId()
                        updateWorkCertificatesave(item,responses.getData().getId(),2,uploadfile,onlyone);
                    } else {
                        // 失败
                        msg = "保存证件正面文件到格力总部失败";
                        if (StringUtils.isNotEmpty(responses.getMsg())){
                            msg = msg + responses.getMsg();
                        }
                        updateWorkCertificateerror(item,msg);
                        return Boolean.TRUE;
                    }
                } else {
                    updateWorkCertificateerror(item,"上传图片到OSS失败");
                    return Boolean.TRUE;
                }
            } else {
                updateWorkCertificateerror(item,"获取签名信息失败");
                return Boolean.TRUE;
            }
        }
        return Boolean.FALSE;
    }


    private String  uploadWdnoFile(String wdno,WorkerCert item,String filePath, String fileId) throws Exception {
        String msg = "";
        String outFile="";

        // 上传图片
        // 1: 获取签名信息
        GreeFileResponseHelper response =  greeLogic.ossGetSignt(wdno,"GET");
        if (response.getStatusCode() == 200){
            ResultData resultData = JSONObject.parseObject(response.getData().toString(), ResultData.class);
            resultData.getExtData().setDir(resultData.getExtData().getDir()+"/"+fileId);
            // 2:文件上传
            PostObjectSample ossPostObject = new PostObjectSample();
            String result = ossPostObject.PostObject(filePath, resultData.getExtData());

            // 3: 保存文件
            if (StringUtils.isEmpty(result.trim())){
                Map<String,String> req = new HashMap<>();
                // 生成对象
                getSaveFileInfo(fileId, resultData, req);
                GreeFileSaveHelper responses = greeLogic.greePostSaveFile(req);
                if (responses.getStatusCode() == 200){
                    // 保存文件ID   responses.getData().getId()
                    // 返回文件
                    outFile = responses.getData().getId();
                } else {
                    msg = "上传证件到格力总部失败";
                    if (StringUtils.isNotEmpty(responses.getMsg())){
                        msg = msg + responses.getMsg();
                    }
                    updateWorkCertificateerror(item,msg);
                }
            } else {
                updateWorkCertificateerror(item,"上传图片到OSS失败");
            }
        } else {
            updateWorkCertificateerror(item,"获取签名信息失败");
        }

        return outFile;
    }


    private String  uploadWdnoFaceFile(String wdno,Worker item,String filePath, String fileId) throws Exception {
        String msg = "";
        String outFile="";

        // 上传图片
        // 1: 获取签名信息
        GreeFileResponseHelper response =  greeLogic.ossGetSignt(wdno,"GET");
        if (response.getStatusCode() == 200){
            ResultData resultData = JSONObject.parseObject(response.getData().toString(), ResultData.class);
            resultData.getExtData().setDir(resultData.getExtData().getDir()+"/"+fileId);
            // 2:文件上传
            PostObjectSample ossPostObject = new PostObjectSample();
            String result = ossPostObject.PostObject(filePath, resultData.getExtData());

            // 3: 保存文件
            if (StringUtils.isEmpty(result.trim())){
                Map<String,String> req = new HashMap<>();
                // 生成对象
                getSaveFileInfo(fileId, resultData, req);
                GreeFileSaveHelper responses = greeLogic.greePostSaveFile(req);
                if (responses.getStatusCode() == 200){
                    // 保存文件ID   responses.getData().getId()
                    // 返回文件
                    outFile = responses.getData().getId();
                } else {
                    msg = "上传证件到格力总部失败";
                    if (StringUtils.isNotEmpty(responses.getMsg())){
                        msg = msg + responses.getMsg();
                    }
                    updateWorkFaceError(item,msg);
                }
            } else {
                updateWorkFaceError(item,"上传图片到OSS失败");
            }
        } else {
            updateWorkFaceError(item,"获取签名信息失败");
        }

        return outFile;
    }


    private Boolean uploadInitFileexc(String fileo, String fid1,String wdno,InsureWorkerRecord wk) throws Exception {

        if (StringUtils.isEmpty(wdno)){
            return Boolean.TRUE;
        }

        if (StringUtils.isNotEmpty(fileo)){
            // 1: 获取签名信息
            GreeFileResponseHelper response =  greeLogic.ossGetSignt(wdno,"GET");
            if (response.getStatusCode() == 200){
                ResultData resultData = JSONObject.parseObject(response.getData().toString(), ResultData.class);
                resultData.getExtData().setDir(resultData.getExtData().getDir()+"/"+fid1);
                // 2:文件上传
                PostObjectSample ossPostObject = new PostObjectSample();
                String result = ossPostObject.PostObject(fileo, resultData.getExtData());
                // 3: 保存文件
                if (StringUtils.isEmpty(result.trim())){
                    Map<String,String>req = new HashMap<>();
                    // 生成对象
                    getSaveFileInfo(fid1, resultData, req);
                    GreeFileSaveHelper responses = greeLogic.greePostSaveFile(req);

                    if (responses.getStatusCode() == 200){
                        // 保存文件ID   responses.getData().getId()
                        wk.setOutVoucher(responses.getData().getId());
                        insureWorkerRecordService.updateById(wk);
                    } else {
                        // 失败
                        log.info("保存保险证件文件到格力总部失败");
                    }
                } else {
                    log.info("保险证件上传图片到OSS失败");
                }
            } else {
                log.info("获取签名信息失败");
                return Boolean.TRUE;
            }
        }

        return Boolean.FALSE;
    }


    private Boolean uploadInitMRFileexc(String fileo, String fid1,String wdno,WorkerMrbx wk) throws Exception {

        if (StringUtils.isEmpty(wdno)){
            return Boolean.TRUE;
        }

        if (StringUtils.isNotEmpty(fileo)){
            // 1: 获取签名信息
            GreeFileResponseHelper response =  greeLogic.ossGetSignt(wdno,"GET");
            if (response.getStatusCode() == 200){
                ResultData resultData = JSONObject.parseObject(response.getData().toString(), ResultData.class);
                resultData.getExtData().setDir(resultData.getExtData().getDir()+"/"+fid1);
                // 2:文件上传
                PostObjectSample ossPostObject = new PostObjectSample();
                String result = ossPostObject.PostObject(fileo, resultData.getExtData());
                // 3: 保存文件
                if (StringUtils.isEmpty(result.trim())){
                    Map<String,String>req = new HashMap<>();
                    // 生成对象
                    getSaveFileInfo(fid1, resultData, req);
                    GreeFileSaveHelper responses = greeLogic.greePostSaveFile(req);

                    if (responses.getStatusCode() == 200){
                        // 保存文件ID   responses.getData().getId()
                        wk.setOutZjlj(responses.getData().getId());
                        wk.setSyncTime(new Date());
                        workerMrbxService.save(wk);
                    } else {
                        // 失败
                        log.info("保存保险证件文件到格力总部失败");
                    }
                } else {
                    log.info("保险证件上传图片到OSS失败");
                }
            } else {
                log.info("获取签名信息失败");
                return Boolean.TRUE;
            }
        }

        return Boolean.FALSE;
    }

    private Boolean uploadInitFile(String fileo, String fid1,String wdno,InsureWorkerCommercialFile wk) throws Exception {
        if (StringUtils.isNotEmpty(fileo)){
            // 1: 获取签名信息
            GreeFileResponseHelper response =  greeLogic.ossGetSignt(wdno,"GET");
            if (response.getStatusCode() == 200){
                ResultData resultData = JSONObject.parseObject(response.getData().toString(), ResultData.class);
                resultData.getExtData().setDir(resultData.getExtData().getDir()+"/"+fid1);
                // 2:文件上传
                PostObjectSample ossPostObject = new PostObjectSample();
                String result = ossPostObject.PostObject(fileo, resultData.getExtData());
                // 3: 保存文件
                if (StringUtils.isEmpty(result.trim())){
                    Map<String,String>req = new HashMap<>();
                    // 生成对象
                    getSaveFileInfo(fid1, resultData, req);
                    GreeFileSaveHelper responses = greeLogic.greePostSaveFile(req);

                    if (responses.getStatusCode() == 200){
                        // 保存文件ID   responses.getData().getId()
                        wk.setOutZjlj(responses.getData().getId());
                        wk.setOutZjljProcess(1);
                        wk.updateById();
                    } else {
                        // 失败
                        log.info("保存保险证件文件到格力总部失败");
                    }
                } else {
                    log.info("保险证件上传图片到OSS失败");
                }
            } else {
                log.info("获取签名信息失败");
                return Boolean.TRUE;
            }
        }

        return Boolean.FALSE;
    }


    private String uploadInitFileBx(String fileAdnPath, String fidId,String wdno) throws Exception {
        String fileId="";
        if (StringUtils.isNotEmpty(fileAdnPath)){
            // 1: 获取签名信息
            GreeFileResponseHelper response =  greeLogic.ossGetSignt(wdno,"GET");
            if (response.getStatusCode() == 200){
                ResultData resultData = JSONObject.parseObject(response.getData().toString(), ResultData.class);
                resultData.getExtData().setDir(resultData.getExtData().getDir()+"/"+fidId);
                // 2:文件上传
                PostObjectSample ossPostObject = new PostObjectSample();
                String result = ossPostObject.PostObject(fileAdnPath, resultData.getExtData());
                // 3: 保存文件
                if (StringUtils.isEmpty(result.trim())){
                    Map<String,String>req = new HashMap<>();
                    // 生成对象
                    getSaveFileInfo(fidId, resultData, req);
                    GreeFileSaveHelper responses = greeLogic.greePostSaveFile(req);
                    if (responses.getStatusCode() == 200){
                        fileId = responses.getData().getId();
                    } else {
                        // 失败
                        log.info("保存保险证件文件到格力总部失败");
                    }
                } else {
                    log.info("保险证件上传图片到OSS失败");
                }
            } else {
                log.info("获取签名信息失败");
            }
        }

        return fileId;
    }

    private String uploadInitFileFace(String fileAdnPath, String fidId,String wdno) throws Exception {
        String fileId="";
        if (StringUtils.isNotEmpty(fileAdnPath)){
            // 1: 获取签名信息
            GreeFileResponseHelper response =  greeLogic.ossGetSignt(wdno,"GET");
            if (response.getStatusCode() == 200){
                ResultData resultData = JSONObject.parseObject(response.getData().toString(), ResultData.class);
                resultData.getExtData().setDir(resultData.getExtData().getDir()+"/"+fidId);
                // 2:文件上传
                PostObjectSample ossPostObject = new PostObjectSample();
                String result = ossPostObject.PostObject(fileAdnPath, resultData.getExtData());
                // 3: 保存文件
                if (StringUtils.isEmpty(result.trim())){
                    Map<String,String>req = new HashMap<>();
                    // 生成对象
                    getSaveFileInfo(fidId, resultData, req);
                    GreeFileSaveHelper responses = greeLogic.greePostSaveFile(req);
                    if (responses.getStatusCode() == 200){
                        fileId = responses.getData().getId();
                    } else {
                        // 失败
                        log.info("保存人脸面像文件到格力总部失败");
                    }
                } else {
                    log.info("人脸面像上传图片到OSS失败");
                }
            } else {
                log.info("获取签名信息失败");
            }
        }

        return fileId;
    }

    private Integer getCount(List<WorkerBrandAccount> workerWdnos, Integer count) {
        for (WorkerBrandAccount w: workerWdnos){
            if (StringUtils.isEmpty(w.getBrandWebsitId())){
                count++;
            }
        }
        return count;
    }

    private void updateWorkCertificateerror(WorkerCert item, String msg) {
        WorkerCert v = new WorkerCert();
        v.setId(item.getId());
        v.setOutSyncTime(new Date());
        v.setOutSyncErrorMsg(msg);
        v.setOutSyncTimes(item.getOutSyncTimes() +1);
        if (msg.length()>250){
            v.setOutSyncErrorMsg(msg.substring(0,250));
        }
        workerCertService.updateById(v);
    }

    private void updateWorkFaceError(Worker item, String msg) {
        item.setOutSyncTime(new Date());
        item.setOutSyncTimes(item.getOutSyncTimes() + 1);
        item.setOutSyncErrorMsg(msg);
        if (msg.length()>250){
            item.setOutSyncErrorMsg(msg.substring(0,250));
        }

        item.updateById();
    }


    private void updateWebsitWorkererror(WebsitWorker item, String msg) {
        WebsitWorker v = new WebsitWorker();
        v.setWebsitWorkerId(item.getWebsitWorkerId());
        v.setSyncErrorMsg(msg);
        if (msg.length()>250){
            v.setSyncErrorMsg(msg.substring(0,250));
        }
        websitWorkerService.updateById(v);
    }

    private void updateOutWorkerUploadError(OutWorkerUpload owu, String msg) {
        owu.setSyncErrorMsg(msg);
        if (msg.length()>250){
            owu.setSyncErrorMsg(msg.substring(0,250));
        }
        owu.updateById();
    }


    private void updateWorkCertificatesave(WorkerCert i, String file, Integer flag,
                                           Boolean bool, Boolean onlyOne) {
        WorkerCert v = new WorkerCert();
        v.setId(i.getId());
        if (flag ==1){
            v.setOutFileUrl(file);
            if (onlyOne){
                v.setOutSyncStatus(1);
            }
        } else {
            v.setOutFileUrl2(file);
            if (bool){
                v.setOutSyncStatus(1);
            }
        }
        v.setOutSyncTime(new Date());
        workerCertService.updateById(v);
    }

    public void updateWorkCertSyncStat(WorkerCert wc,String file, String filet) {
        WorkerCert v = new WorkerCert();
        v.setId(wc.getId());

        if (StringUtils.isNotEmpty(file)){
            v.setOutFileUrl(file);
        }
        if (StringUtils.isNotEmpty(filet)){
            v.setOutFileUrl2(filet);
        }

        v.setOutSyncStatus(1);
        v.setOutSyncTimes(0);
        v.setOutSyncTime(new Date());
        workerCertService.updateById(v);
    }


    public void updateWorkFaceSyncStat(Worker item, String file) {
        item.setOutSyncTimes(1);
        item.setOutSyncTime(new Date());
        item.setOutSyncErrorMsg("成功");
        item.setOutAuthHeadImage(file);

        item.updateById();
    }


    private void getSaveFileInfo(String fileId, ResultData resultData, Map<String, String> req) {
        req.put("bizAppId","flydiy-auto-sit-default-front-greeshmerge");
        req.put("bizTable","default");
        req.put("bizType","default");
        req.put("accessType","auth");
        req.put("url", resultData.getExtData().getDir());
        req.put("name", fileId);
    }



    private List<Worker> getWorkers() {
        return workerService.lambdaQuery()
                .eq(Worker::getIsReal,"YES")
                .isNotNull(Worker::getAuthHeadImage)
                .isNull(Worker::getOutAuthHeadImage)
                .list();
    }

    private List<WorkerCert> getWorkerUploads() {
        // 同步标志-synStatus(0:待同步;1:已同步;99:同步失败)
        return workerCertService.lambdaQuery()
                .in(WorkerCert::getOutSyncStatus,0,99)
                .lt(WorkerCert::getOutSyncTimes,100)
                .list();
    }

    private List<WorkerCert> getWorkerUploadstest() {
        // 同步标志-synStatus(0:待同步;1:已同步;99:同步失败)
        return workerCertService.lambdaQuery()
                .eq(WorkerCert::getId,"469044823285893")
                .list();
    }


    private List<WebsitWorker> getWorkerUploadsBx() {
        List<WebsitWorker> wws = websitWorkerService.lambdaQuery()
                .eq(WebsitWorker::getInsureStatus,2)
                .isNotNull(WebsitWorker::getInsureFiles).list();

        return wws;
    }

    private List<WebsitWorker> getWorkerUploadsBxtext() {
        List<WebsitWorker> wws = websitWorkerService.lambdaQuery()
                .eq(WebsitWorker::getWorkerId,"S13430387965").list();

        return wws;
    }
}
