package com.zd.airbottle.service.impl;

import com.alibaba.fastjson.JSON;
import com.zd.airbottle.domain.QpSupplier;
import com.zd.airbottle.domain.QpTask;
import com.zd.airbottle.domain.QpTaskDetail;
import com.zd.airbottle.domain.vo.QpAirGoodsConfigRelationVo;
import com.zd.airbottle.domain.vo.QpQualificationApplyVO;
import com.zd.airbottle.domain.vo.QpTaskDetailVO;
import com.zd.airbottle.domain.vo.QpTaskVO;
import com.zd.airbottle.mapper.QpTaskDetailMapper;
import com.zd.airbottle.mapper.QpTaskMapper;
import com.zd.airbottle.service.IQpQualificationApplyService;
import com.zd.airbottle.service.IQpSupplierService;
import com.zd.airbottle.service.IQpTaskService;
import com.zd.common.core.constant.HttpStatus;
import com.zd.common.core.domain.R;
import com.zd.common.core.domain.per.PerPrefix;
import com.zd.common.core.exception.ServiceException;
import com.zd.common.core.template.TemplateResult;
import com.zd.common.datascope.annotation.DataScope;
import com.zd.common.security.service.TokenService;
import com.zd.common.security.utils.SaveUtil;
import com.zd.system.api.domain.SysUser;
import com.zd.system.api.message.RemoteMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 待办清单表Service业务层处理
 */
@Service
@Slf4j
public class QpTaskServiceImpl implements IQpTaskService {
    @Autowired
    private QpTaskMapper qpTaskMapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private QpTaskDetailMapper qpTaskDetailMapper;

    @Autowired
    private IQpQualificationApplyService qpQualificationApplyService;

    @Autowired
    private RemoteMessageService remoteMessageService;

    @Autowired
    private IQpSupplierService qpSupplierService;



    /**
     * 查询待办清单表
     *
     * @param id 待办清单表主键
     * @return 待办清单表
     */
    @Override
    public QpTaskVO selectQpTaskById(Long id) {
        return qpTaskMapper.selectQpTaskById(id);
    }

    /**
     * 查询待办清单表列表
     *
     * @param qpTask 待办清单表
     * @return 待办清单表
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u", permi = PerPrefix.AIRBOTTLE_TASK)
    public List<QpTaskVO> selectQpTaskList(QpTaskVO qpTask) {
        return qpTaskMapper.selectQpTaskList(qpTask);
    }

    /**
     * 查询申领记录列表
     *
     * @param qpTask 申领记录
     * @return 申领记录集合
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u", permi = PerPrefix.AIRBOTTLE_INFORMATIONRECORD)
    public List<QpTaskVO> selectQpTaskRecordList(QpTaskVO qpTask) {
        return qpTaskMapper.selectQpTaskList(qpTask);
    }

    /**
     * 新增待办清单表
     *
     * @param qpTaskVO 待办清单表
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertQpTask(QpTaskVO qpTaskVO) {

        SysUser sysUser = tokenService.getLoginUser().getSysUser();

        //校验是否有该实验室的气瓶申请资格
        QpQualificationApplyVO qpQualificationApplyVO = new QpQualificationApplyVO();
        qpQualificationApplyVO.setSubjectId(qpTaskVO.getLocationId());//实验室id
        qpQualificationApplyVO.setCenterAuditStatus(1);//实验中心审核通过
        qpQualificationApplyVO.setUserId(sysUser.getUserId());//用户id
        List<QpQualificationApplyVO> applyVOList = qpQualificationApplyService.selectQpQualificationApplyList(qpQualificationApplyVO);
        if(applyVOList.isEmpty()){
            throw new ServiceException("请先申请该实验室的气瓶申请资格");
        }

        applyVOList = applyVOList.stream().filter(apply -> apply.getEndTime().getTime()>new Date().getTime()).collect(Collectors.toList());
        if(applyVOList.isEmpty()){
            throw new ServiceException("该实验室的气瓶申请资格已过期！");
        }

        //设置其他公共字段
        SaveUtil.setCommonAttr(qpTaskVO);
        qpTaskVO.setCreateTime(new Date());//创建时间
        qpTaskVO.setUserId(sysUser.getUserId());//申请人id
        qpTaskVO.setUserName(sysUser.getNickName());//申请人姓名
        qpTaskVO.setPhone(sysUser.getPhonenumber());//电话
        //申请表数据录入
        qpTaskMapper.insertQpTask(qpTaskVO);

        List<QpTaskDetailVO> detaiVolList = qpTaskVO.getDetailListVO();
        if (detaiVolList != null && !detaiVolList.isEmpty()) {
            for (QpTaskDetailVO qpTaskDetailVO : detaiVolList) {
                Map<String, String> map = new HashMap<>();
                map.put("airName", qpTaskDetailVO.getAirName());//气体名称
                map.put("companyName", qpTaskDetailVO.getCompanyName());//商家名称
                map.put("airConstituents", qpTaskDetailVO.getAirConstituents());//气体组分
                map.put("gasLevel", qpTaskDetailVO.getConfigName());//规格
                qpTaskDetailVO.setApplyDescribe(JSON.toJSONString(map));
                qpTaskDetailVO.setTaskId(qpTaskVO.getId());
                qpTaskDetailVO.setCreateTime(new Date());
                qpTaskDetailVO.setIsDispose(0L);//未处理
                qpTaskDetailMapper.insertQpTaskDetail(qpTaskDetailVO);

                //消息发送
                Long supplierId = qpSupplierService.selectQpSupplierById(qpTaskDetailVO.getSupplierId()).getAccountId();
                R<TemplateResult> resultR = remoteMessageService.backlog(supplierId, "气瓶申请", qpTaskVO.getLocation());
                if (resultR.getCode()!= HttpStatus.SUCCESS){
                    log.error(resultR.getMsg());
                }
            }
        }
        return 1;
    }

    /**
     * 修改待办清单表
     *
     * @param qpTaskVO 待办清单表
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateQpTask(QpTaskVO qpTaskVO) {
        SysUser sysUser = tokenService.getLoginUser().getSysUser();
        if ("1".equals(qpTaskVO.getRemark())) {
            //查询供应商信息
            QpSupplier qpSupplier = qpSupplierService.selectQpSupplierByAccountId(sysUser.getUserId());
            //查询本条订单的所有详情集合
            QpTaskDetail taskDetail = new QpTaskDetail();
            taskDetail.setTaskId(qpTaskVO.getId());
            taskDetail.setSupplierId(qpSupplier.getId());//供应商id
            List<QpTaskDetail> detailList = qpTaskDetailMapper.selectQpTaskDetailList(taskDetail);
            for (QpTaskDetail detail : detailList) {
                //更新待办清单详情表气瓶状态
                QpTaskDetail qpTaskDetail = new QpTaskDetail();
                qpTaskDetail.setId(detail.getId());
                qpTaskDetail.setTaskId(qpTaskVO.getId());
                qpTaskDetail.setQpStatus(1L);//入库
                qpTaskDetail.setCarId(qpTaskVO.getTransportCar().getId());//车辆id
                qpTaskDetail.setCarNumber(qpTaskVO.getTransportCar().getCarCode());//车牌号码
                qpTaskDetail.setTransportId(qpTaskVO.getTransportUser().getId());//司机id
                qpTaskDetail.setTransportName(qpTaskVO.getTransportUser().getUserName());//司机姓名
                qpTaskDetail.setDisposeUserid(sysUser.getUserId());
                qpTaskDetail.setDisposeUser(sysUser.getNickName());
                qpTaskDetail.setDisposeTime(new Date());
                qpTaskDetail.setIsDispose(1L);//已处理
                qpTaskDetailMapper.updateQpTaskDetail(qpTaskDetail);
            }
        }
        return 1;
    }

    /**
     * 批量删除待办清单表
     *
     * @param ids 需要删除的待办清单表主键
     * @return 结果
     */
    @Override
    public int deleteQpTaskByIds(Long[] ids) {
        return qpTaskMapper.deleteQpTaskByIds(ids);
    }

