package com.fs.his.task;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.net.URLDecoder;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fs.common.annotation.Log;
import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.exception.CustomException;
import com.fs.common.service.impl.SmsServiceImpl;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.SecurityUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.company.domain.*;
import com.fs.company.mapper.*;
import com.fs.company.service.ICompanyService;
import com.fs.company.service.impl.CompanyMoneyLogsServiceImpl;
import com.fs.company.vo.RedPacketMoneyVO;
import com.fs.core.config.WxMaConfiguration;
import com.fs.course.mapper.FsCourseRedPacketLogMapper;
import com.fs.course.service.IFsCourseWatchLogService;
import com.fs.crm.param.SmsSendParam;
import com.fs.erp.domain.ErpDeliverys;
import com.fs.erp.domain.ErpOrderQuery;
import com.fs.erp.dto.*;
import com.fs.erp.service.IErpOrderService;
import com.fs.event.TemplateBean;
import com.fs.event.TemplateEvent;
import com.fs.event.TemplateListenEnum;
import com.fs.fastGpt.config.ModeConfig;
import com.fs.fastGpt.domain.FastGptRole;
import com.fs.fastGpt.mapper.FastGptChatSessionMapper;
import com.fs.fastgptApi.param.ChatParam;
import com.fs.fastgptApi.param.VoiceParam;
import com.fs.fastgptApi.result.ChatDetailTStreamFResult;
import com.fs.fastgptApi.service.Impl.AudioServiceImpl;
import com.fs.fastgptApi.util.AudioUtils;
import com.fs.his.config.StoreConfig;
import com.fs.his.domain.*;
import com.fs.his.dto.*;
import com.fs.his.enums.FsStoreOrderLogEnum;
import com.fs.his.enums.FsStoreOrderStatusEnum;
import com.fs.his.enums.ShipperCodeEnum;
import com.fs.his.mapper.*;
import com.fs.his.param.FsFollowMsgParam;
import com.fs.his.param.FsInquiryOrderFinishParam;
import com.fs.his.param.FsPackageOrderDoPayParam;
import com.fs.his.service.*;
import com.fs.his.service.impl.*;
import com.fs.his.vo.FsStoreProductExcelVO;
import com.fs.his.vo.FsStoreProductVO;
import com.fs.his.vo.FsSubOrderResultVO;
import com.fs.im.dto.*;
import com.fs.im.service.IImService;
import com.fs.qw.mapper.QwAppContactWayMapper;
import com.fs.qw.mapper.QwExternalContactTransferLogMapper;
import com.fs.qw.service.IQwAppContactWayService;
import com.fs.qw.service.IQwExternalContactTransferLogService;
import com.fs.qw.service.impl.QwAppContactWayServiceImpl;
import com.fs.qwApi.Result.QwSendMsgResult;
import com.fs.qwApi.param.QwSendMsgParam;
import com.fs.qwApi.service.QwApiService;
import com.fs.qwApi.service.impl.QwApiServiceImpl;
import com.fs.system.domain.SysConfig;
import com.fs.system.mapper.SysConfigMapper;
import com.fs.system.oss.CloudStorageService;
import com.fs.system.oss.OSSFactory;
import com.fs.tzBankPay.TzBankService.TzBankService;
import com.fs.tzBankPay.doman.*;
import com.google.gson.Gson;
import com.qiniu.util.Json;
import com.tencentcloudapi.mongodb.v20180408.models.SpecItem;
import io.lettuce.core.ScriptOutputType;
import javafx.scene.effect.Bloom;
import jdk.nashorn.internal.scripts.JS;
import org.apache.catalina.Store;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import javax.sound.sampled.Line;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.ParseException;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.logging.Logger;
import java.util.regex.Pattern;

import static com.fs.his.utils.PhoneUtil.decryptPhone;

@Component("task")
public class Task {
    @Autowired
    private FsUserCouponMapper fsUserCouponMapper;
    @Autowired
    private SysConfigMapper sysConfigMapper;
    @Autowired
    private IFsPrescribeService fsPrescribeService;
    @Autowired
    IFsStoreOrderService fsStoreOrderService;
    @Autowired
    FsStoreOrderMapper fsStoreOrderMapper;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private FsPackageOrderMapper fsPackageOrderMapper;
    @Autowired
    private IFsFollowService fsFollowService;
    @Autowired
    private IFsStoreAfterSalesService fsStoreAfterSalesService;
    @Autowired
    IErpOrderService erpOrderService;
    @Autowired
    FsIntegralOrderMapper integralOrderMapper;
    @Autowired
    IFsInquiryOrderService iFsInquiryOrderService;
    @Autowired
    FsPackageMapper fsPackageMapper;
    @Autowired
    FsStoreProductMapper fsStoreProductMapper;
    @Autowired
    CompanyMapper companyMapper;
    @Autowired
    private CompanyMoneyLogsMapper moneyLogsMapper;
    @Autowired
    FsUserMapper fsUserMapper;
    @Autowired
    IFsUserIntegralLogsService fsUserIntegralLogsService;
    @Autowired
    SmsServiceImpl smsService;
    @Autowired
    FsStoreOrderItemMapper fsStoreOrderItemMapper;

