package com.baichuanxin.openrestapi.scheduling;

import cn.hutool.core.util.StrUtil;
import cn.hutool.db.DbUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.baichuanxin.openrestapi.common.OnlineTaskConstant;
import com.baichuanxin.openrestapi.common.utils.DateUtil;
import com.baichuanxin.openrestapi.common.utils.FileHandleUtil;
import com.baichuanxin.openrestapi.common.utils.OnlineTaskUtil;
import com.baichuanxin.openrestapi.configs.OneTaskConfig;
import com.baichuanxin.openrestapi.dao.mapper.ECSysConfigMapper;
import com.baichuanxin.openrestapi.dtos.SecurityServicekDto;
import com.baichuanxin.openrestapi.entity.ChangeLegalPerson;
import com.baichuanxin.openrestapi.entity.ECSysConfig;
import com.baichuanxin.openrestapi.entity.LicenseInformation;
import com.baichuanxin.openrestapi.entity.SecurityServicek;
import com.baichuanxin.openrestapi.factorys.TaskFactory;
import com.baichuanxin.openrestapi.service.ECSysconfigService;
import com.baichuanxin.openrestapi.service.LicenseInformationService;
import com.baichuanxin.openrestapi.service.TaskInfoService;
import com.baichuanxin.openrestapi.service.impl.ChangeLegalPersonTaskInfoServiceImpl;
import com.baichuanxin.openrestapi.service.impl.LicenseInformationServiceImpl;
import com.baichuanxin.openrestapi.service.impl.SecurityServicekTaskInfoServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/***
 *@Author duxiangyun
 *@Description  电子证照相关任务
 *@Date 2024/8/22
 */


@Slf4j
@Component
public class ECTask {
    @Autowired
    private ECSysconfigService  ecSysconfigService;
    @Autowired
    private SecurityServicekTaskInfoServiceImpl service;
    @Autowired
    private LicenseInformationServiceImpl licenseInformationServiceImpl;
    @Autowired
    private ChangeLegalPersonTaskInfoServiceImpl   cPersonService;
    /**
     * 更新电子证照token
     */
    @Scheduled(fixedDelay = 12 * 60 * 60 * 1000)    //每隔11小时获取一次
    public void getTokenTask(){
        log.info("开始获取电子证照token任务");
        String token = this.getToken();
        ecSysconfigService.updateToken(token);
        log.info("结束获取电子证照token任务");
    }

    /***
     *@Author duxiangyun
     *@Description 保安服务公司设立提交照面信息
     *@Date 2024/11/13
     */
    @Scheduled(fixedDelay = 3 * 60 * 1000)
    public void   ECSubmitDataTask(){
        log.info("============开始进行证书签章==>保安服务公司设立提交照面数据======================");
        ECSysConfig one = ecSysconfigService.getOne();
        String ecToken = one.getConfigValue();
        List<SecurityServicek> serviceList = service.getUnGetEC();
        List<Map<String, String>> dataList = this.getECInformationHandel(serviceList);
        //在这里获取审批人，拿到审批人的信息
        for (Map<String, String> itemMap : dataList) {
            //1处理xml
            String xml = OnlineTaskUtil.handleXml(itemMap);
            String holderCode = itemMap.get("holderCode");  //统一社会信用编码
            //证照唯一标识
            String unId = itemMap.get("unid");
            String name = itemMap.get("holder");
            //发送请求
            Map<String, String> strMap = OnlineTaskUtil.xmlDataSend(xml, unId,ecToken);   //照面信息发送成功，取得返回值存入库中。同时修改申请数据照面信息提交状态
            String fileNumber = strMap.get("fileNumber");
            String licenseId  = strMap.get("licenseId");
            log.error("文件编码：{}，文件id{}",fileNumber,licenseId);
//            "`id`, `licenseId`, `fileNumber`, `status`, `uscc`, `name`"
            if (StrUtil.isNotBlank(fileNumber)&&StrUtil.isNotBlank(licenseId)) {
                LicenseInformation licenseInformation = new LicenseInformation();
                licenseInformation.setId(unId);
                licenseInformation.setLicenseId(licenseId);
                licenseInformation.setFileNumber(fileNumber);
                licenseInformation.setUscc(holderCode);
                licenseInformation.setName(name);
                licenseInformation.setStatus(0);
                licenseInformationServiceImpl.addLicenseInformation(licenseInformation);
                service.updateLicenseStatus(unId,"1");
            }
        }
    }

