package com.pj.project.tb_business;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;

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.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_pass_record.TbPassRecord;
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.project4sp.role.SpRoleUtil;
import com.pj.project4sp.role4permission.SpRolePermissionService;
import com.pj.utils.so.SoMap;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.pj.utils.sg.*;

import javax.annotation.Resource;

/**
 * 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 TbPassRecordService tbPassRecordService;


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

    /**
     * 增
     */
    public AjaxJson addOrUpdate(TbBusiness t) {
        if (checkCarNo(t.getCardNo()) != null) {
            return AjaxJson.getError("该车辆【" + t.getCardNo() + "】有未完成业务");
        }

        t.setCreateBy(StpUserUtil.getAdmin().getName());
        createCar(t);
        createCarUnit(t);
        TbDriver tbDriver = createDriver(t);
        t.setDriverId(tbDriver.getId());
        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.getNo())) {
            t.setNo(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmm")) + RandomUtil.randomNumbers(4));
        }
        List<TbBusinessItem> items = JSONUtil.toList(t.getItemJson(), TbBusinessItem.class);
        if (StrUtil.isEmpty(t.getId())) {
            t.setCreateTime(new Date());
        }
        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);

        //增加一条放行记录
//        TbPassRecord record = new TbPassRecord();
//        record.setBusinessId(t.getId()).setCustomerId(t.getCustomerId())
//                .setCardNo(t.getCardNo()).setCustomerName(t.getCustomerName())
//                .setStatus(1).setUpdateTime(new Date());
//        tbPassRecordService.saveOrUpdate(record);

        return AjaxJson.getSuccess();
    }

    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);
    }

    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);
        });
    }

    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);
        });
    }

    public TbBusiness findCarTheNewRecord(String carNo) {
        QueryWrapper<TbBusiness> ew = new QueryWrapper<>();
        ew.eq("card_no", carNo);
        ew.orderByDesc("id");
        List<TbBusiness> list = this.list(ew);
        return list.isEmpty() ? null : list.get(0);
    }

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

        //更新放行记录
        TbPassRecord record = tbPassRecordService.getByBusinessId(tbBusiness.getId());
        record.setStatus(2).setInTime(tbBusiness.getRealInTime()).setUpdateTime(new Date());
        tbPassRecordService.saveOrUpdate(record);
    }

    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);

        //更新放行记录
        TbPassRecord record = tbPassRecordService.getByBusinessId(tbBusiness.getId());
        record.setStatus(3).setOutTime(tbBusiness.getOutDayTime()).setUpdateTime(new Date());
        tbPassRecordService.saveOrUpdate(record);

    }

    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;
        }
        String businessId = tbBusiness.getId();
//        TbBusinessItem businessItem = tbBusinessItemService.findByBusinessIdAndTypeName(businessId, itemType);
//        if (businessItem == null) {
//            businessItem = new TbBusinessItem();
//        }
        LocalTime zero = LocalTime.of(0, 0, 0);
        long days = ChronoUnit.DAYS.between(inDayTime.toLocalDate(), outDayTime.toLocalDate());
        BigDecimal basePrice = partConfig.getBasePrice();
        BigDecimal extraPrice = partConfig.getExtraPrice();
        BigDecimal price = basePrice;
        LocalTime outTime = outDayTime.toLocalTime();
        LocalTime nigthEnd = LocalTime.parse(partConfig.getNightEnd(), DateTimeFormatter.ofPattern("HH:mm:ss"));
        if (days >= 1) {
            price = basePrice.add(basePrice.multiply(new BigDecimal(days - 1)));
            if (outTime.isAfter(nigthEnd)){
                price = basePrice.add(basePrice.multiply(new BigDecimal(days)));
            }
            if (outTime.isAfter(zero)&&outTime.isBefore(nigthEnd)){
                price=price.add(extraPrice);
            }
        }
        long hour = ChronoUnit.HOURS.between(zero, outTime);
        if (days == 0) {
            hour = ChronoUnit.HOURS.between(inDayTime, outDayTime);
        }
        String num = days + "天" + hour + "小时";
        if (hour == 0) {
            num = minutes + "分钟";
        }

//        businessItem.setTotal(price).setUnit("天").setItemTypeName(itemType).setItemPrice(partConfig.getBasePrice())
//                .setBusinessId(businessId).setItemName("停车费").setNum(num);
//        tbBusinessItemService.saveOrUpdate(businessItem);
        if (itemType.contains("中国")) {
            tbBusiness.setChinaPartMoney(price).setChinaCarPartTime(minutes);
        } else {
            tbBusiness.setPartMoney(price).setPartTime(minutes);
            ;
        }
        tbBusiness.setTotalMoney(tbBusiness.getItemPrice().add(tbBusiness.getChinaPartMoney()).add(tbBusiness.getPartMoney()));
    }

    public TbBusiness findByChinaCarNo(String carNo) {
        QueryWrapper<TbBusiness> ew = new QueryWrapper<>();
        ew.eq("china_car_no", carNo);
        ew.orderByDesc("id");
        List<TbBusiness> list = this.list(ew);
        return list.isEmpty() ? null : list.get(0);
    }


}