    @Autowired
    FsPatientMapper fsPatientMapper;
    @Autowired
    FsPrescribeDrugMapper fsPrescribeDrugMapper;
    @Autowired
    FsFollowMapper fsFollowMapper;
    @Autowired
    private IImService imService;
    @Autowired
    private FsInquiryOrderMapper inquiryOrderMapper;
    @Autowired
    private CompanyVoiceCallerMapper companyVoiceCallerMapper;
    @Autowired
    private CompanyVoiceLogsMapper companyVoiceLogsMapper;
    @Autowired
    FsPackageOrderServiceImpl packageOrderService;
    @Autowired
    private IFsStoreOrderLogsService fsStoreOrderLogsService;
    org.slf4j.Logger logger= LoggerFactory.getLogger(getClass());
    @Autowired
    IFsDoctorService doctorService;
    @Autowired
    CompanyUserMapper companyUserMapper;
    @Autowired
    FsInquiryOrderMapper fsInquiryOrderMapper;
    @Autowired
    FsCourseRedPacketLogMapper fsCourseRedPacketLogMapper;
    @Autowired
    QwApiService qwApiService;
    //每天执行一次
    @Autowired
    IQwAppContactWayService qwAppContactWayService;

    @Autowired
    FastGptChatSessionMapper fastGptChatSessionMapper;

    @Autowired
    IQwExternalContactTransferLogService qwExternalContactTransferLogService;

    @Autowired
    private IFsCourseWatchLogService fsCourseWatchLogService;

    public void tt() throws Exception
    {


    }


    public void addPrescribeImg() throws Exception
    {
       List<Long> ids= fsPrescribeService.selectFsPrescribeByPrescribeIdByOrderType();
        for (Long id : ids) {
            System.out.println(id);
            fsPrescribeService.PrescribeStoreImg(id);
        }
    }

    public void addQwWatchLog() throws Exception
    {
        fsCourseWatchLogService.addCourseWatchLogDay();
    }


    public void transferLog() throws Exception
    {
        qwExternalContactTransferLogService.updateQwExternalContactTransferLogByStatus();


    }

    public void isArtificial() throws Exception
    {
        fastGptChatSessionMapper.updateFastGptChatSessionByIsReply();

    }
    public void expirationQwAppCountWay(){
        qwAppContactWayService.expirationQwAppCountWay();

    }
    public void sendOrderMsg() throws Exception
    {
        List<FsStoreOrder> fsStoreOrders = fsStoreOrderMapper.selectStoreOrderIdByFollow();
        for (FsStoreOrder fsStoreOrder : fsStoreOrders) {

            fsStoreOrderService.addOrderEatMsg(fsStoreOrder);
        }

    }
    public void redPacketSubMoney() throws Exception
    {
        List<RedPacketMoneyVO> redPacketMoneyVOS = fsCourseRedPacketLogMapper.selectFsCourseRedPacketLogByCompany();
        for (RedPacketMoneyVO redPacketMoneyVO : redPacketMoneyVOS) {
            companyService.subtractCompanyMoney(redPacketMoneyVO.getMoney(),redPacketMoneyVO.getCompanyId());
        }
    }


    public void updateCompanyUserStatus()
    {
        CompanyUser user = new CompanyUser();
        user.setStatus("0");
        user.setDelFlag("0");
        List<CompanyUser> companyUsers = companyUserMapper.selectCompanyUserList(user);
        for (CompanyUser companyUser : companyUsers) {
            if(SecurityUtils.matchesPassword("123456", companyUser.getPassword())){
                companyUser.setStatus("1");
                companyUserMapper.updateCompanyUser(companyUser);
                logger.info("密码为123456 停用账号："+companyUser.getUserId()+":"+companyUser.getNickName());
            }
        }
    }
    public void couponStatus()
    {
        fsUserCouponMapper.updateFsUserCouponStatusByLimtTime();
    }

    //每10秒执行一次
    public void auditPrescribe()
    {
        SysConfig sysConfig = sysConfigMapper.selectConfigByConfigKey("his.inquiryConfig");
        String configValue = sysConfig.getConfigValue();
        Map<String, Object> config = (Map<String, Object>) JSON.parse(configValue);
        boolean isAudit = (boolean)config.get("isAutoPrescribeAudit");
        if (isAudit){
            fsPrescribeService.auditPrescribe();
        }
    }

    public void deliveryOp()
    {
        List<FsStoreOrder> orders = fsStoreOrderMapper.selectOmsOrderdeliveryOp();
        for(FsStoreOrder order:orders){

            ErpOrderQueryRequert request=new ErpOrderQueryRequert();

            request.setCode(order.getExtendOrderId());
            ErpOrderQueryResponse response=erpOrderService.getOrder(request);
            if(response.getOrders()!=null&&response.getOrders().size()>0){
                for(ErpOrderQuery orderQuery : response.getOrders()){
                    if(orderQuery.getDeliverys()!=null&&orderQuery.getDeliverys().size()>0){
                        for(ErpDeliverys delivery:orderQuery.getDeliverys()){
                            if(delivery.getDelivery()&& StringUtils.isNotEmpty(delivery.getMail_no())){
                                //更新商订单状态 删除REDIS
                                fsStoreOrderService.deliveryOrder(order.getOrderCode(),delivery.getMail_no(),delivery.getExpress_code(),delivery.getExpress_name());
                                redisCache.deleteObject("delivery"+":"+order.getExtendOrderId());
                            }
                        }

                    }
                }
            }
        }



    }

