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

import com.baomidou.mybatisplus.mapper.EntityWrapper;
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.base.workflow.entity.Workflow;
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.common.support.util.StringUtils;
import com.yh.saas.plugin.base.service.ICommonBillOperateHisService;
import com.yh.saas.plugin.yiliangyiyun.constant.NumberConstant;
import com.yh.saas.plugin.yiliangyiyun.constant.StatusEnum;
import com.yh.saas.plugin.yiliangyiyun.entity.*;
import com.yh.saas.plugin.yiliangyiyun.exception.*;
import com.yh.saas.plugin.yiliangyiyun.mapper.TranCarInfoMapper;
import com.yh.saas.plugin.yiliangyiyun.service.*;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yh.saas.plugin.yiliangyiyun.util.GeTuiUtils;
import com.yh.saas.plugin.yiliangyiyun.util.WebSocket;
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.Date;
import java.util.List;

/**
 * <p>
 * 记录车次 服务实现类
 * </p>
 *
 * @author Gongdc
 * @since 2021-05-31
 */
@Service
public class TranCarInfoServiceImpl extends ServiceImpl<TranCarInfoMapper, TranCarInfo> implements ITranCarInfoService {

    @Autowired
    private ICommonBillOperateHisService billOperateHisService;
    @Autowired
    private IDriverViewInfoService driverViewInfoService;
    @Autowired
    private IWarehouseInOutInfoService warehouseInOutInfoService;
    @Autowired
    private IWarehouseBaseInfoService warehouseBaseInfoService;
    @Autowired
    private ICommonUserService commonUserService;
    @Autowired
    private IProcurementPlanInfoService procurementPlanInfoService;
    @Autowired
    private IPurchaseReceiptReportService purchaseReceiptReportService;
    @Autowired
    private ISalesDeliveryReportService salesDeliveryReportService;
    @Autowired
    private ITranSettlementReportService tranSettlementReportService;
    @Autowired
    private IDriverPayeeInfoService driverPayeeInfoService;
    @Autowired
    private ITranProcessInfoService tranProcessInfoService;
    @Autowired
    private ITranTaskInfoService tranTaskInfoService;
    @Autowired
    private INewWorkflowService workflowService;
    @Autowired
    private GeTuiUtils geTuiUtils;
    @Autowired
    private INoticeService noticeService;
    @Autowired
    private INoticeTaskService noticeTaskService;
    @Autowired
    private ICommonStaffService staffService;
    @Autowired
    private WebSocket webSocket;

