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.winsea.svc.base.base.entity.CommonStaff;
import com.winsea.svc.base.base.service.ICommonStaffService;
import com.winsea.svc.base.security.util.AuthSecurityUtils;
import com.winsea.svc.notice.entity.NoticeTaskInfo;
import com.winsea.svc.notice.entity.base.BaseNotice;
import com.winsea.svc.notice.service.INoticeService;
import com.winsea.svc.notice.service.INoticeTaskService;
import com.yh.saas.common.support.util.IdGenerator;
import com.yh.saas.plugin.yiliangyiyun.constant.StatusEnum;
import com.yh.saas.plugin.yiliangyiyun.entity.*;
import com.yh.saas.plugin.yiliangyiyun.mapper.CollectionManagementMapper;
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.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 收款管理 服务实现类
 * </p>
 *
 * @author Gongdc
 * @since 2021-08-06
 */
@Service
public class CollectionManagementServiceImpl extends ServiceImpl<CollectionManagementMapper, CollectionManagement> implements ICollectionManagementService {
    @Autowired
    private IWarehouseInOutInfoService warehouseInOutInfoService;
    @Autowired
    private ISalePlanInfoService salePlanInfoService;
    @Autowired
    private ISalesDeliveryReportService salesDeliveryReportService;
    @Autowired
    private INoticeService noticeService;
    @Autowired
    private INoticeTaskService noticeTaskService;
    @Autowired
    private ICommonStaffService staffService;
    /**
     * 收款列表查询
     * @param collectionManagement
     * @return
     */
    @Override
    public Page<CollectionManagement> selectCollectionInfo(CollectionManagement collectionManagement) {
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("startRecord", (collectionManagement.getCurrentPage() - 1)
                * collectionManagement.getPageSize());
        //  公司ID
        pageView.put("compId", collectionManagement.getCompId());
        pageView.put("searchKeyWord", collectionManagement.getSearchKeyWord());
        pageView.put("searchType", collectionManagement.getSearchType());
        pageView.put("pageSize", collectionManagement.getPageSize());
        pageView.put("currentPage", collectionManagement.getCurrentPage());
        // 查询总数
        Integer dataCount = baseMapper.getCountByCondition(pageView);
        List<CollectionManagement> dataList = baseMapper.getListByCondition(pageView);
        if (!CollectionUtils.isEmpty(dataList)){
            for (CollectionManagement collectionManagement1:dataList){
                //定义出库量
                Float outWeight = 0.0f;
                List<SalesDeliveryReport> salesDeliveryReportList=salesDeliveryReportService.selectList(new EntityWrapper<SalesDeliveryReport>()
                .eq("contract_no",collectionManagement1.getContractNo()).eq("delete_flag","0"));
                if (!CollectionUtils.isEmpty(salesDeliveryReportList)){
                    for (SalesDeliveryReport salesDeliveryReport:salesDeliveryReportList){
                        outWeight = outWeight + Float.valueOf(salesDeliveryReport.getNetWeight());
                    }
                }
                collectionManagement1.setOutWeight(outWeight);
            }
        }
        Page<CollectionManagement> page = new Page<>();
        page.setRecords(dataList == null ? Lists.newArrayList() : dataList);
        page.setTotal(dataCount == null ? 0 : dataCount);
        page.setCurrent(collectionManagement.getCurrentPage());
        page.setSize(collectionManagement.getPageSize());
        return page;
    }