    /**
     * 删除待办清单表信息
     *
     * @param id 待办清单表主键
     * @return 结果
     */
    @Override
    public int deleteQpTaskById(Long id) {
        return qpTaskMapper.deleteQpTaskById(id);
    }

    /**
     * 小程序日期查询
     */
    @Override
    public List<QpTaskVO> selectQpTaskListOrderByDate(QpTaskVO qpTaskVO) {
        return qpTaskMapper.selectQpTaskListOrderByDate(qpTaskVO);
    }

    /**
     * 小程序供气回收记录日期查询
     */
    @Override
    public List<QpTaskVO> selectQpTaskListOrderByDateReclaim(QpTaskVO qpTaskVO) {
        return qpTaskMapper.selectQpTaskListOrderByDateReclaim(qpTaskVO);
    }

    @Override
    public List<QpTask> getApplyList(String applyName, Date applyTime) {
        return qpTaskMapper.getApplyList(applyName, applyTime);
    }

    /**
     * 实验室信息关联查询
     */
    @Override
    public List<QpTaskVO> selectQpTaskBySubjectRelation(QpTaskVO qpTaskVO) {
        return qpTaskMapper.selectQpTaskBySubjectRelation(qpTaskVO);
    }

    /***
     * 气瓶使用记录按照实验室分组
     */
    @Override
    public List<QpTaskVO> selectUseRecord(QpTaskVO qpTaskVO) {
        return qpTaskMapper.selectUseRecord(qpTaskVO);
    }

    /***
     * 实验室下的气瓶使用情况
     */
    @Override
    public List<QpAirGoodsConfigRelationVo> selectUseRecordBySubjectId(QpTaskVO qpTaskVO) {
        return qpTaskMapper.selectUseRecordBySubjectId(qpTaskVO);
    }

    /**
     * 根据当前登录用户 查询待办清单申请集合
     */
    @Override
    public List<QpTaskVO> selectQpTaskListCount(QpTaskVO qpTaskVO) {
        return qpTaskMapper.selectQpTaskListCount(qpTaskVO);
    }

    /**
     * 查询某个实验室配置的气瓶数量信息
     */
    @Override
    public List<Map<String, Object>> selectSubjectDetail(Long subjectId) {
        return qpTaskMapper.selectSubjectDetail(subjectId);
    }

    @Override
    public List<QpTask> getByIds(List<Long> ids) {
        return qpTaskMapper.getByIds(ids);
    }
}
