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

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
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.entity.CommonStaffRole;
import com.winsea.svc.base.base.service.ICommonRoleResourceService;
import com.winsea.svc.base.base.service.ICommonStaffRoleService;
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.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.YException;
import com.yh.saas.plugin.yiliangyiyun.exception.YExceptionEnum;
import com.yh.saas.plugin.yiliangyiyun.mapper.TranTaskInfoMapper;
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.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 记录运输任务 服务实现类
 * </p>
 *
 * @author Gongdc
 * @since 2021-05-31
 */
@Service
public class TranTaskInfoServiceImpl extends ServiceImpl<TranTaskInfoMapper, TranTaskInfo> implements ITranTaskInfoService {

    @Autowired
    private ITranProcessInfoService tranProcessInfoService;
    @Autowired
    private ITranTaskInfoService tranTaskInfoService;
    @Autowired
    private ITranCarInfoService tranCarInfoService;
    @Autowired
    private ICommonBillOperateHisService billOperateHisService;
    @Autowired
    private IWarehouseBaseInfoService warehouseBaseInfoService;
    @Autowired
    private IContractManagementInfoService contractManagementInfoService;
    @Autowired
    private IContractGoodsInfoService contractGoodsInfoService;
    @Autowired
    private IInOutWarehouseTaskService iInOutWarehouseTaskService;
    @Autowired
    private IWarehousePositionInfoService warehousePositionInfoService;
    @Autowired
    private INoticeService noticeService;
    @Autowired
    private INoticeTaskService noticeTaskService;
    @Autowired
    private ICommonStaffService staffService;


