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

import com.alibaba.fastjson.JSONObject;
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.Brand;
import com.zfire.jiasm.syncdata.plus.entity.WebsitWorker;
import com.zfire.jiasm.syncdata.plus.entity.WorkerBrandAccount;
import com.zfire.jiasm.syncdata.plus.entity.WorkerCert;
import com.zfire.jiasm.syncdata.plus.service.WebsitWorkerService;
import com.zfire.jiasm.syncdata.plus.service.WorkerBrandAccountService;
import com.zfire.jiasm.syncdata.plus.service.WorkerCertService;
import com.zfire.jiasm.syncdata.response.ResultData;
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 javax.annotation.Resource;
import java.io.File;
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
    WebsitWorkerService websitWorkerService;



    @Override
    public void procesUploadWorkeCert() {

        List<WorkerCert> recs = new ArrayList<>();
        List<WorkerBrandAccount> workerWdnos = new ArrayList<>();
        String fileo ="";
        String filet ="";
        String fid1 = "";
        String fid2 = "";
        String fid3 = "";
        Integer count = 0;

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

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

        for (WorkerCert item:recs){
            fileo ="";
            filet ="";
            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){
                    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()))){
                    fileo = IdWorker.getIdStr() + ".jpg";
                    // 下载文件生成新文件 fid1
                    baseService.saveToFile(ossUtil.getUrlWw(item.getFileUrl()),fileo);
                }
                if (StringUtils.isNotEmpty(item.getFileUrl2()) && (StringUtils.isEmpty(item.getOutFileUrl2()))){
                    filet = IdWorker.getIdStr() + ".jpg";
                    // 下载文件生成新文件 fid2
                    baseService.saveToFile(ossUtil.getUrlWw(item.getFileUrl2()),filet);
                }

                // 上传图片 按网点上传
                for (WorkerBrandAccount wdno: workerWdnos){
                    uploadFileexc(fileo, filet,wdno.getBrandWebsitId(),item);
                    delfilet(fid3);
                    // 保险数据同步 保险证不在证件表中
                    fid3 = uploadInsureCert(wdno);
                }

                // 文件清除
                delfile(fileo, filet, fid3);
            } 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);
            }
        }
    }


    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 = "";
        WebsitWorker wk = websitWorkerService.lambdaQuery()
                .eq(WebsitWorker::getWebsitWorkerId, wdno.getWebsitWorkerId()).one();
        if (StringUtils.isEmpty(wk.getOutInsureCert())){
            // 生成图片
            if (StringUtils.isEmpty(wk.getInsureCert())){
                fid1 = "bx.jpg";
                baseService.initFile(fid1);
            } else {
                fid1 = IdWorker.getIdStr() + ".jpg";
                baseService.saveToFile(ossUtil.getUrlWw(wk.getInsureCert()),fid1);
            }
            fileo = fid1;
            uploadInitFileexc(fileo, fid1, wdno.getBrandWebsitId(),wk);
        }
        return fid1;
    }

    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 Boolean uploadInitFileexc(String fileo, String fid1,String wdno,WebsitWorker 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.setOutInsureCert(responses.getData().getId());
                        websitWorkerService.updateById(wk);
                    } else {
                        // 失败
                        log.info("保存保险证件文件到格力总部失败");
                    }
                } else {
                    log.info("保险证件上传图片到OSS失败");
                }
            } else {
                log.info("获取签名信息失败");
                return Boolean.TRUE;
            }
        }

        return Boolean.FALSE;
    }

    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 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);
    }

    private void getSaveFileInfo(String id1, 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", id1);
    }


    /**
     * 该表只进行增加数据
     *     相同类型数据只取最大ID
     * @return
     */
    private List<WorkerCert> getWorkerUploads() {
        // 同步标志-synStatus(0:待同步;1:已同步;99:同步失败)
        return workerCertService.lambdaQuery()
                .in(WorkerCert::getOutSyncStatus,0,99)
                .lt(WorkerCert::getOutSyncTimes,10)
                .list();
    }
}