    public void CreateOmsAndHis()
    {
        List<Long> omsList = fsStoreOrderMapper.selectFsStoreOrderNoCreateOms();
        for (Long l : omsList) {
            try {
                fsStoreOrderService.createOmsOrder(l);
            } catch (Exception e) {
            }
        }
        List<Long> tuiOrderList = fsStoreOrderMapper.selectFsStoreOrderNoTuiOrder();
        for (Long l : tuiOrderList) {
            try {
                fsStoreOrderService.tuiOrder(l);
            } catch (Exception e) {
            }

        }
    }

    public void createFollow()
    {
        List<FsStoreOrder> orders = fsStoreOrderMapper.selectStoreOrderIdByFollow();
        for (FsStoreOrder order : orders) {
            try {

                fsStoreOrderService.addFsFollowByStoreOrder(order);
            }catch (Exception e){
                logger.info("创建随访错误："+order);
            }
        }
    }
    @Autowired
    IFsStoreSubOrderService fsStoreSubOrderService;


    public void puSubStoreOrder()
    {
        List<Long> longs = fsStoreSubOrderService.selectFsStoreSubOrderByNoPush();
        int i=0;
        for (Long aLong : longs) {
            FsSubOrderResultVO fsSubOrderResultVO = fsStoreSubOrderService.TuiFsStoreSubOrderByStoreOrder(aLong);
            if (fsSubOrderResultVO!=null&&fsSubOrderResultVO.getCode()!=null&&fsSubOrderResultVO.getCode()==1){
                i++;
                if (i>65){
                    return;
                }
            }

        }
    }

    public void refundOp()
    {
        List<FsStoreAfterSales> list=fsStoreAfterSalesService.selectFsStoreAfterSalesByDoAudit();
        if(list!=null){
            for(FsStoreAfterSales afterSales:list){
                try {
                    fsStoreAfterSalesService.auditing(afterSales);
                }catch (Exception e){

                }

            }
        }

    }
    public void isAfterSales() {
        SysConfig sysConfig = sysConfigMapper.selectConfigByConfigKey("his.store");
        String configValue = sysConfig.getConfigValue();
        Map<String, Object> config = (Map<String, Object>) JSON.parse(configValue);
        Integer storeAfterSalesDay = (Integer)config.get("storeAfterSalesDay");
        List<FsStoreOrder> fsStoreOrders = fsStoreOrderMapper.selectFsStoreOrderNoIsAfterSales(storeAfterSalesDay);
        for (FsStoreOrder fsStoreOrder : fsStoreOrders) {
            try {
                fsStoreOrderService.addIntegralAndShareByStoreOrder(fsStoreOrder);
            }catch (Exception e) {
                logger.info("分账错误: " + fsStoreOrder.getOrderCode());
            }
        }

    }


    public void integralOrderStatus(){
        integralOrderMapper.updatePackageOrderStatusByDeliveryTime();
    }

    public void packageStatus()
    {
        fsPackageOrderMapper.updatePackageOrderStatusByFinishTime();
        SysConfig sysConfig = sysConfigMapper.selectConfigByConfigKey("his.store");
        String configValue = sysConfig.getConfigValue();
        Map<String, Object> config = (Map<String, Object>) JSON.parse(configValue);
        Integer unPayTime = (Integer)config.get("unPayTime");
        fsPackageOrderMapper.updatePackageOrderStatusByStatus(unPayTime);
    }

    public void endFollow(){
        fsStoreOrderService.endFollow();
    }


    public void erDelivery(){
        fsStoreOrderService.endDeliveryOrder();
    }



    @Autowired
    private ICompanyService companyService;
    public void addCompanyMoney(){
        List<FsStoreOrder> orders = fsStoreOrderMapper.selectOrderIds();
        for (FsStoreOrder order : orders){
            CompanyMoneyLogs moneyLog1 = moneyLogsMapper.selectCompanyMoneyLogsByOrderId(order.getOrderId(), 5);
            CompanyMoneyLogs moneyLog2 = moneyLogsMapper.selectCompanyMoneyLogsByOrderId(order.getOrderId(),3);
            if (moneyLog1==null){
                companyService.subtractCompanyMoney(order);
            }
            if (moneyLog2==null){
                companyService.addCompanyMoney(order);
                FsStoreOrder orderMap = new FsStoreOrder();
                orderMap.setOrderId(order.getOrderId());
                orderMap.setTuiMoneyTime(new Date());
                fsStoreOrderMapper.updateFsStoreOrder(orderMap);
            }
        }
    }