    /**
     * 创建运输任务
     * @param tranTaskInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addTranTask(TranTaskInfo tranTaskInfo){
        //新增主键id
        tranTaskInfo.setId(IdGenerator.generateUUID());
        tranTaskInfo.setStatus(StatusEnum.TRAN_DO.getName());
        tranTaskInfo.setStatusFlag(StatusEnum.TRAN_DO.getFlag());
        //新增运输阶段
        List<TranProcessInfo> tranProcessInfoList = tranTaskInfo.getTranProcessInfoList();
        if (!CollectionUtils.isEmpty(tranProcessInfoList)) {
            for (TranProcessInfo tranProcessInfo : tranProcessInfoList) {
                tranProcessInfo.setId(IdGenerator.generateUUID());
                tranProcessInfo.setInfoId(tranTaskInfo.getId());
                tranProcessInfo.setGoodsName(tranTaskInfo.getGoodsName());
                tranProcessInfo.setGoodsNameKey(tranTaskInfo.getGoodsNameKey());
                tranProcessInfo.setContractNo(tranTaskInfo.getContractNo());
                tranProcessInfo.setReceivingDate(tranTaskInfo.getCreateDate());
                tranProcessInfo.setProcessStatusFlag(StatusEnum.PROCESS_DO.getFlag());
                tranProcessInfo.setProcessStatus(StatusEnum.PROCESS_DO.getName());
                tranProcessInfo.setFeedbackStatusFlag(StatusEnum.FEEDBACK_DO.getFlag());
                tranProcessInfo.setFeedbackStatus(StatusEnum.FEEDBACK_DO.getName());
                tranProcessInfo.setReceivingStatusFlag(StatusEnum.FEEDBACK_DO.getFlag());
                tranProcessInfo.setReceivingStatus(StatusEnum.FEEDBACK_DO.getName());
                Wrapper<TranProcessInfo> tranProcessInfoWrapper = new EntityWrapper<>();
                tranProcessInfoWrapper.orderBy("sort",false);
                tranTaskInfo.setCurrentTransferAddress(tranProcessInfo.getReceivePrivate() + tranProcessInfo.getReceiveCity()
                    + tranProcessInfo.getReceiveArea() + tranProcessInfo.getReceiveDetailedAddress() );
                this.updateById(tranTaskInfo);
            }
        }

        //判断任务编号是否唯一
        List<TranTaskInfo> tranTaskInfoList = tranTaskInfoService.selectList(new EntityWrapper<TranTaskInfo>()
                .eq(TranTaskInfo.QueryFiles.TASK_NO,tranTaskInfo.getTaskNo())
                .eq(TranTaskInfo.QueryFiles.DELETE_FLAG, NumberConstant.CONSTANT0));
        if (tranTaskInfoList.size()>0){
            throw new YException(YExceptionEnum.TASK_NO_ERROR);
        }
        boolean one = this.insert(tranTaskInfo);
        boolean two = tranProcessInfoService.insertBatch(tranProcessInfoList);
        // 插入操作历史
        String staffName = this.billOperateHisService.getStaffAndName();
        // 插入操作历史
        this.billOperateHisService.saveBillOperateHis(tranTaskInfo.getId(), NumberConstant.CONSTANT_TRAN, staffName, null,
                tranTaskInfo.getStatus(), null, "");

        //创建任务
        if ("2710b21efc1e4393930c5dc800010dc4".equals(tranTaskInfo.getCompId())) {
            List<CommonStaff> commonStaffList = staffService.selectList(new EntityWrapper<CommonStaff>()
                    .eq("dept_id", "839073b95d9a4529ba55dba5104eba19")
                    .eq("delete_flag","0"));
            List<String> staffIds = commonStaffList.stream().map(CommonStaff::getStaffId).collect(Collectors.toList());
        // 先删除任务
        noticeService.removeNotice(BaseNotice.NoticeStatus.TASK, "TRANTASK-APPROVE",
                tranTaskInfo.getId(), null);
        String staffNames = "XXX";
        CommonStaff commitUserInfo = staffService.getInfo(AuthSecurityUtils.getCurrentUserId());
        if (commitUserInfo != null) {
            staffNames = commitUserInfo.getMajorRole() != null
                    ? commitUserInfo.getMajorRole().getRoleName() + " " + commitUserInfo.getStaffName()
                    : commitUserInfo.getStaffName();
        }
        String taskContent = "";
        // 向下一步操作人发送任务通知
        taskContent = "运输任务" + staffNames + "内勤" + staffNames + "提交的" + tranTaskInfo.getTranType() + "运输任务待派发，请及时处理。";
        NoticeTaskInfo taskInfo = new NoticeTaskInfo();
        taskInfo.setCompId(commitUserInfo.getCompId());
        taskInfo.setAcceptType(BaseNotice.AcceptStatus.STAFF);
        taskInfo.setBusinessId(tranTaskInfo.getId());
        taskInfo.setBusinessType("TRANSPORTATIONTASK");
        taskInfo.setMessageContent(taskContent);
        taskInfo.setBusinessCode("TRANTASK-APPROVE");
//            taskInfo.setNoticeTaskStatus(NoticeTaskInfo.NoticeTaskStatus.RETURN);
        noticeTaskService.createNoticeTask(staffIds,
                null, taskInfo);
        }
        // 假如 都成功返回ok
        if (one && two ) {
            return "OK";
        } else {
            return "NG";
        }
    }

    /**
     * 查看运输信息
     * @param id
     * @return
     */
    @Override
    public TranTaskInfo getTranTask(String id){
        //查看运输信息
        TranTaskInfo tranTaskInfo = this.selectById(id);
        //查看运输阶段信息
        List<TranProcessInfo> tranProcessInfoList = tranProcessInfoService.selectList(new EntityWrapper<TranProcessInfo>()
                .eq(TranProcessInfo.QueryFiles.INFO_ID,id).eq(TranProcessInfo.QueryFiles.DELETE_FLAG,NumberConstant.CONSTANT0)
                .orderBy(TranProcessInfo.QueryFiles.SORT));
        if (!CollectionUtils.isEmpty(tranProcessInfoList)) {
            for (TranProcessInfo tranProcessInfo:tranProcessInfoList){
                //查看运输阶段下派车数量
               Integer carNum= tranCarInfoService.selectCount(new EntityWrapper<TranCarInfo>()
                        .eq(TranCarInfo.QueryFiles.PROCESS_ID,tranProcessInfo.getId()).eq(TranCarInfo.QueryFiles.DELETE_FLAG,NumberConstant.CONSTANT0));
                tranProcessInfo.setCarNum(carNum);
            }
            tranTaskInfo.setTranProcessInfoList(tranProcessInfoList);
        }
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("id", id);
        // 查询调度总数包括已删除的
        Integer dataCount = baseMapper.getProcessByCondition(pageView);
        tranTaskInfo.setCount(dataCount);
        return tranTaskInfo;
    }

