package com.pj.tb_goods_transit;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.pj.current.config.SystemObject;
import com.pj.current.dto.APPLoginUserInfo;
import com.pj.enummj.*;
import com.pj.retry.SmsRetryService;
import com.pj.tb_goods_cart.TbGoodsCart;
import com.pj.tb_goods_cart.TbGoodsCartService;
import com.pj.tb_order.TbOrder;
import com.pj.tb_order.TbOrderMapper;
import com.pj.tb_people.TbPeople;
import com.pj.tb_people.TbPeopleMapper;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * @Author Mechrevo
 * @Date 2023 07 21 16 36
 **/
@Service
@Transactional(rollbackFor = Exception.class)
public class MethodGoodsTransitService {

    @Autowired
    private TbGoodsTransitService tbGoodsTransitService;


    /** 短信运营商 */
    @Autowired
    private SmsRetryService smsRetryService;
    @Autowired
    private TbOrderMapper tbOrderMapper;
    @Autowired
    private TbPeopleMapper tbPeopleMapper;
    @Autowired
    private TbGoodsCartService tbGoodsCartService;



    /**
     * todo:给边民组组员发送短信通知
     */
    public int sendSms(List<TbPeople> peopleIdList) {
        Map<String,Object> param = new HashMap<>();
        param.put("msg","您的组长已下单,请前往app进行确认!");
//        AliyunSmsService.sendSms("18934859524", "边民互市","SMS_462415029",JSONUtils.toJSONString(param));
        //获取当前电脑核心数
        int processors = Runtime.getRuntime().availableProcessors() / 2;
        //创建固定线程
        ExecutorService executorService = Executors.newFixedThreadPool(processors);
        //执行任务
        //每次执行20条
        int bai = 20;
        //计算需要创建的线程数
        int threads = (int) Math.ceil((double) peopleIdList.size() / bai);
        //创建计数器
        int count = 0;
        for (int i = 0; i < threads; i++) {
            int start = i * bai;
            int end = Math.min(start + bai,peopleIdList.size());
            //截取集合数量
            List<TbPeople> enterpriseList = peopleIdList.subList(start, end);
            //多线程执行任务
            executorService.submit(() -> {
                enterpriseList.forEach(item -> {
                    // 给边民发送短信,调用短信商接口API
                    try {
                        smsRetryService.sendSmsMsg(item.getBorderTel());
                    } catch (Exception e) {
                        System.out.println("异常被抓住了!");
                        throw new RuntimeException(e);
                    }

                });
            });
            //计数
            count += enterpriseList.size();
            System.out.println("发送的短信数量为: " + count + " 条。");

        }
        //关闭多线程
        executorService.shutdown();
        return count;
    }