    //每天执行一次
    public void syncExpress()
    {
        List<Long> ids =fsStoreOrderMapper.selectSyncExpressIds();
        for (Long id : ids) {
            fsStoreOrderService.syncExpress(id);
        }

    }

    public void refundCompanyMoney(){
        List<FsStoreOrder> list = fsStoreOrderMapper.selectOrders();
        for (FsStoreOrder order : list ){
            companyService.refundCompanyMoney(order);
        }
    }

    public void subIntegral()
    {
        fsUserIntegralLogsService.subFsUserIntegralLogsByOrder5();
    }

    public void finishInquiry(){
        List<FsInquiryOrder> orders = inquiryOrderMapper.selectFsInquiryOrderByFinish();
        for (FsInquiryOrder order : orders) {
            // 订单已超过48小时，执行关闭操作
            FsInquiryOrderFinishParam param = new FsInquiryOrderFinishParam();
            param.setOrderId(order.getOrderId());
            param.setDoctorId(order.getDoctorId());
            try {
                iFsInquiryOrderService.autoFinishOrder(param);
            }catch (Exception e){
                logger.info("订单已超过48小时关闭异常"+param);
            }

        }
    }


    public void finishStoreOrderByXN(){
        List<FsStoreOrder> orders = fsStoreOrderMapper.selectFinishStoreOrderByXN();
        if (orders!=null&&orders.size()>0){
            for (FsStoreOrder o : orders) {
                FsStoreOrder order = fsStoreOrderMapper.selectFsStoreOrderByOrderId(o.getOrderId());
                if (order.getStatus()!= 2) {
                    continue;
                }
                FsStoreOrder o1 = new FsStoreOrder();
                o1.setUpdateTime(new DateTime());
                o1.setFinishTime(new Date());
                o1.setOrderId(o.getOrderId());
                o1.setStatus(FsStoreOrderStatusEnum.STATUS_4.getValue());
                int i = fsStoreOrderMapper.updateFsStoreOrder(o1);
                fsStoreOrderLogsService.create(order.getOrderId(), FsStoreOrderLogEnum.FINISH_ORDER.getValue(),
                        FsStoreOrderLogEnum.FINISH_ORDER.getDesc());
                if (order.getCompanyId()!=null&&order.getTuiMoneyStatus()==0&&order.getPayType()==1){
                    companyService.addCompanyMoney(order);
                }
            }
        }
    }

    public void inquirySendSms(){
        List<FsInquiryOrder> orders = inquiryOrderMapper.selectFsInquiryOrderBySendSms();
        for (FsInquiryOrder order : orders){
            FsInquiryOrderPatientDTO patientDTO = JSON.parseObject(order.getPatientJson(),FsInquiryOrderPatientDTO.class);
            if (patientDTO!=null&&patientDTO.getPatientName()!=null){
                FsUser fsUser = fsUserMapper.selectFsUserByUserId(order.getUserId());
                if (fsUser!=null&&fsUser.getPhone()!=null){
                    smsService.sendUserSms(fsUser.getPhone(), patientDTO.getPatientName(), "2");
                    order.setIsSendSms(1);
                    inquiryOrderMapper.updateFsInquiryOrder(order);
                }

            }
        }
    }

    //处理30天问题件
    public void clearProblemOrder(){
        List<FsStoreOrder> orders = fsStoreOrderMapper.selectFsStoreOrderByProblemOrder();
        for (FsStoreOrder order : orders){
            FsStoreOrder map = new FsStoreOrder();
            map.setStatus(4);
            map.setOrderId(order.getOrderId());
            fsStoreOrderMapper.updateFsStoreOrder(map);
        }

    }


    //30天无通话记录回收坐席
    public void recoverCompanyCaller(){
        SysConfig sysConfig = sysConfigMapper.selectConfigByConfigKey("his.store");
        StoreConfig fsPayConfig = new Gson().fromJson(sysConfig.getConfigValue(), StoreConfig.class);
        Integer days = fsPayConfig.getStoreCall();
        List<CompanyVoiceCaller> list = companyVoiceCallerMapper.selectCompanyVoiceCallerByRecover(days);
        for (CompanyVoiceCaller caller : list){
            Long count = companyVoiceLogsMapper.selectCompanyVoiceLogsCountByCallerNo(caller.getCallerNo(),caller.getBindTime());
            if (count==0){
                caller.setCompanyId(0l);
                caller.setCompanyUserId(0l);
                caller.setMobile("");
                caller.setStatus(1);
                caller.setBindTime(null);
                companyVoiceCallerMapper.updateCompanyVoiceCaller(caller);
            }
        }
    }


    public void tb() {
        packageOrderService.payConfirm("", "1780763211956486144", "1075999515888117190", "14", 1);
    }







