package com.bjtdba.merchant.service.impl;

import com.bjtdba.entity.merchant.MerchantQrcode;
import com.bjtdba.entity.merchant.SystemConfigValue;
import com.bjtdba.merchant.dao.*;
import com.bjtdba.merchant.dto.PayUser;
import com.bjtdba.merchant.service.MerchantCashierService;
import com.bjtdba.merchant.vo.MerchantCashierShow;
import com.bjtdba.utils.QRCodeUtil;
import com.bjtdba.utils.ResponseUtil;
import com.bjtdba.utils.uploadDownload;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class MerchantCashierServiceImpl implements MerchantCashierService {

    @Autowired
    private MerchantDao merchantDao;
    @Autowired
    private MerchantQrcodeDao merchantQrcodeDao;
    @Autowired
    private StoreOrderDao storeOrderDao;
    @Autowired
    private OrderMerchantDao orderMerchantDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private UserVisitDao userVisitDao;
    @Autowired
    private MerchantConsumptionScoreLog merchantConsumptionScoreLog;
    @Autowired
    private SystemConfigValueDao systemConfigValueDao;

    @Override
    public Object selectMerchantByMerId(int mer_id) throws Exception {
        Map<String,Object> data=new HashMap<String,Object>();
        if(StringUtils.isBlank(String.valueOf(mer_id))){
            return ResponseUtil.fail("参数为空");
        }
        MerchantCashierShow merchantCashierShow = merchantDao.selectByMerId(mer_id);
        Map<String,String> srcMap = merchantQrcodeDao.selectMerchantQrcodeByMerId(mer_id);
        if(srcMap!=null){
            if(srcMap.get("code_id").toString().trim().equals("")||srcMap.get("code_id").toString().trim().equals(null)) {

                merchantCashierShow.setQrcode_src(srcMap.get("qrcode_src"));
                merchantCashierShow.setShow_src(srcMap.get("show_src"));
                merchantCashierShow.setCode_id(srcMap.get("code_id"));
            }else{
                merchantCashierShow=UpQrCode(merchantCashierShow,mer_id);
            }
        }
        data.put("merchantCashierShow",merchantCashierShow);
        return ResponseUtil.ok(data);
    }

    /**
     * 更新生产二维码的方法
     */

    @Value("${zhifu.url}")
    private String zhifuurl;

    public MerchantCashierShow UpQrCode(MerchantCashierShow merchantCashierShow,int mer_id)throws Exception{
        /**
         * 1、生成时间戳   充当二维码的code以及名称
         * 2、将本地的二维码上传到远程数据库
         * 3、将二维码的地址以及uid、mer_id、code、二维码的url 保存到数据库中  与商户产生绑定
         * 3、将本的二维码删除
         */

        // 存放在二维码中的内容    http://app.bjtdba.com/offlinepay/index.html?id=164888564678229691#/
//        测试环境：https://offlinepay-test.bjtdba.com/mer_id=148


//        生产环境：https://offlinepay.bjtdba.com/mer_id=148
        long timeNew = System.currentTimeMillis(); // 13位数的时间戳    这个也是code
        String text = zhifuurl+mer_id;
        // 嵌入二维码的图片路径
        String imgPath = "";
        // 生成的二维码的路径及名称
        String destPath = "/Users/hanyuxing/qrcode/"+timeNew+".jpg";
        //生成二维码
        QRCodeUtil.encode(text, imgPath, destPath, true);
        // 解析二维码
        String str = QRCodeUtil.decode(destPath);
        // 打印出解析出的内容
        System.out.println(str);
        //上传二维码到c d n
        File file = new File(destPath);
        FileInputStream input = new FileInputStream(file);
        MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain", IOUtils.toByteArray(input));
        Map<String, String> qrCode = uploadDownload.qrCode(multipartFile);
        MerchantQrcode merchantQrcode = new MerchantQrcode();
//        merchantQrcode.setUid(uid);
        merchantQrcode.setMer_id(mer_id);
        merchantQrcode.setCode_id("");
        merchantQrcode.setQrcode_src(qrCode.get("url"));
        merchantQrcode.setShow_src(qrCode.get("url"));
        merchantCashierShow.setQrcode_src(qrCode.get("url"));
        merchantCashierShow.setShow_src(qrCode.get("url"));
        merchantQrcodeDao.upMerchantQrcode(merchantQrcode);
        deleteDir(new File("/Users/hanyuxing/qrcode"));
        return merchantCashierShow;
    }

    private boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //递归删除目录中的子目录下
            for (int i=0;i<children.length;i++){
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }
    @Override
    public Object selectMerchantOrder(int mer_id, String start_time, String end_time) {
        try {
            Map<String,Object> data=new HashMap<String,Object>();
            Map<String,Long> orderLineOrderSun = storeOrderDao.onLineOrdeSun(mer_id,start_time,end_time);
            Map<String,Long> belowTheLineSum = orderMerchantDao.belowTheLineSum(mer_id,start_time,end_time);
            Double consumption = merchantConsumptionScoreLog.selectConsumptionScore(1,null,mer_id);
            int sun = userDao.selectByMerId(mer_id,start_time,end_time);
            int visitorNumber = userVisitDao.selectVisitorNumberByMerId(mer_id,start_time,end_time);
            int xianxiarenshu=orderMerchantDao.belowTheLineNumber(mer_id,start_time,end_time);
            //20250227 添加京豆，贡献值
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");

            SimpleDateFormat sdfHH=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            Date startDate=sdfHH.parse(start_time+" 00:00:00");
            Date endDate=sdfHH.parse(end_time+" 23:59:59");
            long stimeL=startDate.getTime()/1000; //10位的时间戳
            long endtimeL=endDate.getTime()/1000;  //10位的时间戳
            String jingdousum=orderMerchantDao.jingdouSum(mer_id,stimeL,endtimeL);
            String gongxianSumsum=orderMerchantDao.gongxianSum(mer_id,start_time,end_time);


            Long a = orderLineOrderSun.get("orderLineNumber");
            Long b = belowTheLineSum.get("belowTheLineNumber");
            Long number = orderLineOrderSun.get("orderLineNumber") + xianxiarenshu;
            data.put("orderLineOrderSun",orderLineOrderSun);
            data.put("belowTheLineSum",belowTheLineSum);
            data.put("consumption",consumption);
            data.put("jingdousum",jingdousum);
            data.put("gongxianSumsum",gongxianSumsum);
            data.put("sun",sun);
            data.put("visitorNumber",visitorNumber);
            data.put("number",number);
        return ResponseUtil.ok(data);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.fail();
        }
    }

    @Override
    public Object payUserList(Integer pageNum, Integer pageSize,int mer_id) {
        Map<String,Object> data=new HashMap<String,Object>();
        List<PayUser> onLineOrdeList = storeOrderDao.onLineOrdeList(mer_id);
        List<PayUser> belowTheLineList = orderMerchantDao.belowTheLineList(mer_id);
        List<PayUser> visitList = userVisitDao.visitorList(mer_id);
        List<PayUser> payUsers = new ArrayList<>();
        payUsers.addAll(onLineOrdeList);
        payUsers.addAll(belowTheLineList);
        //payUsers.addAll(visitList);

        Collections.sort(payUsers, Comparator.comparing(PayUser::getCreate_time, (t1, t2) -> t2.compareTo(t1)));
        int total = payUsers.size();//
        PageInfo<PayUser> pageInfo = null;
        if(total/pageSize+1>= pageNum){
            Page page = new Page(pageNum, pageSize);
            page.setTotal(total);
            //计算当前需要显示的数据下标起始值
            int startIndex = (pageNum - 1) * pageSize;
            int endIndex = Math.min(startIndex + pageSize,total);
            //从链表中截取需要显示的子链表，并加入到Page
            page.addAll(payUsers.subList(startIndex,endIndex));
            pageInfo = new PageInfo<>(page);
        }else{
            Page page = new Page(0, 0);
            page.setTotal(0);
            List<PayUser> a = new ArrayList<>();
            pageInfo = new PageInfo<>(a);
        }
        data.put("pageInfo",pageInfo);
        return ResponseUtil.ok(data);
    }

    /**
     * 消费分
     * 1、判断该商户是否开启消费分
     * 2、以结算  pm=1 status = 1
     * 3、预估   pm=1 status = 0
     * 4、以释放 pm=2
     */
    @Override
    public Object merchantConsumption(int mer_id) {
        Map<String,Object> data=new HashMap<String,Object>();
        Integer consumptionScore = merchantDao.selectConsumptionScoreByMerId(mer_id);
        Double settlement = 0.0;
        Double predict = 0.0;
        Double release = 0.0;
        if(consumptionScore == 1){
            settlement = merchantConsumptionScoreLog.selectConsumptionScore(1,1,mer_id);
            predict = merchantConsumptionScoreLog.selectConsumptionScore(1,0,mer_id);
            release = merchantConsumptionScoreLog.selectConsumptionScore(2,1,mer_id);
        }
        data.put("consumptionScore",consumptionScore);
        data.put("settlement",settlement);
        data.put("predict",predict);
        data.put("release",release);
        return ResponseUtil.ok(data);
    }

    @Override
    public Object updateConsumptionScore(String mer_id) {
        System.out.println("mer_id======"+mer_id);
        Integer mer_id1 = Integer.parseInt(mer_id);
        String configValue = systemConfigValueDao.selectConfigValueByKeyAndMerId("base_commission",mer_id1);
        int status = 0;
        if(configValue!=null){
            if(Integer.parseInt(configValue)<2){
                int a = systemConfigValueDao.updateConfigValue("base_commission",mer_id1);
            }
            status = merchantDao.updateConsumptionScore(mer_id1);
        }else{
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            //添加进去
            SystemConfigValue rrxSystemConfigValue = new SystemConfigValue();
            rrxSystemConfigValue.setConfigKey("base_commission");
            rrxSystemConfigValue.setValue("5");
            rrxSystemConfigValue.setCreateTime(new Date());
            rrxSystemConfigValue.setMerId(mer_id1);
            int configStatus = systemConfigValueDao.insert(rrxSystemConfigValue);
            status = merchantDao.updateConsumptionScore(mer_id1);
        }
        if(status != 1){
            return ResponseUtil.fail("开通异常");
        }

        return ResponseUtil.ok("开通成功");
    }

    @Override
    public Object selectMerchantConsumptionScoreLog(Integer pageNum, Integer pageSize,String mer_id) {
        Map<String,Object> data=new HashMap<String,Object>();
        PageHelper.startPage(pageNum,pageSize);
        PageInfo<MerchantConsumptionScoreLog> pageInfo = null;
        List<MerchantConsumptionScoreLog> merchantConsumptionScoreLoglist = merchantConsumptionScoreLog.selectMerchantConsumptionScoreLog(mer_id);
        pageInfo = new PageInfo<MerchantConsumptionScoreLog>(merchantConsumptionScoreLoglist);
        if(pageInfo.getPages()<pageNum){
            PageHelper.startPage(0,0);
            List<MerchantConsumptionScoreLog> order = new ArrayList<>();
            pageInfo = new PageInfo<>(order);
        }
        data.put("merchantConsumptionScoreLoglist",pageInfo);
        return ResponseUtil.ok(data);
    }
}