    /**
     * 设置订单表的属性
     * @param tbGoodsTransit
     * @param appLoginInfo
     * @return
     */
    public TbOrder setTbOrderProperties(TbGoodsTransit tbGoodsTransit, APPLoginUserInfo appLoginInfo){
        //执行采购,创建一级市场订单表
        TbOrder tbOrder = new TbOrder();
        List<TbPeople> tbPeopleList = tbPeopleMapper.selectList(new LambdaQueryWrapper<TbPeople>()
                .eq(TbPeople::getId, appLoginInfo.getFk()).eq(TbPeople::getIsLock,IsLock.IS_LOCK_ON.getCode())
                .eq(TbPeople::getDeleteStatus,DeleteStatus.DELETE_STATUS_ON.getCode()));
        if(tbPeopleList.size() != 1)throw new RuntimeException("当前用户信息有误!");
        //设置属性
        tbOrder.setGroupId(tbPeopleList.get(0).getGroupId());
        tbOrder.setTradeAreaId(tbGoodsTransit.getTradeAreaId());
        tbOrder.setTradeAreaName(tbGoodsTransit.getTradeAreaName());
        tbOrder.setGoodsId(tbGoodsTransit.getId());
        tbOrder.setSaleMainId(Long.valueOf(tbGoodsTransit.getMerchantId()));
		tbOrder.setTradeNo(SystemObject.getREFcode("YJSCDD",new Date()));  // 交易编号
        tbOrder.setBuyUserId(tbPeopleList.get(0).getId());
        tbOrder.setBuyUserType(appLoginInfo.getUserType() == 1? 3 + "" : 2 + "");
        tbOrder.setBuyUserName(appLoginInfo.getLoginName());
        tbOrder.setCallCarStatus(0); // 叫车状态,默认未叫车
        tbOrder.setEnterpriseId(Long.valueOf(tbGoodsTransit.getMerchantId()));
        tbOrder.setEnterpriseName(tbGoodsTransit.getMerchantName());
        tbOrder.setTotalWeight(tbGoodsTransit.getGrossWeight());
        tbOrder.setTotalPrice(tbGoodsTransit.getPrice());
        tbOrder.setCancelPeople(1); // 1=默认边民确认
		tbOrder.setTradeTime(new Date());  // 交易时间
//		tbOrder.setPayType();  //交易类型
//		tbOrder.setRealPrice();  // 当前结算金额
        tbOrder.setShouldPrice(tbGoodsTransit.getPrice());  //应结算金额
//		tbOrder.setReceiveName();
//		tbOrder.setReceivePhone(); // 收货人的基本信息
//		tbOrder.setReceiveAddress();
        tbOrder.setGoodsNames(tbGoodsTransit.getGoodsName());
        tbOrder.setShopId(tbGoodsTransit.getShopId());
        tbOrder.setShopName(tbGoodsTransit.getShopName());
        tbOrder.setGoodsUnit(tbGoodsTransit.getGoodsUnits());
        //设置下单时的默认状态
        tbOrder.setDeleteStatus(DeleteStatus.DELETE_STATUS_ON.getCode()); // 删除状态默认是1,可用
        tbOrder.setEnterpriseConfirm(ConfirmStatus.CONFIRM_STATUS_ZERO.getCode()); // 0为待商家确认
        tbOrder.setPeopleConfirmStatus(ConfirmStatus.CONFIRM_STATUS_ZERO.getCode()); // 0为待边民确认
        tbOrder.setSend(DeliverStatus.DELIVER_STATUS_ZERO.getCode());  // 0为未发货 1为已发货
        tbOrder.setTradeStatus(TradeStatus.TRADE_STATUS_ONE.getCode()); //支付状态默认是1,已支付
        tbOrder.setResaleStatus(ResaleStatus.RESALE_STATUS_ZERO.getCode()); // 是否转售状态,默认未转售 0
        tbOrder.setFinishStatus(OrderStatus.ORDER_STATUS_ZERO.getCode());  // 订单完成状态,默认未完成 0
        //订单表基本字段
        tbOrder.setCreateBy(appLoginInfo.getLoginId());
        tbOrder.setCreateName(appLoginInfo.getLoginName());
        tbOrder.setCreateTime(new Date());
        //申报信息
        tbOrder.setApply(ApplyStatus.APPLY_STATUS_ZERO.getCode()); // 默认待申报


        return tbOrder;
    }

    /**
     * 如果购物车内的商品为已下单,则将所有人添加该商品到购物车的状态全部改成已下单
     * @param tbGoodsCarts
     */
    public void goodsCartIsOrder(List<TbGoodsCart> tbGoodsCarts){
        if(tbGoodsCarts.size() == 0)return;
        //将购物的的商品订单状态改成已下单
        tbGoodsCarts.forEach(item -> {
            item.setGoodsIsorderStatus(1);
        });
        tbGoodsCartService.saveBatch(tbGoodsCarts);
    }