    public void addSend(){
       String userId="4048905872";
       String doctorId="147";
        String storeOrderId="470920";
        String followId="1062986";
        //发送给用户
        MsgDTO msgDTO=new MsgDTO();
        MsgCustomDTO customDTO=new MsgCustomDTO();
        customDTO.setType("startDrugReport");
        customDTO.setImType(2);
        customDTO.setOrderId(storeOrderId);
        customDTO.setFollowId(followId);
        msgDTO.setCloudCustomData(JSONUtil.toJsonStr(customDTO));
        msgDTO.setFrom_Account("U-"+userId);
        msgDTO.setTo_Account("D-"+doctorId);
        List<MsgDataDTO> msgs=new ArrayList<>();
        MsgDataDTO msg=new MsgDataDTO();
        msg.setMsgType("TIMTextElem");
        msg.setMsgContent(new MsgDataFormatDTO("您好"));
        msgs.add(msg);
        msgDTO.setMsgBody(msgs);
        MsgResponseDTO msgResponseDTO = imService.sendMsg(msgDTO);
        System.out.println(msgResponseDTO);
    }

//    @Autowired
//    private FsStoreMapper fsStoreMapper;
//    @Autowired
//    private IFsExpressService expressService;
//
//    public void task() {
//        List<FsStoreOrder> list = fsStoreOrderMapper.selectOrders();
//        for (FsStoreOrder order : list){
//            FsStore store = fsStoreMapper.selectFsStoreByStoreId(order.getStoreId());
//            if (order.getStatus()==3){
//                //订阅物流回调
//                String lastFourNumber = "";
//                if (order.getDeliveryCode().equals(ShipperCodeEnum.SF.getValue())) {
//                    if (store.getSendPhone()!=null){
//                        lastFourNumber = store.getSendPhone();
//                    }else {
//                        lastFourNumber = order.getUserPhone();
//                    }
//                    if (lastFourNumber.length() == 11) {
//                        lastFourNumber = StrUtil.sub(lastFourNumber, lastFourNumber.length(), -4);
//                    }
//                }
//                expressService.subscribeEspress(order.getOrderCode(),order.getDeliveryCode(),order.getDeliverySn(),lastFourNumber);
//            }
//        }
//    }

