package com.yh.saas.plugin.yiliangyiyun.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.yh.saas.common.support.util.IdGenerator;
import com.yh.saas.plugin.yiliangyiyun.constant.NumberConstant;
import com.yh.saas.plugin.yiliangyiyun.entity.*;
import com.yh.saas.plugin.yiliangyiyun.mapper.FreightReceivingDispatchingMapper;
import com.yh.saas.plugin.yiliangyiyun.service.*;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 货运收发信息 服务实现类
 * </p>
 *
 * @author Gongdc
 * @since 2021-08-19
 */
@Service
public class FreightReceivingDispatchingServiceImpl extends ServiceImpl<FreightReceivingDispatchingMapper, FreightReceivingDispatching> implements IFreightReceivingDispatchingService {

    @Autowired
    private IFreightReceivingDispatchingCarService freightReceivingDispatchingCarService;
    @Autowired
    private IReceivingUserService receivingUserService;
    @Autowired
    private IIdentityAuthenticationInfoService iIdentityAuthenticationInfoService;


    /**
     * 货运收发列表
     *
     * @param freightReceivingDispatching
     * @return
     */
    @Override
    public Page<FreightReceivingDispatching> selectFreightReceivingDispatchingPage(FreightReceivingDispatching freightReceivingDispatching) {
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("startRecord", (freightReceivingDispatching.getCurrentPage() - 1)
                * freightReceivingDispatching.getPageSize());
        List<String> idList = new ArrayList<>();
        List<ReceivingUser> receivingUsers = receivingUserService.selectList(new EntityWrapper<ReceivingUser>()
                .eq("receive_phone", freightReceivingDispatching.getAccountNumber()));
        for (ReceivingUser receivingUser : receivingUsers) {
            idList.add(receivingUser.getInfoId());
        }
        //公司id
        pageView.put("compId", freightReceivingDispatching.getCompId());
        pageView.put("searchType", freightReceivingDispatching.getSearchType());
        pageView.put("searchKeyWord", freightReceivingDispatching.getSearchKeyWord());
        pageView.put("accountNumber", freightReceivingDispatching.getAccountNumber());
        pageView.put("idList", idList);
        pageView.put("pageSize", freightReceivingDispatching.getPageSize());
        pageView.put("currentPage", freightReceivingDispatching.getCurrentPage());
        // 查询总数
        Integer dataCount = baseMapper.getCountByCondition(pageView);
        List<FreightReceivingDispatching> dataList = baseMapper.getListByCondition(pageView);
        Page<FreightReceivingDispatching> page = new Page<>();
        page.setRecords(dataList == null ? Lists.newArrayList() : dataList);
        page.setTotal(dataCount == null ? 0 : dataCount);
        page.setCurrent(freightReceivingDispatching.getCurrentPage());
        page.setSize(freightReceivingDispatching.getPageSize());
        return page;
    }