    /**
     * 方法抽取  导入
     * @param row
     * @param sheet
     * @param count
     * @return
     */
    public int importMethod(HSSFRow row, HSSFSheet sheet, int count){

        //创建接受集合
        List<TbGoodsTransit> list = new ArrayList<>();

        for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
            //封装数据到行对象
            row = sheet.getRow(i);
            //定义返回值实体
            TbGoodsTransit tbGoodsTransit = new TbGoodsTransit();
            //解析数据
            if(row.getCell(1) != null && !row.getCell(1).toString().trim().equals(""))
                tbGoodsTransit.setMerchantId(row.getCell(1).getStringCellValue());

            if(row.getCell(2) != null && !row.getCell(2).toString().trim().equals(""))
                tbGoodsTransit.setMerchantName(row.getCell(2).getStringCellValue());

            if(row.getCell(3) != null && !row.getCell(3).toString().trim().equals(""))
                tbGoodsTransit.setGoodsType(row.getCell(3).getStringCellValue());

            if(row.getCell(4) != null && !row.getCell(4).toString().trim().equals(""))
                tbGoodsTransit.setGoodsName(row.getCell(4).getStringCellValue());

            if(row.getCell(5) != null && !row.getCell(5).toString().trim().equals(""))
                tbGoodsTransit.setGoodsUnits(row.getCell(5).getStringCellValue());

            HSSFCell cell6 = row.getCell(6);
            if (cell6 != null && (cell6.getCellType() == CellType.NUMERIC || cell6.getCellType() == CellType.FORMULA))
                tbGoodsTransit.setNetWeight(cell6.getNumericCellValue());

            HSSFCell cell7 = row.getCell(7);
            if (cell7 != null && (cell7.getCellType() == CellType.NUMERIC || cell7.getCellType() == CellType.FORMULA))
                tbGoodsTransit.setGrossWeight(cell7.getNumericCellValue());

            HSSFCell cell8 = row.getCell(8);
            if (cell8 != null && (cell8.getCellType() == CellType.NUMERIC || cell8.getCellType() == CellType.FORMULA))
                tbGoodsTransit.setPrice(cell8.getNumericCellValue());

            if(row.getCell(9) != null && !row.getCell(9).toString().trim().equals(""))
                tbGoodsTransit.setDeclareOdd(row.getCell(9).getStringCellValue());

            if(row.getCell(10) != null && !row.getCell(10).toString().trim().equals(""))
                tbGoodsTransit.setPlaceOrigin(row.getCell(10).getStringCellValue());

            if(row.getCell(11) != null && !row.getCell(11).toString().trim().equals(""))
                tbGoodsTransit.setDescription(row.getCell(11).getStringCellValue()   );

            HSSFCell cell9 = row.getCell(12);
            if (cell9 != null && (cell9.getCellType() == CellType.NUMERIC || cell9.getCellType() == CellType.FORMULA))
                tbGoodsTransit.setStock(cell9.getNumericCellValue());

            HSSFCell cell10 = row.getCell(13);
            if (cell10 != null && (cell10.getCellType() == CellType.NUMERIC || cell10.getCellType() == CellType.FORMULA))
                tbGoodsTransit.setGoodsStatus((int)cell10.getNumericCellValue());

            HSSFCell cell11 = row.getCell(14);
            if (cell11 != null && (cell11.getCellType() == CellType.NUMERIC || cell11.getCellType() == CellType.FORMULA))
                tbGoodsTransit.setAuditStatus((int) cell11.getNumericCellValue());

            HSSFCell cell2 = row.getCell(15);
            if (cell2 != null && cell2.getCellType() == CellType.NUMERIC && DateUtil.isCellDateFormatted(cell2))
                if(row.getCell(15) != null && !row.getCell(15).toString().trim().equals(""))
                    tbGoodsTransit.setAuditTime(cell2.getDateCellValue());

            if(row.getCell(16) != null && !row.getCell(16).toString().trim().equals(""))
                tbGoodsTransit.setRemark(row.getCell(16).getStringCellValue());

            //公共字段
            HSSFCell cell4 = row.getCell(17);
            if (cell4 != null && cell4.getCellType() == CellType.NUMERIC && DateUtil.isCellDateFormatted(cell4)) {
                tbGoodsTransit.setCreateTime(cell4.getDateCellValue());
            }

            if(row.getCell(18) != null && !row.getCell(18).toString().trim().equals(""))
                tbGoodsTransit.setCreateBy(row.getCell(18).getStringCellValue());

            if(row.getCell(19) != null && !row.getCell(19).toString().trim().equals(""))
                tbGoodsTransit.setCreateName(row.getCell(19).getStringCellValue());

            if(row.getCell(20) != null && !row.getCell(20).toString().trim().equals(""))
                tbGoodsTransit.setUpdateBy(row.getCell(20).getStringCellValue());

            if(row.getCell(21) != null && !row.getCell(21).toString().trim().equals(""))
                tbGoodsTransit.setUpdateName(row.getCell(21).getStringCellValue());

            HSSFCell cell3 = row.getCell(22);
            if (cell3 != null && cell3.getCellType() == CellType.NUMERIC && DateUtil.isCellDateFormatted(cell3)) {
                tbGoodsTransit.setUpdateTime(cell3.getDateCellValue());
            }
            //删除状态,默认可用
            tbGoodsTransit.setDeleteStatus(1);
//			//添加到集合
			list.add(tbGoodsTransit);

        }

        System.out.println("待处理数据量为: " + list.size() + " 条。");

        //创建多线程
        ExecutorService executorService = Executors.newFixedThreadPool(6);

        //每次100条
        int bai = 100;
        //计算需要创建的线程数
        int threads = (int) Math.ceil((double) list.size() / bai);
        for (int i = 0; i < threads; i++) {
            int start = i * bai;
            int end = Math.min(start + bai,list.size());

            //截取集合数量
            List<TbGoodsTransit> enterpriseList = list.subList(start, end);

            //多线程执行任务
            executorService.submit(() -> {
                tbGoodsTransitService.saveBatch(enterpriseList);
            });
            //计数
            count += enterpriseList.size();

        }
        //关闭线程池
        executorService.shutdown();

        return count;
    }

}