    /**
     * 派发
     * @param collectionManagement
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String distribute(CollectionManagement collectionManagement) {
        //生成出库任务
        WarehouseInOutInfo warehouseInOutInfo = new WarehouseInOutInfo();
        warehouseInOutInfo.setId(IdGenerator.generateUUID());
        warehouseInOutInfo.setStatus(StatusEnum.TEMPORARILY_STORED.getName());
        warehouseInOutInfo.setStatusFlag(StatusEnum.TEMPORARILY_STORED.getFlag());
        warehouseInOutInfo.setTranCarNo(collectionManagement.getTranCarNo());
        warehouseInOutInfo.setCarNo(collectionManagement.getCarNo());
        warehouseInOutInfo.setBoxNo(collectionManagement.getBoxNo());
        warehouseInOutInfo.setTitleNo(collectionManagement.getTitleNo());
        warehouseInOutInfo.setAgent(collectionManagement.getAgent());
        warehouseInOutInfo.setCommonId(collectionManagement.getStaffId());
        //收货方
        warehouseInOutInfo.setConsignee(collectionManagement.getBuyer());
        warehouseInOutInfo.setTaskType("出库任务");
        warehouseInOutInfo.setInOutFlag("1");
        //查询销售计划的出货库
        SalePlanInfo salePlanInfo = salePlanInfoService.selectById(collectionManagement.getPlanId());
        if (salePlanInfo != null) {
            //设置默认出库仓库
            warehouseInOutInfo.setWarehouseName(salePlanInfo.getSendWarehouse());
        }
        warehouseInOutInfo.setContractNo(collectionManagement.getContractNo());
        warehouseInOutInfo.setGoodsName(collectionManagement.getGoodsName());
        warehouseInOutInfoService.insert(warehouseInOutInfo);

        tesk(warehouseInOutInfo,"1");
        return "ok";
    }

    /**
     * 删除
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteCar(String id){
        WarehouseInOutInfo warehouseInOutInfo = warehouseInOutInfoService.selectById(id);
        warehouseInOutInfoService.deleteById(warehouseInOutInfo.getId());
    }

    /**
     * 编辑
     * @param collectionManagement
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String editInfo(CollectionManagement collectionManagement) {
        //未收>0
        if (collectionManagement.getCollectionIngPayable()!=null&&collectionManagement.getCollectionEdPayable()!=null&&collectionManagement.getCollectionIngPayable()-collectionManagement.getCollectionEdPayable()>0){
            collectionManagement.setStatus(StatusEnum.NOT_COLLECTION.getName());
            collectionManagement.setStatusFlag(StatusEnum.NOT_COLLECTION.getFlag());
        }
        else if(collectionManagement.getCollectionIngPayable()!=null&&collectionManagement.getCollectionEdPayable()!=null) {
            collectionManagement.setStatus(StatusEnum.COLLECTION.getName());
            collectionManagement.setStatusFlag(StatusEnum.COLLECTION.getFlag());
        }
        boolean one = this.updateById(collectionManagement);
        if (one ) {
            return "OK";
        } else {
            return "NG";
        }
    }

    /**
     * 查看
     * @param id
     */
    @Override
    public CollectionManagement getInfo(String id) {
        CollectionManagement collectionManagement = this.selectById(id);
        return collectionManagement;
    }



    /**
     * 任务
     *
     * @param warehouseInOutInfo
     */
    private void tesk(WarehouseInOutInfo warehouseInOutInfo, String flag) {
        // 先删除任务
        noticeService.removeNotice(BaseNotice.NoticeStatus.TASK, "INOUTTASK-TASK-APPROVE",
                warehouseInOutInfo.getId(), null);
        String staffName = "XXX";
        CommonStaff commitUserInfo = staffService.getInfo(AuthSecurityUtils.getCurrentUserId());
        if (commitUserInfo != null) {
            staffName = commitUserInfo.getMajorRole() != null
                    ? commitUserInfo.getMajorRole().getRoleName() + " " + commitUserInfo.getStaffName()
                    : commitUserInfo.getStaffName();
        }
        String taskContent = "";
        // 向下一步操作人发送任务通知
        if ("1".equals(flag)) {
            taskContent = "您的合同(" + warehouseInOutInfo.getContractNo() + ")车辆：" + warehouseInOutInfo.getCarNo() + "已发出";
        } else {
            taskContent = "您的合同(" + warehouseInOutInfo.getContractNo() + ")车辆：" + warehouseInOutInfo.getCarNo() + "申请卸货，请及时确认";

        }
        NoticeTaskInfo taskInfo = new NoticeTaskInfo();
        taskInfo.setCompId(commitUserInfo.getCompId());
        taskInfo.setAcceptType(BaseNotice.AcceptStatus.STAFF);
        taskInfo.setBusinessId(warehouseInOutInfo.getId());
        taskInfo.setBusinessType("WAREHOUSE");
        taskInfo.setMessageContent(taskContent);
        taskInfo.setBusinessCode("INOUTTASK-TASK-APPROVE");
//            taskInfo.setNoticeTaskStatus(NoticeTaskInfo.NoticeTaskStatus.RETURN);
        noticeTaskService.createNoticeTask(Lists.newArrayList(warehouseInOutInfo.getCommonId()),
                null, taskInfo);

    }
}