    /***
     *@Author duxiangyun
     *@Description 保安服务公司法人变更提交照面信息
     *@Date 2024/11/13
     */
    @Scheduled(fixedDelay = 3 * 60 * 1000)
    public void   changeECSubmitDataTask(){
        log.info("============开始进行证书签章==>法人变更提交照面数据======================");
        ECSysConfig one = ecSysconfigService.getOne();
        String ecToken = one.getConfigValue();
        //查询所有的法人变更数据
        List<ChangeLegalPerson> changeLegalPersonList = cPersonService.getUnGetEC();
        List<Map<String, String>> dataList = this.getCPersonECInformationHandel(changeLegalPersonList);
        for (Map<String, String> itemMap : dataList) {
            //判断此前是否申领过电子证照如果有则调用变更的接口 如果没有则调用申请的接口
            //通过社会信用代码查询是否申领过
            List<LicenseInformation> licenseList = licenseInformationServiceImpl.getByUscc(itemMap.get("holderCode"));
            //1处理xml
            String xml = OnlineTaskUtil.handleXml(itemMap);
            String holderCode = itemMap.get("holderCode");  //统一社会信用编码
            //证照唯一标识
            String unId = itemMap.get("unid");
            String name = itemMap.get("holder");
            if (licenseList.isEmpty()){    //没有申领过电子证照
                //发送请求
                Map<String, String> strMap = OnlineTaskUtil.xmlDataSend(xml, unId,ecToken);   //照面信息发送成功，取得返回值存入库中。同时修改申请数据照面信息提交状态
                String fileNumber = strMap.get("fileNumber");
                String licenseId  = strMap.get("licenseId");
                log.error("文件编码：{}，文件id{}",fileNumber,licenseId);
                if (StrUtil.isNotBlank(fileNumber)&&StrUtil.isNotBlank(licenseId)) {
                    LicenseInformation licenseInformation = new LicenseInformation();
                    licenseInformation.setId(unId);
                    licenseInformation.setLicenseId(licenseId);
                    licenseInformation.setFileNumber(fileNumber);
                    licenseInformation.setUscc(holderCode);
                    licenseInformation.setName(name);
                    licenseInformation.setStatus(0);
                    licenseInformationServiceImpl.addLicenseInformation(licenseInformation);
                    cPersonService.updateLicenseStatus(unId,"0");
                }
            }else {//申领过电子证照
                int i = OnlineTaskUtil.updateXmlDataSend(ecToken, licenseList.get(0).getLicenseId(), xml, unId);
                if (i==00){
                    cPersonService.updateLicenseStatus(unId,"1");
                    LicenseInformation licenseInformation = licenseList.get(0);
                    licenseInformation.setLicenseId(unId);
                    licenseInformation.setStatus(0);
                    licenseInformationServiceImpl.addLicenseInformation(licenseInformation);
                }
            }

        }
    }

