package com.pj.project.tb_business;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pj.constants.UserTypeEnum;
import com.pj.current.config.CarConfig;
import com.pj.current.config.PartConfig;
import com.pj.current.satoken.StpUserUtil;
import com.pj.project.tb_business_item.TbBusinessItem;
import com.pj.project.tb_business_item.TbBusinessItemService;
import com.pj.project.tb_business_people.TbBusinessPeople;
import com.pj.project.tb_business_people.TbBusinessPeopleService;
import com.pj.project.tb_car.TbCar;
import com.pj.project.tb_car.TbCarService;
import com.pj.project.tb_costomer.TbCostomer;
import com.pj.project.tb_costomer.TbCostomerService;
import com.pj.project.tb_driver.TbDriver;
import com.pj.project.tb_driver.TbDriverService;
import com.pj.project.tb_item.TbItem;
import com.pj.project.tb_item.TbItemService;
import com.pj.project.tb_item_type.TbItemType;
import com.pj.project.tb_item_type.TbItemTypeService;
import com.pj.project.tb_notices.TbNoticesService;
import com.pj.project.tb_pass_record.TbPassRecordService;
import com.pj.project.tb_unit.TbUnit;
import com.pj.project.tb_unit.TbUnitService;
import com.pj.project4sp.admin.SpAdmin;
import com.pj.utils.sg.AjaxJson;
import com.pj.utils.so.SoMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;

/**
 * Service: tb_business -- 入境登记
 *
 * @author qzy
 */
@Service
public class TbBusinessService extends ServiceImpl<TbBusinessMapper, TbBusiness> implements IService<TbBusiness> {

    /**
     * 底层 Mapper 对象
     */
    @Autowired
    TbBusinessMapper tbBusinessMapper;
    @Resource
    private TbCarService tbCarService;
    @Resource
    private TbDriverService tbDriverService;
    @Resource
    private TbCostomerService tbCostomerService;

    @Resource
    private TbItemService tbItemService;
    @Resource
    private TbItemTypeService tbItemTypeService;
    @Resource
    private TbBusinessItemService tbBusinessItemService;

    @Resource
    TbUnitService tbUnitService;
    @Resource
    TbBusinessPeopleService tbBusinessPeopleService;
    @Resource
    private PartConfig partConfig;
    @Resource
    private CarConfig carConfig;

    @Resource
    private TbPassRecordService tbPassRecordService;
    @Resource
    private TbNoticesService tbNoticesService;


    public TbBusiness checkCarNo(String carNo) {
        QueryWrapper<TbBusiness> ew = new QueryWrapper<>();
        ew.eq("card_no", carNo)
                .eq("admin_confirm_out", 0);
        return this.getOne(ew);
    }