    /**
     * 删除运输信息
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteTranTask(String id) {
        //删除运输信息
        TranTaskInfo tranTaskInfo = this.selectById(id);
        //判断是否有运输阶段
        List<TranProcessInfo> tranProcessInfos = tranProcessInfoService.selectList(new EntityWrapper<TranProcessInfo>()
                .eq(TranProcessInfo.QueryFiles.INFO_ID, tranTaskInfo.getId()));
        if(tranProcessInfos.size()>1){
            throw new YException(YExceptionEnum.TRAN_PROCESS_SORT_ERROR);
        }
        else{
            //删除运输信息
            this.deleteById(tranTaskInfo.getId());
            //删除运输阶段信息
            tranProcessInfoService.deleteById(tranProcessInfos.get(0).getId());
//        if (!CollectionUtils.isEmpty(tranProcessInfos)) {
//            for (TranProcessInfo tranProcessInfo : tranProcessInfos) {
//                tranProcessInfoService.deleteById(tranProcessInfo.getId());
//                }
//            }
        }
    }

    /**
     * 编辑运输任务
     * @param tranTaskInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String editTranTask(TranTaskInfo tranTaskInfo){
        // 运输任务编辑
        this.updateById(tranTaskInfo);
        //运输阶段编辑
        List<TranProcessInfo> tranProcessInfoList = tranTaskInfo.getTranProcessInfoList();
        if (!CollectionUtils.isEmpty(tranProcessInfoList)){
            tranProcessInfoList.forEach(tranProcessInfo -> {
                if(StringUtils.isEmpty(tranProcessInfo.getId())){
                    tranProcessInfo.setId(IdGenerator.generateUUID());
                    tranProcessInfo.setInfoId(tranTaskInfo.getId());
                    tranProcessInfoService.insert(tranProcessInfo);
                }
                else{
                    if(StatusEnum.TRAN_COMPLETED.getFlag().equals(tranTaskInfo.getStatusFlag())) {
                        throw new YException(YExceptionEnum.TRAN_PROCESS_ERROR);
                    }else {
                        tranProcessInfoService.updateById(tranProcessInfo);
                    }
                }
            });
        }
        return tranTaskInfo.getId();
    }

    /**
     * 运输管理页面
     * @param tranTaskInfo
     * @return
     */
    @Override
    public Page<TranTaskInfo> selectTranTaskInfoPage(TranTaskInfo tranTaskInfo){
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("startRecord", (tranTaskInfo.getCurrentPage() - 1)
                * tranTaskInfo.getPageSize());
        //公司id
        pageView.put("compId",tranTaskInfo.getCompId());
        pageView.put("start",tranTaskInfo.getStart());
        pageView.put("end",tranTaskInfo.getEnd());
        pageView.put("searchKeyWord",tranTaskInfo.getSearchKeyWord());
        pageView.put("searchType", tranTaskInfo.getSearchType());
        pageView.put("pageSize",tranTaskInfo.getPageSize());
        pageView.put("currentPage",tranTaskInfo.getCurrentPage());
        // 查询运输任务总数
        Integer dataCount = baseMapper.getCountByCondition(pageView);
        List<TranTaskInfo> dataList = baseMapper.getListByCondition(pageView);
        Page<TranTaskInfo> page = new Page<>();
        page.setRecords(dataList == null ? Lists.newArrayList() : dataList);
        page.setTotal(dataCount == null ? 0 : dataCount);
        page.setCurrent(tranTaskInfo.getCurrentPage());
        page.setSize(tranTaskInfo.getPageSize());
        return page;
    }