    /**
     * 添加发车信息
     *
     * @param tranCarInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addTranCar(TranCarInfo tranCarInfo) throws ServiceException {
        //新增主键id
        tranCarInfo.setId(IdGenerator.generateUUID());
        tranCarInfo.setCompId(AuthSecurityUtils.getCurrentUserInfo().getCompId());
        tranCarInfo.setStatus(StatusEnum.NOT_DELIVERED.getName());
        tranCarInfo.setStatusFlag(StatusEnum.NOT_DELIVERED.getFlag());
        tranCarInfo.setConfirmFlag(StatusEnum.NOT_CONFIRM.getFlag());
        //根据手机号判断司机是否认证
        DriverViewInfo driverViewInfo =
                driverViewInfoService.selectOne(new EntityWrapper<DriverViewInfo>()
                        .eq(DriverViewInfo.QueryFiles.DRIVER_PHONE, tranCarInfo.getDriverPhone())
                        .eq(DriverViewInfo.QueryFiles.DELETE_FLAG, NumberConstant.CONSTANT0));
        if (driverViewInfo == null) {
            throw new AppServiceException(ExceptionDefinition.DRIVER_NOT_CERTIFIED);
        }
        //发车时生成入库任务
        WarehouseInOutInfo warehouseInOutInfo = new WarehouseInOutInfo();
        warehouseInOutInfo.setId(IdGenerator.generateUUID());
        warehouseInOutInfo.setStatus(StatusEnum.TEMPORARILY_STORED.getName());
        warehouseInOutInfo.setStatusFlag(StatusEnum.TEMPORARILY_STORED.getFlag());
        warehouseInOutInfo.setTranCarNo(tranCarInfo.getTranCarNo());
        warehouseInOutInfo.setCarNo(tranCarInfo.getCarNo());
        warehouseInOutInfo.setTaskType("入库任务");
        warehouseInOutInfo.setInOutFlag("2");
        //查询采购计划的收货库
        ProcurementPlanInfo procurementPlanInfo = procurementPlanInfoService.selectById(tranCarInfo.getPlanId());
        if (procurementPlanInfo != null) {
            //设置默认入库仓库
            warehouseInOutInfo.setWarehouseName(procurementPlanInfo.getReceiveWarehouse());
        }
        warehouseInOutInfo.setContractNo(tranCarInfo.getContractNo());
        warehouseInOutInfo.setGoodsName(tranCarInfo.getGoodsName());
        warehouseInOutInfo.setStartWeight(tranCarInfo.getLoadNetWeight());

        List<WarehouseBaseInfo> listTmo = warehouseBaseInfoService.selectList(new EntityWrapper<WarehouseBaseInfo>().eq("warehouse_name", warehouseInOutInfo.getWarehouseName()));
        if (listTmo.size() > 0) {
            WarehouseBaseInfo warehouseBaseInfo = listTmo.get(0);
            warehouseInOutInfo.setAgent(warehouseBaseInfo.getPersonCharge());
            warehouseInOutInfo.setCommonId(warehouseBaseInfo.getPersonChargeKey());
            List<CommonUser> tmp = commonUserService.selectList(new EntityWrapper<CommonUser>().eq("phone", warehouseBaseInfo.getPersonPhone()));
            if (tmp.size() > 0) {
                geTuiUtils.pushByCid("入库任务", "您有新的入库任务待完成，车牌号：" + warehouseInOutInfo.getCarNo(), tmp.get(0).getId());

                tesk(warehouseInOutInfo, "2");

                UnimallMessage messageDO = new UnimallMessage();
                messageDO.setAdminId(tmp.get(0).getId());
                messageDO.setCustomer(tmp.get(0).getUserName());
                messageDO.setOperation("入库任务");
                messageDO.setResult("您有新的入库任务待完成，车牌号：" + warehouseInOutInfo.getCarNo());
                messageDO.setGmtUpdate(new java.util.Date());
                messageDO.setGmtCreate(new Date());
                messageDO.setTaskId(IdGenerator.generateUUID());
                messageDO.setCompanyId(AuthSecurityUtils.getCurrentUserInfo().getCompId());
                messageDO.setPath("XXXXX");
                webSocket.sendOneMessage(messageDO);
            }
        }
        boolean two = warehouseInOutInfoService.insert(warehouseInOutInfo);
        boolean one = this.insert(tranCarInfo);
        // 插入操作历史
        String staffName = this.billOperateHisService.getStaffAndName();
        // 插入操作历史
        this.billOperateHisService.saveBillOperateHis(tranCarInfo.getId(), NumberConstant.CONSTANT_TRAN, staffName, null,
                tranCarInfo.getStatus(), null, "");
        //成功返回ok
        if (one && two) {
            return "OK";
        } else {
            return "NG";
        }
    }

    /**
     * 确认卸货
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String confirmUnloading(String id) {
        //查询车辆信息
        TranCarInfo tranCarInfo = this.selectById(id);
        //更改状态
        if (tranCarInfo != null) {
            tranCarInfo.setConfirmFlag(StatusEnum.CONFIRM.getFlag());
            //更改运输任务信息
            this.updateById(tranCarInfo);
            // 插入操作历史
            String staffName = this.billOperateHisService.getStaffAndName();
            // 插入操作历史
            this.billOperateHisService.saveBillOperateHis(tranCarInfo.getId(), NumberConstant.CONSTANT_TRAN, staffName, null,
                    tranCarInfo.getStatus(), null, "");
            //更新报表客户确认状态
            //采购
            PurchaseReceiptReport purchaseReceiptReport = purchaseReceiptReportService.selectOne(new EntityWrapper<PurchaseReceiptReport>()
                    .eq("tran_car_no", tranCarInfo.getTranCarNo())
                    .eq("car_no", tranCarInfo.getCarNo())
                    .eq("contract_no", tranCarInfo.getContractNo()));
            if (purchaseReceiptReport != null) {
                purchaseReceiptReport.setCustomerConfirmationStatus("是");
                purchaseReceiptReport.setCustomerConfirmationStatusFlag("3");
                purchaseReceiptReportService.updateById(purchaseReceiptReport);
            }
            //销售
            SalesDeliveryReport salesDeliveryReport = salesDeliveryReportService.selectOne(new EntityWrapper<SalesDeliveryReport>()
                    .eq("tran_car_no", tranCarInfo.getTranCarNo())
                    .eq("car_no", tranCarInfo.getCarNo())
                    .eq("contract_no", tranCarInfo.getContractNo()));
            if (salesDeliveryReport != null) {
                salesDeliveryReport.setCustomerConfirmationStatus("是");
                salesDeliveryReport.setCustomerConfirmationStatusFlag("3");
                salesDeliveryReportService.updateById(salesDeliveryReport);
            }
            return "OK";
        }
        return "NG";
    }

    /**
     * 查发车数量
     *
     * @param tranCarInfo
     */
    @Override
    public List<TranCarInfo> selectTranCarInfoNum(TranCarInfo tranCarInfo) {
        //查合同下的发车数据
        List<TranCarInfo> tranCarInfoList = this.selectList(new EntityWrapper<TranCarInfo>()
                .eq("contract_no", tranCarInfo.getContractNo())
                .eq(TranCarInfo.QueryFiles.DELETE_FLAG, NumberConstant.CONSTANT0)
                .orderBy("tran_car_no", true));
        return tranCarInfoList;
    }

    /**
     * 删除车辆
     *
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteTranCar(String id) {
        TranCarInfo tranCarInfo = this.selectById(id);
        if (tranCarInfo != null) {
            this.deleteById(tranCarInfo.getId());
        }
    }

    /**
     * APP保存反馈
     * @param tranCarInfo
     * @return
     */
    @Override
    public String feedbackTranCar(TranCarInfo tranCarInfo) {
        this.updateById(tranCarInfo);
        return tranCarInfo.getId();
    }

    /**
     * 任务
     *
     * @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);

    }

}