    /**
     * 删除信息
     *
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteFreightReceivingDispatching(String id) {
        //删除司机信息
        FreightReceivingDispatching freightReceivingDispatching = this.selectById(id);
        this.deleteById(freightReceivingDispatching.getId());
        //删除详细信息
        List<FreightReceivingDispatchingCar> freightReceivingDispatchingCars = freightReceivingDispatchingCarService.selectList(new EntityWrapper<FreightReceivingDispatchingCar>()
                .eq("batch", freightReceivingDispatching.getBatch()));
        if (!CollectionUtils.isEmpty(freightReceivingDispatchingCars)) {
            for (FreightReceivingDispatchingCar freightReceivingDispatchingCar : freightReceivingDispatchingCars) {
                freightReceivingDispatchingCarService.deleteById(freightReceivingDispatchingCar.getId());
            }
        }
        //删除收货人信息
        List<ReceivingUser> receivingUsers = receivingUserService.selectList(new EntityWrapper<ReceivingUser>()
                .eq("info_id", id));
        if (!CollectionUtils.isEmpty(receivingUsers)) {
            for (ReceivingUser receivingUser : receivingUsers) {
                receivingUserService.deleteById(receivingUser.getId());
            }
        }
    }

    /**
     * 添加
     *
     * @param freightReceivingDispatching
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String insertFreightReceivingDispatching(FreightReceivingDispatching freightReceivingDispatching) {
        String batch = IdGenerator.generateUUID();
        freightReceivingDispatching.setId(IdGenerator.generateUUID());
        freightReceivingDispatching.setStatusFlag("1");
        freightReceivingDispatching.setStatus("发货");
        freightReceivingDispatching.setBatch(batch);
        this.insert(freightReceivingDispatching);
//        freightReceivingDispatching.setId(IdGenerator.generateUUID());
//        freightReceivingDispatching.setStatusFlag("2");
//        freightReceivingDispatching.setStatus("收货");
////        IdentityAuthenticationInfo identityAuthenticationInfo=iIdentityAuthenticationInfoService.selectOne(new EntityWrapper<>()
////        .eq("cover","0")
////        .eq(""))
//        freightReceivingDispatching.setBatch(batch);
//        this.insert(freightReceivingDispatching);
        return freightReceivingDispatching.getId();
    }


    /**
     * 添加发车信息
     *
     * @param freightReceivingDispatchingCar
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String insertFreightReceivingDispatchingCar(FreightReceivingDispatchingCar freightReceivingDispatchingCar) {
        freightReceivingDispatchingCar.setId(IdGenerator.generateUUID());
        freightReceivingDispatchingCar.setStatusFlag("1");
        freightReceivingDispatchingCar.setStatus("待签收");
//        List<FreightReceivingDispatching> freightReceivingDispatchingList = this.selectList(new EntityWrapper<FreightReceivingDispatching>()
//                .eq("batch", freightReceivingDispatchingCar.getBatch())
//                .eq("delete_flag", "0"));
//        if (!CollectionUtils.isEmpty(freightReceivingDispatchingList)) {
//            for (FreightReceivingDispatching freightReceivingDispatching : freightReceivingDispatchingList) {
//                freightReceivingDispatching.setSignedFor(String.valueOf(Float.valueOf(freightReceivingDispatching.getSignedFor()) + 1));
//                this.updateById(freightReceivingDispatching);
//            }
//            freightReceivingDispatchingCar.setGoodsIngPayable(freightReceivingDispatchingCar.getReciveNetWeight() * freightReceivingDispatchingList.get(0).getGoodsPrice());
//            freightReceivingDispatchingCar.setFreightIngPayable(freightReceivingDispatchingCar.getReciveNetWeight() * freightReceivingDispatchingList.get(0).getFreightUnitPrice());
//        }
        FreightReceivingDispatching freightReceivingDispatching = this.selectOne(new EntityWrapper<FreightReceivingDispatching>()
                .eq("batch", freightReceivingDispatchingCar.getBatch())
                .eq("delete_flag", "0"));
        if (freightReceivingDispatching != null) {
            freightReceivingDispatching.setSignedFor(String.valueOf(Float.valueOf(freightReceivingDispatching.getSignedFor()) + 1));
            freightReceivingDispatchingCar.setGoodsIngPayable(freightReceivingDispatchingCar.getReciveNetWeight() * freightReceivingDispatching.getGoodsPrice());
            freightReceivingDispatchingCar.setFreightIngPayable(freightReceivingDispatchingCar.getReciveNetWeight() * freightReceivingDispatching.getFreightUnitPrice());
            this.updateById(freightReceivingDispatching);
        }
        freightReceivingDispatchingCarService.insert(freightReceivingDispatchingCar);
        return freightReceivingDispatchingCar.getId();
    }


    /**
     * 付扣运费款
     *
     * @param freightReceivingDispatchingCar
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String paymentAndDeductionfreight(FreightReceivingDispatchingCar freightReceivingDispatchingCar) {
        FreightReceivingDispatchingCar freightReceivingDispatchingCar1 = freightReceivingDispatchingCarService.selectById(freightReceivingDispatchingCar.getId());
        if ("0".equals(freightReceivingDispatchingCar.getFlag())) {
            freightReceivingDispatchingCar1.setFreightIngPayable(freightReceivingDispatchingCar1.getFreightIngPayable() - freightReceivingDispatchingCar.getFreightDeductionAmount());
            freightReceivingDispatchingCar1.setFreightDeductionAmount(freightReceivingDispatchingCar1.getFreightDeductionAmount() + freightReceivingDispatchingCar.getFreightDeductionAmount());
        } else {
            freightReceivingDispatchingCar1.setFreightIngPayable(freightReceivingDispatchingCar.getFreightIngPayable());
            // 付款金额 用已付这个字段  然后累加
            freightReceivingDispatchingCar1.setFreightEdPayable(freightReceivingDispatchingCar1.getFreightEdPayable() + freightReceivingDispatchingCar.getMoney());
        }
        freightReceivingDispatchingCarService.updateById(freightReceivingDispatchingCar1);
        return freightReceivingDispatchingCar.getId();
    }


    /**
     * 付扣货款
     *
     * @param freightReceivingDispatchingCar
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String PaymentDeduction(FreightReceivingDispatchingCar freightReceivingDispatchingCar) {
        FreightReceivingDispatchingCar freightReceivingDispatchingCar1 = freightReceivingDispatchingCarService.selectById(freightReceivingDispatchingCar.getId());
        freightReceivingDispatchingCar1.setGoodsIngPayable(freightReceivingDispatchingCar.getGoodsIngPayable());
        // 付款金额 用已付这个字段  然后累加
        freightReceivingDispatchingCar1.setGoodsEdPayable(freightReceivingDispatchingCar1.getGoodsEdPayable() + freightReceivingDispatchingCar.getGoodsEdPayable());
        freightReceivingDispatchingCar1.setGoodsDeductionAmount(freightReceivingDispatchingCar1.getGoodsDeductionAmount() + freightReceivingDispatchingCar.getGoodsDeductionAmount());
        if (freightReceivingDispatchingCar1.getGoodsIngPayable().equals(freightReceivingDispatchingCar1.getGoodsEdPayable())) {
            freightReceivingDispatchingCar1.setStatusFlag("5");
            freightReceivingDispatchingCar1.setStatus("已完成");
        }
        List<FreightReceivingDispatching> freightReceivingDispatchingList = this.selectList(new EntityWrapper<FreightReceivingDispatching>()
                .eq("batch", freightReceivingDispatchingCar.getBatch())
                .eq("delete_flag", "0"));
        if (!CollectionUtils.isEmpty(freightReceivingDispatchingList)) {
            for (FreightReceivingDispatching freightReceivingDispatching : freightReceivingDispatchingList) {
                freightReceivingDispatching.setToSettled(String.valueOf(Float.valueOf(freightReceivingDispatching.getToSettled()) - 1));
                this.updateById(freightReceivingDispatching);
            }
        }
//        FreightReceivingDispatching freightReceivingDispatching = this.selectById(freightReceivingDispatchingCar.getInfoId());
//        if (freightReceivingDispatching != null) {
//            freightReceivingDispatching.setToSettled(String.valueOf(Integer.valueOf(freightReceivingDispatching.getToSettled()) - 1));
//            this.updateById(freightReceivingDispatching);
//        }
        freightReceivingDispatchingCarService.updateById(freightReceivingDispatchingCar1);
        return freightReceivingDispatchingCar.getId();
    }

    /**
     * 确认收货
     *
     * @param freightReceivingDispatchingCar
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String confirmFreightReceivingDispatchingCar(FreightReceivingDispatchingCar freightReceivingDispatchingCar) {
        FreightReceivingDispatchingCar freightReceivingDispatchingCar1 = freightReceivingDispatchingCarService.selectById(freightReceivingDispatchingCar.getId());
        freightReceivingDispatchingCar1.setStatusFlag("3");
        freightReceivingDispatchingCar1.setStatus("待结算");
        freightReceivingDispatchingCar1.setReciveCollectionScreenshot(freightReceivingDispatchingCar.getReciveCollectionScreenshot());
        List<FreightReceivingDispatching> freightReceivingDispatchingList = this.selectList(new EntityWrapper<FreightReceivingDispatching>()
                .eq("batch", freightReceivingDispatchingCar.getBatch())
                .eq("delete_flag", "0"));
        if (!CollectionUtils.isEmpty(freightReceivingDispatchingList)) {
            for (FreightReceivingDispatching freightReceivingDispatching : freightReceivingDispatchingList) {
                freightReceivingDispatching.setToSettled(String.valueOf(Float.valueOf(freightReceivingDispatching.getToSettled()) + 1));
                freightReceivingDispatching.setSignedFor(String.valueOf(Float.valueOf(freightReceivingDispatching.getSignedFor()) - 1));
                this.updateById(freightReceivingDispatching);
            }
            //发货净重小
            if (freightReceivingDispatchingCar1.getReciveNetWeight() < freightReceivingDispatchingCar.getDispatchNetWeight()) {
                freightReceivingDispatchingCar1.setGoodsIngPayable(freightReceivingDispatchingCar1.getReciveNetWeight() * freightReceivingDispatchingList.get(0).getGoodsPrice());
                freightReceivingDispatchingCar1.setFreightIngPayable(freightReceivingDispatchingCar1.getReciveNetWeight() * freightReceivingDispatchingList.get(0).getFreightUnitPrice() - freightReceivingDispatchingCar.getFreightDeductionAmount());
            } else {
                freightReceivingDispatchingCar1.setGoodsIngPayable(freightReceivingDispatchingCar.getDispatchNetWeight() * freightReceivingDispatchingList.get(0).getGoodsPrice());
                freightReceivingDispatchingCar1.setFreightIngPayable(freightReceivingDispatchingCar.getDispatchNetWeight() * freightReceivingDispatchingList.get(0).getFreightUnitPrice() - freightReceivingDispatchingCar.getFreightDeductionAmount());

            }
        }
//        FreightReceivingDispatching freightReceivingDispatching = this.selectById(freightReceivingDispatchingCar.getInfoId());
//        if (freightReceivingDispatching != null) {
//            freightReceivingDispatching.setToSettled(String.valueOf(Integer.valueOf(freightReceivingDispatching.getToSettled()) + 1));
//            freightReceivingDispatching.setStatusFlag("2");
//            freightReceivingDispatching.setStatus("收货");
//            this.updateById(freightReceivingDispatching);
//        }
        freightReceivingDispatchingCarService.updateById(freightReceivingDispatchingCar1);
        return freightReceivingDispatchingCar1.getId();
    }

    /**
     * 添加收货人
     *
     * @param receivingUser
     * @return
     */
    @Override
    public String insertReceivingUser(ReceivingUser receivingUser) {
        receivingUser.setId(IdGenerator.generateUUID());
        receivingUserService.insert(receivingUser);
        return receivingUser.getInfoId();
    }


    /**
     * 查看详情
     *
     * @param id
     * @return
     */
    @Override
    public FreightReceivingDispatching getFreightReceivingDispatching(String id) {
        //查看信息
        FreightReceivingDispatching freightReceivingDispatching = this.selectById(id);
        // 查看详情
        List<FreightReceivingDispatchingCar> freightReceivingDispatchingCars = freightReceivingDispatchingCarService.selectList(new EntityWrapper<FreightReceivingDispatchingCar>()
                .eq("batch", freightReceivingDispatching.getBatch())
                .eq("delete_flag", "0"));
        if (!CollectionUtils.isEmpty(freightReceivingDispatchingCars)) {
            freightReceivingDispatching.setFreightReceivingDispatchingCars(freightReceivingDispatchingCars);
        }
        List<ReceivingUser> receivingUsers = receivingUserService.selectList(new EntityWrapper<ReceivingUser>()
                .eq("info_id", id)
                .eq("delete_flag", "0"));
        if (!CollectionUtils.isEmpty(receivingUsers)) {
            freightReceivingDispatching.setReceivingUsers(receivingUsers);
        }
        return freightReceivingDispatching;
    }
}