    //    public void task() {
//        List<FsPackage> fsPackages = fsPackageMapper.selectFsPackageList(new FsPackage());
//        for (FsPackage fsPackage : fsPackages) {
//            String productJson = fsPackage.getProductJson();
//            if (productJson != null && productJson != "") {
//                JSONArray objects = JSONUtil.parseArray(fsPackage.getProductJson());
//                List<FsPackagePruductDTO> products = JSONUtil.toList(objects, FsPackagePruductDTO.class);
//                if (products != null && products.size() > 0) {
//                    for (FsPackagePruductDTO product : products) {
//                        FsStoreProduct fsStoreProduct = fsStoreProductMapper.selectFsStoreProductByProductId(product.getProductId());
//                        product.setPrescribeSpec(fsStoreProduct.getPrescribeSpec());
//                    }
//                    String jsonStr = JSONUtil.toJsonStr(products);
//                    fsPackage.setProductJson(jsonStr);
//                    fsPackageService.updateFsPackage(fsPackage);
//                }
//            }
//        }
//    }


//    public void task(){
//        String filePath = "C:\\home\\ex.xlsx";
//        try {
//            InputStream inputStream = new FileInputStream(new File(filePath));
//            ExcelUtil<FsStoreProduct> util = new ExcelUtil<>(FsStoreProduct.class);
//            List<FsStoreProduct> list = util.importExcel(inputStream);
//            for (FsStoreProduct fsStoreProduct : list) {
//                String barCode = fsStoreProduct.getBarCode();
//                List<FsStoreProduct> p= fsStoreProductMapper.selectCode(barCode);
//                if (p!=null&&p.size()>0){
//                    for (FsStoreProduct storeProduct : p) {
//                        FsStoreProduct s = new FsStoreProduct();
//                        s.setProductId(storeProduct.getProductId());
//                        s.setProductName(fsStoreProduct.getProductName());
//                        s.setPrescribeSpec(fsStoreProduct.getPrescribeSpec());
//                        fsStoreProductMapper.updateFsStoreProduct(s);
//                        logger.info( "更新商品:"+storeProduct.getProductName()+"规格"+fsStoreProduct.getPrescribeSpec());
//                    }
//                }
//            }
//        }catch (Exception e){
//
//        }
//        logger.info("更新商品完成");
//
//    }
//    public void task(){
//        FsPatient p = new FsPatient();
//        p.setIsDel(0);
//        List<FsPatient> fsPatients = fsPatientMapper.selectFsPatientList(p);
//        Long num=0L;
//        for (FsPatient fsPatient : fsPatients) {
//            boolean b=false;
//            if (fsPatient.getIdCard()!=null){
//
//                String idCardNumber = fsPatient.getIdCard();
//                if (idCardNumber == null || idCardNumber.length() != 18) {
//                    b=true;
//                }else {
//                    String regex = "\\d{17}[0-9Xx]";
//                    if (!Pattern.matches(regex, idCardNumber)) {
//                        b=true;
//                    }else {
//                        try {
//                            String birthDateString = idCardNumber.substring(6, 14);
//                            LocalDate birthDate = LocalDate.parse(birthDateString, DateTimeFormatter.ofPattern("yyyyMMdd"));
//                            LocalDate currentDate = LocalDate.now();
//                            int age = currentDate.getYear() - birthDate.getYear();
//                            if (currentDate.getMonthValue() < birthDate.getMonthValue()
//                                    || (currentDate.getMonthValue() == birthDate.getMonthValue()
//                                    && currentDate.getDayOfMonth() < birthDate.getDayOfMonth())) {
//                                age--;
//                            }
//                            if (age < 18) {
//                                b=true;
//                            }
//                        }catch (Exception e){
//                            b=true;
//                        }
//
//                    }
//                }
//            }
//            if (b==true){
//                FsPatient fsPatient1 = new FsPatient();
//                fsPatient1.setPatientId(fsPatient.getPatientId());
//                fsPatient1.setIsDel(1);
//                fsPatientMapper.updateFsPatient(fsPatient1);
//                num++;
//                logger.info("删除病人:"+fsPatient.getPatientName()+":"+fsPatient.getIdCard());
//                logger.info("数量:"+num);
//            }
//        }
//    }

//    public void aa(){
//        String[] numbers = {
//                "1774771531176476672",
//                "1774747581851631616",
//                "1774735879609253888",
//                "1774728203970019328",
//                "1774721325441482752",
//                "1774706058258808832",
//                "1774691294237425664",
//                "1774686009271779328",
//                "1774679466350477312",
//                "1774674516987871232"
//        };
//
//        for (String number : numbers) {
//            FsStoreOrder fsStoreOrder = fsStoreOrderMapper.selectFsStoreOrderByOrderCode(number);
//            Long orderId = fsStoreOrder.getOrderId();
//            List<FsStoreOrderItem> fsStoreOrderItems = fsStoreOrderItemMapper.selectFsStoreOrderItemListByOrderId(orderId);
//            for (FsStoreOrderItem fsStoreOrderItem : fsStoreOrderItems) {
//                fsStoreOrderItemMapper.deleteFsStoreOrderItemByItemId(fsStoreOrderItem.getItemId()+"");
//            }
//            FsPrescribeDrug fsPrescribeDrug = new FsPrescribeDrug();
//            fsPrescribeDrug.setPrescribeId(fsStoreOrder.getPrescribeId());
//            List<FsPrescribeDrug> fsPrescribeDrugs = fsPrescribeDrugMapper.selectFsPrescribeDrugList(fsPrescribeDrug);
//            if (fsPrescribeDrugs!=null){
//                for (FsPrescribeDrug prescribeDrug : fsPrescribeDrugs) {
//                    String drugName = prescribeDrug.getDrugName();
//                    FsStoreProduct fsStoreProduct = fsPrescribeDrugMapper.selectFsPrescribeDrugCode(drugName, fsStoreOrder.getStoreId());
//                    List<FsStoreProductAttrValue> fsStoreProductAttrValues = fsStoreProductAttrValueMapper.selectFsStoreProductAttrValueByProductId(fsStoreProduct.getProductId());
//                    if (fsStoreProductAttrValues!=null&&fsStoreProductAttrValues.size()>0){
//                        FsStoreProductAttrValue fsStoreProductAttrValue = fsStoreProductAttrValues.get(0);
//                        prescribeDrug.setProductId(fsStoreProduct.getProductId());
//                        prescribeDrug.setProductAttrValueId(fsStoreProductAttrValue.getId());
//                        fsPrescribeDrugMapper.updateFsPrescribeDrug(prescribeDrug);
//                    }
//
//                }
//            }
//
//            FsPrescribe prescribe=fsPrescribeService.selectFsPrescribeByPrescribeId(fsStoreOrder.getPrescribeId());
//            List<FsPrescribeDrug> drugs=fsPrescribeDrugMapper.selectFsPrescribeDrugList(fsPrescribeDrug);
//            List<FsStoreOrderItem> items=new ArrayList<>();
//            Long totalNum=0l;
//            BigDecimal totalPrice=new BigDecimal(0);
//            BigDecimal totalCostPrice = new BigDecimal("0");
//            for(FsPrescribeDrug drug:drugs){
//                totalPrice=totalPrice.add(drug.getDrugPrice().multiply(BigDecimal.valueOf(drug.getDrugNum())));
//                totalNum=totalNum+drug.getDrugNum();
//                FsStoreOrderItem item=new FsStoreOrderItem();
//                item.setProductId(drug.getProductId());
//                item.setIsDrug(drug.getIsDrug());
//                item.setStoreId(prescribe.getStoreId());
//                item.setProductAttrValueId(drug.getProductAttrValueId());
//                if (drug.getProductAttrValueId()!=null){
//                    FsStoreProductAttrValue value = fsStoreProductAttrValueMapper.selectFsStoreProductAttrValueById(drug.getProductAttrValueId());
//                    if (value.getCost()!=null){
//                        if (drug.getDrugNum()!=null){
//                            totalCostPrice=totalCostPrice.add(value.getCost().multiply(BigDecimal.valueOf(drug.getDrugNum())));
//                        }
//                    }
//                }
//
//                item.setNum(drug.getDrugNum());
//                FsStoreOrderItemDTO dto=new FsStoreOrderItemDTO();
//                dto.setImage(drug.getDrugImgUrl());
//                dto.setNum(drug.getDrugNum());
//                FsStoreProduct product=fsStoreProductMapper.selectFsStoreProductByProductId(drug.getProductId());
//                if(product!=null){
//                    dto.setProductName(product.getProductName());
//                    dto.setProductId(product.getProductId());
//                }
//                FsStoreProductAttrValue value=fsStoreProductAttrValueMapper.selectFsStoreProductAttrValueById(drug.getProductAttrValueId());
//                if(value!=null){
//                    dto.setSku(value.getSku());
//                    dto.setBarCode(value.getBarCode());
//                    dto.setPrice(value.getPrice());
//                    dto.setNum(drug.getDrugNum());
//                    dto.setImage(value.getImage());
//                }
//                item.setIsPrescribe(1);
//                item.setJsonInfo(JSON.toJSONString(dto));
//                items.add(item);
//            }
//            //中药总价处理
//            if(prescribe.getPrescribeType().equals(2)){
//                FsPrescribeUsageDTO dto=JSONUtil.toBean(prescribe.getUsageJson(),FsPrescribeUsageDTO.class);
//                totalPrice=totalPrice.multiply(BigDecimal.valueOf(dto.getCounts()));
//                totalNum=dto.getCounts();
//                totalCostPrice=totalCostPrice.multiply(BigDecimal.valueOf(dto.getCounts()));
//            }
//            FsStoreOrder order = new FsStoreOrder();
//            order.setOrderId(fsStoreOrder.getOrderId());
//            order.setCostPrice(totalCostPrice);
//            order.setItemJson(JSONUtil.toJsonStr(items));
//            fsStoreOrderMapper.updateFsStoreOrder(order);
//            for(FsStoreOrderItem item:items){
//                item.setOrderId(fsStoreOrder.getOrderId());
//                fsStoreOrderItemMapper.insertFsStoreOrderItem(item);
//            }
//        }
//
//
//    }

//    public void task()
//    {
//
//        List<FsPackageOrder> fsPackageOrders = fsPackageOrderMapper.selectFsPackageOrderallList();
//        Integer num=0;
//        for (FsPackageOrder fsPackageOrder : fsPackageOrders) {
//            FsPackageOrder o = fsPackageOrderMapper.selectFsPackageOrderByOrderId(fsPackageOrder.getOrderId());
//            if (o.getPackageJson()!=null){
//                System.out.println("更改订单："+o.getOrderId());
//                List<FsPackagePruductDTO> products=null;
//                try {
//                    Map<String,Object> packageJson = (Map)JSON.parse(o.getPackageJson());
//                    String json = (String)packageJson.get("productJson");
//                    JSONArray objects =JSONUtil.parseArray(json);
//                     products=JSONUtil.toList(objects,FsPackagePruductDTO.class);
//
//                }catch (Exception e){
//                    System.out.println("json解析错误"+o.getPackageJson());
//                }
//               BigDecimal toal = new BigDecimal(0);
//                for (FsPackagePruductDTO product : products) {
//                    if (product.getCount()==null){
//                        product.setCount(0);
//                    }
//                    if (product.getCostPrice()==null){
//                        product.setCostPrice(new BigDecimal("0"));
//                    }
//                    toal= toal.add(product.getCostPrice().multiply(new BigDecimal(product.getCount())));
//                }
//                Integer followRate = 6;
//                BigDecimal in=new BigDecimal("0");
//                if (o.getCycle()!=null){
//                    in= new BigDecimal((o.getCycle()/followRate) *300);
//                }
//
//                FsPackageOrder order = new FsPackageOrder();
//                order.setOrderId(o.getOrderId());
//                order.setInquiryCostPrice(in);
//                order.setProductCostPrice(toal);
//                order.setTotalCostPrice(toal.add(in));
//                iFsPackageOrderService.updateFsPackageOrder(order);
//                num++;
//            }
////
//        }
//
//        logger.info("所有订单同步完成："+num);
//
//
//    }


//    @Autowired
//    private TzBankService tzBankService;

//    public void task(){
//        List<FsStorePayment> fsStorePayments = fsStorePaymentMapper.selectFsStorePaymentbyshare();
//        //交易金额
//       String s="";
//        for (FsStorePayment fsStorePayment : fsStorePayments) {
//            String busType="";
//            if (fsStorePayment.getBusinessType()==1){
//                busType ="inquiry";
//            }else if(fsStorePayment.getBusinessType()==2){
//                busType ="store";
//            }else {
//                busType ="package";
//            }
//            //交易金额
//            BigDecimal payMoney = fsStorePayment.getPayMoney();
//            BigDecimal share = payMoney.multiply(new BigDecimal(0.001)).setScale(2, RoundingMode.HALF_UP);
//
//                OrderShareParam orderShareParam = new OrderShareParam();
//                //// 传的分账订单号
//                orderShareParam.setOutOrderNo("share"+fsStorePayment.getPayCode());
//                //旧的支付外部订单号 支付时上上传的
//                orderShareParam.setOldPayOutOrderNo(busType+fsStorePayment.getPayCode());
//                orderShareParam.setTrxAmt(fsStorePayment.getPayMoney().doubleValue());
//                OrderShareParam.sharers sharer = new OrderShareParam.sharers();
//                //分账金额
//            if (share.compareTo(BigDecimal.ZERO)!=0){
//                sharer.setShareAmt(share.doubleValue());
//                sharer.setSharerCstName("重庆云联融智科技有限公司");
//                sharer.setSharerCstNo("943103603046907709");
//                List<OrderShareParam.sharers> sharers = new ArrayList<>();
//                sharers.add(sharer);
//                orderShareParam.setSharers(sharers);
//            }
//                TzBankResult<OrderShareResult> r = tzBankService.orderShare(orderShareParam);
//                if (r.getRetType().equals("S")){
//                    if (r.getBody().getShareOrdStatus().equals("90")||r.getBody().getShareOrdStatus().equals("60")){
//                        FsStorePayment sharePayment = new FsStorePayment();
//                        sharePayment.setPaymentId(fsStorePayment.getPaymentId());
//                        sharePayment.setShareStatus(1);
//                        sharePayment.setShareCode(r.getBody().getShareOrderNo());
//                        sharePayment.setShareMoney(new BigDecimal(r.getBody().getTrxAmt()));
//                        fsStorePaymentMapper.updateFsStorePayment(sharePayment);
//                        logger.info("分账完成:"+r);
//                        FsStoreOrder fsStoreOrder = fsStoreOrderMapper.selectFsStoreOrderByOrderCode(fsStorePayment.getBusinessCode());
//                        if (fsStoreOrder!=null){
//                            FsStoreOrder fsStoreOrder1 = new FsStoreOrder();
//                            fsStoreOrder1.setOrderId(fsStoreOrder.getOrderId());
//                            fsStoreOrder1.setIsAfterSales(0);
//                            fsStoreOrderMapper.updateFsStoreOrder(fsStoreOrder1);
//                        }
//                    }else {
//                        logger.info("分账失败:"+fsStorePayment);
//                        s+="/n 分账失败"+fsStorePayment.getPayCode()+r.getRetMsg();
//                    }
//                }else {
//                    logger.info("分账请求失败:"+fsStorePayment+r.getRetMsg());
//                    s+="/n 分账失败"+fsStorePayment.getPayCode()+r.getRetMsg();
//                }
//
//        }
//        logger.info("分账请求完成:"+s);
//}