    /***
     *@Author duxiangyun
     *@Description   取回电子证照
     *@Date 2024/11/13
     */
    @Scheduled(fixedDelay = 3 * 60 * 1000)
    public void getECFileTask(){
        List<LicenseInformation> licenseInfomations = licenseInformationServiceImpl.get("0");
        //1、获取证照的base64编码
        //获取请求参数
        //取得证照数据
        try {
            //取得未获取电子证照的数据
            List<Map<String,String>> fileList = licenseInfomations.stream().map(item -> {
                Map<String, String > itemMap = new HashMap<>();
                itemMap.put("id", item.getId());
                itemMap.put("fileNumber", item.getFileNumber());
                itemMap.put("status", item.getStatus().toString());
                itemMap.put("name", item.getName());
                return itemMap;
            }).collect(Collectors.toList());
            //循环处理每条数据
            for (Map<String, String> itemMap : fileList) {
                //获取证照数据,base64编码
                String fileNumber = OnlineTaskUtil.getFileRequest(itemMap.get("fileNumber"));
                String fileName   = itemMap.get("name");
                String id = itemMap.get("id");
                if (!fileNumber.isEmpty()){   //若果存在一个文件出错后面所有的多拿不到文件了,获取文件编码不返回空就返回base64编码
                    //base 进行解码
                    //文件写到本地
                    String ecFilePath = FileHandleUtil.fileSave(fileNumber, id, fileName);
                    //修改文件获取状态   0代表未获取 1代表已经获取
                    licenseInformationServiceImpl.updateStatusById(id,"1");
                    //修改申请表数据文件路径 以及电子证照状态 2 代表已经拿到电子证
                    List<Map<String,Object>>  lists = new ArrayList<>();
                    Map<String,Object>  map  = new HashMap<>();
                    map.put("uid",id);
                    map.put("path",StrUtil.join("/","/uploads/ecfile",id,StrUtil.join(".",fileName,"ofd")));
                    map.put("originalPath",StrUtil.join("/","/uploads/ecfile",id,StrUtil.join(".",fileName,"ofd")));
                    map.put("name",StrUtil.join(".",fileName,"ofd"));
                    lists.add(map);
                    service.updateStatusAndfile(id,"2",JSON.toJSONString(lists));
                    cPersonService.updateStatusAndfile(id,"2",JSON.toJSONString(lists));
                }else {
                    //该文件还没完成盖章
                    log.error("{} 还未完成盖章",id);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

//    /***
//     *@Author duxiangyun
//     *@Description   法人变更取回电子证照
//     *@Date 2024/11/13
//     */
//    @Scheduled(fixedDelay = 3 * 60 * 1000)
//    public void cPGetECFileTask(){
//        List<LicenseInformation> licenseInfomations = licenseInformationServiceImpl.get("0");
//        //1、获取证照的base64编码
//        //获取请求参数
//        //取得证照数据
//        try {
//            //取得未获取电子证照的数据
//            List<Map<String,String>> fileList = licenseInfomations.stream().map(item -> {
//                Map<String, String > itemMap = new HashMap<>();
//                itemMap.put("id", item.getId());
//                itemMap.put("fileNumber", item.getFileNumber());
//                itemMap.put("status", item.getStatus().toString());
//                itemMap.put("name", item.getName());
//                return itemMap;
//            }).collect(Collectors.toList());
//            //循环处理每条数据
//            for (Map<String, String> itemMap : fileList) {
//                //获取证照数据,base64编码
//                String fileNumber = OnlineTaskUtil.getFileRequest(itemMap.get("fileNumber"));
//                String fileName   = itemMap.get("name");
//                String id = itemMap.get("id");
//                if (!fileNumber.isEmpty()){   //若果存在一个文件出错后面所有的多拿不到文件了,获取文件编码不返回空就返回base64编码
//                    //base 进行解码
//                    //文件写到本地
//                    String ecFilePath = FileHandleUtil.fileSave(fileNumber, id, fileName);
//                    //修改文件获取状态   0代表未获取 1代表已经获取
//                    licenseInformationServiceImpl.updateStatusById(id,"1");
//                    //修改申请表数据文件路径 以及电子证照状态 2 代表已经拿到电子证
//                    List<Map<String,Object>>  lists = new ArrayList<>();
//                    Map<String,Object>  map  = new HashMap<>();
//                    map.put("uid","");
//                    map.put("path",ecFilePath);
//                    map.put("originalPath",ecFilePath);
//                    map.put("name",StrUtil.join(".",fileName,"ofd"));
//                    lists.add(map);
//                    cPersonService.updateStatusAndfile(id,JSON.toJSONString(lists),"2");
//                }else {
//                    //该文件还没完成盖章
//                    log.error("{} 还未完成盖章",id);
//                }
//            }
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
//    }


    public String  getToken(){
        String accessToken= "false";
        String getTokenUrl= "http://65.26.106.115:8003/license-api-release/oauth/token" ;
        Map<String, Object> formDataMap = new HashMap<>();
        formDataMap.put("client_id","linewell-oauth");
        formDataMap.put("client_secret","linewell-mobile");
        formDataMap.put("grant_type","password");
        formDataMap.put("scope","readwrite");
        formDataMap.put("username","dzzz_bajgxxxt");
        formDataMap.put("password","Bajgxxxt_6777");
        HttpResponse execute = HttpUtil.createPost(getTokenUrl).header("Content-Type", "application/x-www-form-urlencoded")
                .form(formDataMap).execute();
        String responseBody = execute.body();
        if (execute.isOk()){
            Map<String, String> resMap = JSON.parseObject(execute.body(), Map.class);
            accessToken = resMap.get("access_token");
            log.error("获取电子证照token响应体:{}",responseBody);
        }
        return accessToken;
    }

    /**
     * 保安服务公司设立照面信息获取
     * "select  ITEM_SERVICE_NUMBER ,ITEM_COMPANYNAME,ITEM_USCC,ITEM_ADDRESS,ITEM_LEGALNAME,ITEM_BUSINESSSCOPE, " +
     *            "ITEM_REGISTEREDCAPITAL  ,ITEM_CODE_NUMBER ,ID ，CREATED from  `security_flow`.tlk_securitysevicek where item_uscc  is not null  and  STATELABEL=\"审批通过\"   ORDER BY  CREATED  desc  LIMIT 10 ;  ";
     */
    public List<Map<String,String >>  getECInformationHandel(List<SecurityServicek> serviceList){
        List<Map<String,String>>  mapList ;
        mapList =serviceList.stream().map(item -> {
            Map<String, String> par = new HashMap<>();
            String licenseNumber = item.getItemServiceNumber();    //获取证照编号
            par.put("licenseNumber", licenseNumber);
            String issueDate = DateUtil.dateFormatter(item.getItemOverTime(),"yyyy-MM-dd");           //颁证时间   //审核通过时间
            log.info("+++++结束时间{}",issueDate);
            par.put("issueDate", issueDate);
            String holder = item.getItemCompanyName();           //持证者 --公司名称
            par.put("holder", holder);
            String holderCode = item.getItemLegalCardnumber();  //统一社会信用代码   //或者法人身份证号码
            par.put("holderCode", holderCode);
            String zs = item.getItemAddress();       // 住所
            par.put("zs", zs);
            String fddbr = item.getItemLegalName();   //法定代表人
            par.put("fddbr", fddbr);
            String itemBusinessscope = item.getItemBusinessScope();    //经营范围
            par.put("fwfw", OnlineTaskUtil.strHandle(itemBusinessscope));
            String zczb= item.getItemRegisteredCapital();                 //注册资本
            par.put("zczb", zczb);
            String pzwh = item.getItemCodeNumber();              //批准文号
            par.put("pzwh", pzwh);
            String ID =item.getID();
            par.put("unid", ID);                            //ID
            return  par;
        }).collect(Collectors.toList());
        return mapList;
    }
    /**
     * 保安服务公司法人变更照面信息
     * "select  ITEM_SERVICE_NUMBER ,ITEM_COMPANYNAME,ITEM_USCC,ITEM_ADDRESS,ITEM_LEGALNAME,ITEM_BUSINESSSCOPE, " +
     *            "ITEM_REGISTEREDCAPITAL  ,ITEM_CODE_NUMBER ,ID ，CREATED from  `security_flow`.tlk_securitysevicek where item_uscc  is not null  and  STATELABEL=\"审批通过\"   ORDER BY  CREATED  desc  LIMIT 10 ;  ";
     */
    public List<Map<String,String >>  getCPersonECInformationHandel(List<ChangeLegalPerson> changeLegalList){
        List<Map<String,String>>  mapList ;
        mapList =changeLegalList.stream().map(item -> {
            Map<String, String> par = new HashMap<>();
            String licenseNumber = item.getItemSecurityTrainPermitNo();    //获取证照编号
            par.put("licenseNumber", licenseNumber);
            String issueDate =DateUtil.dateFormatter(item.getItemOverTime(),"yyyy-MM-dd");           //颁证时间   //审核通过时间
            par.put("issueDate", issueDate);
            log.info("+++++结束时间{}",issueDate);
            String holder = item.getItemCompanyName();           //持证者 --公司名称
            par.put("holder", holder);
            String holderCode = item.getItemUscc();  //统一社会信用代码
            par.put("holderCode", holderCode);
            String zs = item.getItemAddress();       // 住所
            par.put("zs", zs);
            String fddbr = item.getItemAppointmentLegalName();   //法定代表人
            par.put("fddbr", fddbr);
            String itemBusinessscope = item.getItemBusinessScope();    //经营范围
            par.put("fwfw", OnlineTaskUtil.strHandle(itemBusinessscope));
            String zczb= item.getItemRegisteredCapital();                 //注册资本
            par.put("zczb", zczb);
            String pzwh = item.getItemApprovalNumber();              //批准文号
            par.put("pzwh", pzwh);
            String ID =item.getId();
            par.put("unid", ID);                            //ID
            return  par;
        }).collect(Collectors.toList());
        return mapList;
    }
}