    /**
     * 更改状态
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String editStatus(String id){
        //查询运输任务信息
        TranTaskInfo tranTaskInfo = this.selectById(id);
        //更改状态
        if (tranTaskInfo != null ){
            if (StatusEnum.TRAN_DO.getFlag().equals(tranTaskInfo.getStatusFlag())) {
                tranTaskInfo.setStatusFlag(StatusEnum.TRAN_COMPLETED.getFlag());
                tranTaskInfo.setStatus(StatusEnum.TRAN_COMPLETED.getName());
            } else {
                tranTaskInfo.setStatusFlag(StatusEnum.TRAN_DO.getFlag());
                tranTaskInfo.setStatus(StatusEnum.TRAN_DO.getName());
            }
            //更改运输任务信息
            this.updateById(tranTaskInfo);
            // 插入操作历史
            String staffName = this.billOperateHisService.getStaffAndName();
            // 插入操作历史
            this.billOperateHisService.saveBillOperateHis(tranTaskInfo.getId(), NumberConstant.CONSTANT_TRAN, staffName, null,
                    tranTaskInfo.getStatus(), null, "");
            return "OK";
        }
        return "NG";
    }
    
    /**
     * 根据仓库类型选库名
     * @param compId
     * @param warehouseType
     * @return
     */
    @Override
    public List<WarehouseBaseInfo> selectWarehouseList(String compId, String warehouseType) {
        List<WarehouseBaseInfo> warehouseBaseInfoList =warehouseBaseInfoService.selectList(new EntityWrapper<WarehouseBaseInfo>()
                .eq(WarehouseBaseInfo.QueryFiles.COMP_ID, compId)
                .eq(WarehouseBaseInfo.QueryFiles.DELETE_FLAG, NumberConstant.CONSTANT0)
                .eq(WarehouseBaseInfo.QueryFiles.WAREHOUSE_TYPE,warehouseType)
                .orderBy(WarehouseBaseInfo.QueryFiles.UPDATE_DATE, false));
        if (!CollectionUtils.isEmpty(warehouseBaseInfoList)) {
            for (WarehouseBaseInfo warehouseBaseInfo : warehouseBaseInfoList) {
                //临时库带出品级
                if ("2".equals(warehouseBaseInfo.getWarehouseType())){
                    ContractManagementInfo contractManagementInfo=contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                    .eq("comp_id",compId)
                    .eq("contract_no",warehouseBaseInfo.getWarehouseName()));
                    if (contractManagementInfo!=null){
                        //货物信息
                        ContractGoodsInfo contractGoodsInfo = contractGoodsInfoService.selectOne(new EntityWrapper<ContractGoodsInfo>().eq(ContractGoodsInfo.QueryFiles.CONTRACT_ID, contractManagementInfo.getId()));
                        warehouseBaseInfo.setGrade(contractGoodsInfo.getGrade());
                        warehouseBaseInfo.setGoodsName(contractGoodsInfo.getGoodsName());
                    }
                }
                // 以库位为维度查询
                List<WarehousePositionInfo> warehousePositionInfos = warehousePositionInfoService.selectList(new EntityWrapper<WarehousePositionInfo>()
                        .eq("base_id", warehouseBaseInfo.getId()));
                if (!CollectionUtils.isEmpty(warehousePositionInfos)) {
                    warehouseBaseInfo.setPositionInfos(warehousePositionInfos);
                }
            }

        }
        return warehouseBaseInfoList;
    }

    /**
     * 查合同号下拉列表
     * flag(1船运 2火运）
     * @param flag
     * @return
     */
    @Override
    public List<String> selectTranTask(String flag) {
        List<String> stringList=new ArrayList<>();
        List<ContractManagementInfo> contractManagementInfoList=contractManagementInfoService.selectList(new EntityWrapper<ContractManagementInfo>()
                .eq("comp_id", AuthSecurityUtils.getCurrentUserInfo().getCompId())
                .orderBy("update_date",false));
        if (!CollectionUtils.isEmpty(contractManagementInfoList)) {
            for (ContractManagementInfo contractManagementInfo : contractManagementInfoList) {
                Wrapper wrapper=new EntityWrapper();
                wrapper.eq("contract_no", contractManagementInfo.getContractNo());
                if ("1".equals(flag)){
                    wrapper.eq("tran_type","船运");
                }
                else {
                    wrapper.eq("tran_type","火运");
                }
                List<TranProcessInfo> tranProcessInfos = tranProcessInfoService.selectList(wrapper);
                if (!CollectionUtils.isEmpty(tranProcessInfos)){
                    for (TranProcessInfo tranProcessInfo:tranProcessInfos){
                        stringList.add(tranProcessInfo.getContractNo());
                    }
                }
            }
        }
        List<InOutWarehouseTask> inOutWarehouseTaskList=iInOutWarehouseTaskService.selectList(new EntityWrapper<InOutWarehouseTask>()
                .eq("comp_id", AuthSecurityUtils.getCurrentUserInfo().getCompId())
                .orderBy("update_date",false));
        if (!CollectionUtils.isEmpty(inOutWarehouseTaskList)) {
            for (InOutWarehouseTask inOutWarehouseTask : inOutWarehouseTaskList) {
                Wrapper wrapper=new EntityWrapper();
                wrapper.eq("contract_no", inOutWarehouseTask.getMoveTaskNo());
                if ("1".equals(flag)){
                    wrapper.eq("tran_type","船运");
                }
                else {
                    wrapper.eq("tran_type","火运");
                }
                List<TranProcessInfo> tranProcessInfos = tranProcessInfoService.selectList(wrapper);
                if (!CollectionUtils.isEmpty(tranProcessInfos)){
                    for (TranProcessInfo tranProcessInfo:tranProcessInfos){
                        stringList.add(tranProcessInfo.getContractNo());
                    }
                }
            }
        }
        LinkedHashSet<String> hashSet = new LinkedHashSet<>(stringList);
        ArrayList<String> listWithoutDuplicates = new ArrayList<>(hashSet);
        return listWithoutDuplicates;
    }
    /**
     * 根据合同号查运输任务
     * @param contractNo
     */
    @Override
    public List<TranTaskInfo> selectTask(String contractNo,String flag) {
        List<TranTaskInfo> tranTaskInfoList=this.selectList(new EntityWrapper<TranTaskInfo>()
                .eq("comp_id", AuthSecurityUtils.getCurrentUserInfo().getCompId())
                .eq("contract_no",contractNo)
                .orderBy("update_date",false));
        if (!CollectionUtils.isEmpty(tranTaskInfoList)){
            for (TranTaskInfo tranTaskInfo : tranTaskInfoList) {
                Wrapper wrapper=new EntityWrapper();
                if ("1".equals(flag)){
                    wrapper.eq("tran_type","船运");
                }
                else {
                    wrapper.eq("tran_type","火运");
                }
                //查看运输阶段信息
                wrapper.eq(TranProcessInfo.QueryFiles.INFO_ID,tranTaskInfo.getId())
                        .eq(TranProcessInfo.QueryFiles.DELETE_FLAG,NumberConstant.CONSTANT0)
                         .orderBy(TranProcessInfo.QueryFiles.SORT);
                List<TranProcessInfo> tranProcessInfos = tranProcessInfoService.selectList(wrapper);
                if (!CollectionUtils.isEmpty(tranProcessInfos)){
                    tranTaskInfo.setTranProcessInfoList(tranProcessInfos);
                }
            }
        }
        return tranTaskInfoList;
    }
}