        //同步流水
//    public void task(){
//        CompanyMoneyLogs item = moneyLogsMapper.selectCompanyMoneyLogsById(248884L);
//        String logsId=item.getLogsId().toString();
//        Long companyId=item.getCompanyId();
//        BigDecimal companyMoney= item.getBalance();
//        List<CompanyMoneyLogs> logs=moneyLogsMapper.selectCompanyMoneyLogsByCompanyId(companyId,logsId);
//        if(logs!=null){
//            for(CompanyMoneyLogs log:logs){
//                companyMoney=companyMoney.add(log.getMoney());
//                CompanyMoneyLogs logMap=new CompanyMoneyLogs();
//                logMap.setLogsId(log.getLogsId());
//                logMap.setBalance(companyMoney);
//                moneyLogsMapper.updateCompanyMoneyLogs(logMap);
//            }
//            Company company = new Company();
//            company.setCompanyId(companyId);
//            company.setMoney(companyMoney);
//            companyMapper.updateCompany(company);
//        }
//
//    }


//    public String upTp(String s)  {
//        BufferedImage img = null;
//        InputStream is =null;
//        try {
//            URL url = new URL(s);
//            URLConnection connection = url.openConnection();
//            is = connection.getInputStream();
//        } catch (IOException e) {
//            return s;
//        }
//        String caselsh  = s.substring(s.lastIndexOf(".")+1);
//        CloudStorageService storage = OSSFactory.build();
//        System.out.println(s);
//        String url = storage.uploadSuffix(is, "."+caselsh);
//        try {
//            is.close();
//        } catch (IOException e) {
//        }
//        return url;
//
//    }
//public void st() throws Exception
//{
//    String destinationFolder = "E:/st/";
//    int i=1;
//    List<String> strings = fsInquiryOrderMapper.selectTongueImages();
//    for (String string : strings) {
//        String[] split = string.split(",");
//        for (String imageUrl : split) {
//            String fileName = i+".jpg";
//            try {
//                URL url = new URL(imageUrl);
//                InputStream is = url.openStream();
//                File destinationDir = new File(destinationFolder);
//                if (!destinationDir.exists()) {
//                    destinationDir.mkdirs();
//                }
//                FileOutputStream fos = new FileOutputStream(destinationFolder + fileName);
//
//                byte[] buffer = new byte[4096];
//                int bytesRead;
//                while ((bytesRead = is.read(buffer)) != -1) {
//                    fos.write(buffer, 0, bytesRead);
//                }
//                System.out.println(i);
//                i++;
//                fos.close();
//                is.close();
//            } catch (IOException e) {
//                System.out.println("错误: ");
//            }
//        }
//    }
//
//}
}