    /**
     * 增
     */
    public AjaxJson addOrUpdate(TbBusiness t) {
        if (checkCarNo(t.getCardNo()) != null && StrUtil.isEmpty(t.getId())) {
            return AjaxJson.getError("该车辆【" + t.getCardNo() + "】有未完成业务");
        }
        if (checkCarNo(t.getChinaCarNo()) != null && StrUtil.isEmpty(t.getId())) {
            return AjaxJson.getError("该车辆【" + t.getChinaCarNo() + "】有未完成业务");
        }
        double carSize = t.getCardSize();
        if (carSize > carConfig.getMaxLength()) {
            return AjaxJson.getError("车辆规格不能大于" + carConfig.getMaxLength());
        }
        double netWeight = t.getNetWeight();
        if (netWeight > carConfig.getMaxWeight()) {
            return AjaxJson.getError("车辆载重不能大于" + carConfig.getMaxWeight());
        }
        t.setCreateBy(StpUserUtil.getAdmin().getName());
        createCarUnit(t);
        String customerId = t.getCustomerId();
        TbCostomer tbCostomer = tbCostomerService.getById(customerId);
        t.setCustomerName(tbCostomer.getName()).setCustomerType(tbCostomer.getPayType());
        if (StrUtil.equals(customerId, UserTypeEnum.PLATFORM_ADMIN.getCustomerId())) {
            t.setConfirmInputBy(StpUserUtil.getAdmin().getName())
                    .setConfirmInput(1)
                    .setConfirmInputTime(new Date());
        }
        if (StrUtil.isEmpty(t.getId())) {
            t.setCreateTime(new Date());
            t.setNo(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmm")) + RandomUtil.randomNumbers(4));
            storeMsg(t.getCustomerId(), "新增一条业务数据:【" + t.getNo() + "】" + DateUtil.now() + "。");
        } else {
            storeMsg(t.getCustomerId(), "业务订单:【" + t.getNo() + "】数据发生更改，" + DateUtil.now() + "。");
        }
        List<TbBusinessItem> items = JSONUtil.toList(t.getItemJson(), TbBusinessItem.class);
        saveOrUpdate(t);
        createBusinessPeople(t);
        tbBusinessItemService.removeByBusinessId(t.getId());
        BigDecimal price = new BigDecimal(0);
        for (TbBusinessItem item : items) {
            Double num = NumberUtil.parseDouble(item.getNum());
            TbItem tbItem = tbItemService.getById(item.getItemId());
            price = price.add(NumberUtil.mul(num, tbItem.getPrice()));
            TbItemType tbItemType = tbItemTypeService.getById(tbItem.getTypeId());
            item.setBusinessId(t.getId()).setItemCode(tbItem.getItemCode())
                    .setItemName(tbItem.getItemName()).setItemPrice(tbItem.getPrice())
                    .setItemTypeId(tbItem.getTypeId()).setItemTypeName(tbItemType.getName())
                    .setUnit(tbItem.getUnit()).setTotal(NumberUtil.mul(num, tbItem.getPrice()));
        }
        t.setItemPrice(price).setTotalMoney(price);
        this.saveOrUpdate(t);
        tbBusinessItemService.saveBatch(items);

        //增加或修改一条境外车未入场记录
        tbPassRecordService.addOrUpdate(t.getId(), t.getCustomerId(), t.getCustomerName(),
                t.getCardNo(), 1, null, null, t.getCountryName());
        //增加或修改一条中国车未入场记录
        tbPassRecordService.addOrUpdate(t.getId(), t.getCustomerId(), t.getCustomerName(),
                t.getChinaCarNo(), 1, null, null, "中国车");

        return AjaxJson.getSuccess();
    }

    public void storeMsg(String businessCustomerId, String content) {
        String currentCustomerId = StpUserUtil.getCustomerId();
        if (StrUtil.equals(currentCustomerId, UserTypeEnum.PLATFORM_ADMIN.getCustomerId())) {
            BusinessMessageManager.set(businessCustomerId, content);
        } else {
            BusinessMessageManager.set(UserTypeEnum.PLATFORM_ADMIN.getCustomerId(), content);
        }
    }

    private void createBusinessPeople(TbBusiness t) {
        tbBusinessPeopleService.removeByBusinessId(t.getId());
        List<TbBusinessPeople> peopleList = JSONUtil.toList(t.getPeopleJson(), TbBusinessPeople.class);
        peopleList.forEach(tbBusinessPeople -> tbBusinessPeople.setBusinessId(t.getId()).setCreateTime(new Date()));
        tbBusinessPeopleService.saveBatch(peopleList);
    }

    private void createCarUnit(TbBusiness t) {
        TbUnit tbUnit = tbUnitService.findByUnit(t.getCardSize());
        if (tbUnit == null) {
            tbUnit = new TbUnit();
            tbUnit.setUnit(t.getCardSize() + "");
            tbUnitService.save(tbUnit);
        }
    }


    private TbDriver createDriver(TbBusiness business) {
        TbDriver tbDriver = tbDriverService.findByIdCardNo(business.getCardNo());
        if (tbDriver == null) {
            tbDriver = new TbDriver();
            tbDriver.setCreateTime(new Date()).setIdCard(business.getCardNo())
                    .setName(business.getDriverName()).setPhone(business.getDriverPhone());
            tbDriverService.save(tbDriver);
        }
        return tbDriver;

    }

    private TbCar createCar(TbBusiness business) {
        String cardNo = business.getCardNo();
        TbCar tbCar = tbCarService.findByCardNo(cardNo);
        if (tbCar == null) {
            tbCar = new TbCar();
        }
        tbCar.setCardNo(cardNo)
                .setCardSize(business.getCardSize())
                .setCountryName(business.getCountryName())
                .setLastGoodsName(business.getGoodsName())
                .setLastNetWeight(business.getNetWeight());
        tbCarService.saveOrUpdate(tbCar);
        return tbCar;
    }


    /**
     * 查集合 - 根据条件（参数为空时代表忽略指定条件）
     */
    public List<TbBusiness> getList(SoMap so) {

        return tbBusinessMapper.getList(so);
    }


    public void pay(String id, String payTicket) {
        TbBusiness tbBusiness = this.getById(id);
        SpAdmin admin = StpUserUtil.getAdmin();
        tbBusiness.setPayStatus(2).setPayBy(admin.getName())
                .setPayBy(StpUserUtil.getAdmin().getName())
                .setPayTicket(payTicket)
                .setPayTime(new Date());
        if (StrUtil.equals(admin.getCustomerId(), UserTypeEnum.PLATFORM_ADMIN.getCustomerId())) {
            tbBusiness.setAdminConfirmPay(1).setPayStatus(3)
                    .setAdminConfirmPayBy(admin.getName()).setAdminConfirmPayTime(new Date());
        }
        this.updateById(tbBusiness);
        storeMsg(tbBusiness.getCustomerId(), "业务订单【" + tbBusiness.getNo() + "】已支付" + DateUtil.now() + "。");
        //发送消息
        String text = "您的费用已支付，业务单号["+ tbBusiness.getNo() + "]";
        tbNoticesService.sendNotice(tbBusiness.getId(), tbBusiness.getNo(), tbBusiness.getCustomerId(), text);
    }

    public void confirm(List<String> ids) {
        ids.forEach(id -> {
            TbBusiness business = this.getById(id);
            business.setConfirmInput(1).setConfirmInputTime(new Date()).setConfirmInputBy(StpUserUtil.getAdmin().getName());
            this.updateById(business);
            storeMsg(business.getCustomerId(), "业务订单【" + business.getNo() + "】已确认" + DateUtil.now() + "。");
        });
    }

    public void adminConfirmPay(List<String> ids, String ticket) {
        ids.forEach(id -> {
            TbBusiness business = this.getById(id);
            business.setAdminConfirmPayTime(new Date()).setAdminConfirmPay(1).setAdminConfirmPayBy(StpUserUtil.getAdmin().getName())
                    .setPayStatus(3).setPayTicket(ticket);
            this.updateById(business);
            storeMsg(business.getCustomerId(), "业务订单【" + business.getNo() + "】已确认支付" + DateUtil.now() + "。");
            //发送消息
            String text = "您的费用已支付，业务单号["+ business.getNo() + "]";
            tbNoticesService.sendNotice(business.getId(), business.getNo(), business.getCustomerId(), text);
        });
    }

    public TbBusiness findCarTheNewRecord(String carNo, int inOrOut) {
        QueryWrapper<TbBusiness> ew = new QueryWrapper<>();
        ew.eq("card_no", carNo);
        if (inOrOut == 1) {
            ew.eq("admin_confirm_in", 0).isNull("in_channel");
        } else {
            ew.eq("admin_confirm_out", 0).isNull("out_channel").isNotNull("real_in_time");
        }
        return getOne(ew);
    }

    @Deprecated
    public void adminConfirmIn(String id, String inChannel) {
        TbBusiness tbBusiness = this.getById(id);
        tbBusiness.setRealInTime(new Date()).setInChannel(inChannel);
        this.updateById(tbBusiness);

        //更新境外车入场记录
        tbPassRecordService.addOrUpdate(tbBusiness.getId(), tbBusiness.getCustomerId(), tbBusiness.getCustomerName(),
                tbBusiness.getCardNo(), 2, tbBusiness.getRealInTime(), null, tbBusiness.getCountryName());
        //更新中国车入场记录
        tbPassRecordService.addOrUpdate(tbBusiness.getId(), tbBusiness.getCustomerId(), tbBusiness.getCustomerName(),
                tbBusiness.getChinaCarNo(), 2, tbBusiness.getChinaCarInTime(), null, "中国车");
        //发送消息
        String text = "您的车辆已入场，业务单号["+ tbBusiness.getNo() + "]";
        tbNoticesService.sendNotice(tbBusiness.getId(), tbBusiness.getNo(), tbBusiness.getCustomerId(), text);

    }

    public void adminOut(String id, Date outDayTime, String outChannel, String carType) {
        TbBusiness tbBusiness = this.getById(id);
        tbBusiness.setOutDayTime(outDayTime).setOutChannel(outChannel);
        calculationPartMoney(carType, tbBusiness);
        this.updateById(tbBusiness);

        //更新境外车出场记录
        tbPassRecordService.addOrUpdate(tbBusiness.getId(), tbBusiness.getCustomerId(), tbBusiness.getCustomerName(),
                tbBusiness.getCardNo(), 3,
                tbBusiness.getRealInTime(), tbBusiness.getOutDayTime(), tbBusiness.getCountryName());
        //更新中国车出场记录
        tbPassRecordService.addOrUpdate(tbBusiness.getId(), tbBusiness.getCustomerId(), tbBusiness.getCustomerName(),
                tbBusiness.getChinaCarNo(), 3,
                tbBusiness.getChinaCarInTime(), tbBusiness.getChinaCarOutTime(), "中国车");
        //发送消息
        String text = "您的车辆已离场，业务单号["+ tbBusiness.getNo() + "]";
        tbNoticesService.sendNotice(tbBusiness.getId(), tbBusiness.getNo(), tbBusiness.getCustomerId(), text);

    }

    @Async
    public void calculationPartMoney(String itemType, TbBusiness tbBusiness) {
        Date iTime = tbBusiness.getRealInTime();
        Date oTime = tbBusiness.getOutDayTime();
        if (itemType.contains("中国")) {
            iTime = tbBusiness.getChinaCarInTime();
            oTime = tbBusiness.getChinaCarOutTime();
        }
        LocalDateTime inDayTime = iTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        LocalDateTime outDayTime = oTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        long minutes = ChronoUnit.MINUTES.between(inDayTime, outDayTime);
        if (minutes < 0) {
            return;
        }
        double carSize = tbBusiness.getCardSize();
        if (carSize < partConfig.getFreeCarLength() || minutes <= partConfig.getFreeMinutes()) {
            return;
        }
        long days = ChronoUnit.DAYS.between(inDayTime.toLocalDate(), outDayTime.toLocalDate());
        long hour = ChronoUnit.HOURS.between(inDayTime, outDayTime);
        BigDecimal basePrice = partConfig.getBasePrice();
        BigDecimal extraPrice = partConfig.getExtraPrice();
        BigDecimal price = basePrice.add(basePrice.multiply(new BigDecimal(hour / 24))).add(new BigDecimal(days).multiply(extraPrice));
        if (itemType.contains("中国")) {
            tbBusiness.setChinaPartMoney(price).setChinaCarPartTime(minutes);
        } else {
            tbBusiness.setPartMoney(price).setPartTime(minutes);
        }
        tbBusiness.setTotalMoney(tbBusiness.getItemPrice().add(tbBusiness.getChinaPartMoney()).add(tbBusiness.getPartMoney()));
    }

    /**
     * @param carNo
     * @param inOrOut 1入 2出
     * @return
     */
    public TbBusiness findByChinaCarNo(String carNo, int inOrOut) {
        QueryWrapper<TbBusiness> ew = new QueryWrapper<>();
        ew.eq("china_car_no", carNo);
        if (inOrOut == 1) {
            ew.eq("admin_confirm_in", 0).isNull("china_car_in_channel");
        } else {
            ew.eq("admin_confirm_out", 0)
                    .isNull("china_car_out_channel")
                    .isNotNull("china_car_in_time");
        }
        return this.getOne(ew);
    }


}
