package com.zehong.system.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.github.pagehelper.PageInfo;
import com.zehong.common.core.domain.entity.SysUser;
import com.zehong.common.utils.DateUtils;
import com.zehong.common.utils.PageInfoUtil;
import com.zehong.system.domain.*;
import com.zehong.system.domain.form.TWorkOrderForm;
import com.zehong.system.domain.vo.OrderFeedbackVo;
import com.zehong.system.domain.vo.WorkOrderVo;
import com.zehong.system.mapper.*;
import com.zehong.system.service.ITWorkOrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 工单基础信息Service业务层处理
 * 
 * @author zehong
 * @date 2021-07-19
 */
@Service
public class TWorkOrderServiceImpl implements ITWorkOrderService 
{
    @Autowired
    private TWorkOrderMapper tWorkOrderMapper;
    @Autowired
    private TOrderFeedbackMapper tOrderFeedbackMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private TInspectionPlanMapper tInspectionPlanMapper;
    @Autowired
    private TInspectionDataMapper tInspectionDataMapper;
    @Autowired
    private THiddenTroubleMapper tHiddenTroubleMapper;
    @Autowired
    private TDeviceAlarmMapper tDeviceAlarmMapper;
    @Autowired
    private TPipeMapper tPipeMapper;
    @Autowired
    private TDeviceInfoMapper tDeviceInfoMapper;

    /**
     * 查询工单基础信息
     * 
     * @param orderId 工单基础信息ID
     * @return 工单基础信息
     */
    @Override
    public WorkOrderVo selectTWorkOrderById(String orderId) throws Exception
    {
        WorkOrderVo workOrderVo = new WorkOrderVo();
        TWorkOrder tWorkOrder = tWorkOrderMapper.selectTWorkOrderById(orderId);

        BeanUtils.copyProperties(tWorkOrder, workOrderVo);

        // 获取巡检员姓名
        SysUser appointInspector = sysUserMapper.selectUserById(tWorkOrder.getAppointInspector());
        workOrderVo.setAppointInspectorName(appointInspector.getNickName());

        if(tWorkOrder.getActualInspector() != tWorkOrder.getAppointInspector() && tWorkOrder.getActualInspector() != null){
            SysUser actualInspector = sysUserMapper.selectUserById(tWorkOrder.getActualInspector());
            workOrderVo.setActualInspectorName(actualInspector.getNickName());
        } else {
            workOrderVo.setActualInspectorName(appointInspector.getNickName());
        }

        // 获取源数据(1巡检信息，2隐患信息，3报警信息)
        String orderType = tWorkOrder.getOrderType();
        int resourceId = tWorkOrder.getResourceId();

        List<TDeviceInfo> deviceInfoList = new ArrayList<>();
        List<TPipe> pipeList = new ArrayList<>();

        if("1".equals(orderType)){

            TInspectionData data = new TInspectionData();
            data.setPlanId(resourceId);

            List<TInspectionData> totalList = tInspectionDataMapper.selectTInspectionDataList(data);
            workOrderVo.setDeviceNum(totalList.size());

            if(totalList.size() != 0) {
                TDeviceInfo deviceInfo = null;
                TPipe pipe = null;

                for (TInspectionData temp : totalList) {
                    if(!"0".equals(temp.getDeviceType())) {
                        deviceInfo = tDeviceInfoMapper.selectTDeviceInfoById(temp.getDeviceId());
                        if (deviceInfo != null) {
                            deviceInfoList.add(deviceInfo);
                        }
                    } else {
                        pipe = tPipeMapper.selectTPipeById(temp.getDeviceId());
                        if(pipe != null){
                            pipeList.add(pipe);
                        }
                    }
                }
            }

            int finish = tInspectionDataMapper.selectFinishTInspectionData(resourceId);
            workOrderVo.setFinishNum(finish);

        } else if("2".equals(orderType)) {

            THiddenTrouble trouble = tHiddenTroubleMapper.selectTHiddenTroubleById(resourceId);
            Integer deviceId = trouble.getDeviceId();
            String deviceType = trouble.getDeviceType();

            if("0".equals(deviceType)){
                TPipe pipe = tPipeMapper.selectTPipeById(deviceId);
                if(pipe != null){
                    workOrderVo.setDeviceName(pipe.getPipeName());
                    pipeList.add(pipe);
                }
            } else {
                TDeviceInfo device = tDeviceInfoMapper.selectTDeviceInfoById(deviceId);
                if(device != null){
                    workOrderVo.setDeviceName(device.getDeviceName());
                    deviceInfoList.add(device);
                }
            }
            workOrderVo.setDeviceType(deviceType);

        } else if("3".equals(orderType)) {

            TDeviceAlarm alarm = tDeviceAlarmMapper.selectTDeviceAlarmById(resourceId);
            Integer deviceId = alarm.getDeviceId();
            String deviceType = alarm.getDeviceType();

            if("0".equals(deviceType)){
                TPipe pipe = tPipeMapper.selectTPipeById(deviceId);
                if(pipe != null) {
                    workOrderVo.setDeviceName(pipe.getPipeName());
                    pipeList.add(pipe);
                }
            } else {
                TDeviceInfo device = tDeviceInfoMapper.selectTDeviceInfoById(deviceId);
                if(device != null){
                    workOrderVo.setDeviceName(device.getDeviceName());
                    deviceInfoList.add(device);
                }
            }
            workOrderVo.setDeviceType(deviceType);
        }

        workOrderVo.setDeviceInfoList(deviceInfoList);
        workOrderVo.setPipeList(pipeList);

        List<TOrderFeedback> feedbackList = tOrderFeedbackMapper.selectTOrderFeedbackByOrderId(tWorkOrder.getOrderId());
        List<OrderFeedbackVo> feedbackVoList = new ArrayList<>();
        TDeviceInfo device = null;

        if(feedbackList.size() != 0) {

            for (TOrderFeedback feedback : feedbackList) {
                OrderFeedbackVo feedbackVo = new OrderFeedbackVo();
                BeanUtils.copyProperties(feedback, feedbackVo);

                if("0".equals(feedback.getDeviceType())) {
                    TPipe pipe = tPipeMapper.selectTPipeById(feedback.getDeviceId());
                    if(pipe != null){
                        feedbackVo.setDeviceName(pipe.getPipeName());
                    }
                } else {
                    device = tDeviceInfoMapper.selectTDeviceInfoById(feedback.getDeviceId());
                    if (device != null) {
                        feedbackVo.setDeviceName(device.getDeviceName());
                    }
                }
                feedbackVoList.add(feedbackVo);
            }

            if (feedbackVoList.size() != 0) {
                workOrderVo.setFeedbackList(feedbackVoList);
            }
        }

        return workOrderVo;
    }

    /**
     * 查询工单基础信息列表
     * 
     * @param tWorkOrderForm 工单基础信息
     * @return 工单基础信息
     */
    @Override
    public List<WorkOrderVo> selectTWorkOrderList(TWorkOrderForm tWorkOrderForm) throws Exception
    {
        List<WorkOrderVo> workOrderVoList = new ArrayList<WorkOrderVo>();
        List<TWorkOrder> workOrderList = tWorkOrderMapper.selectTWorkOrderList(tWorkOrderForm);
        if(workOrderList.size() != 0){

            for(TWorkOrder workOrder : workOrderList){
                WorkOrderVo workOrderVo = new WorkOrderVo();
                BeanUtils.copyProperties(workOrder, workOrderVo);

                // 获取巡检员姓名
                SysUser appointInspector = sysUserMapper.selectUserById(workOrder.getAppointInspector());
                workOrderVo.setAppointInspectorName(appointInspector.getNickName());

                if(workOrder.getActualInspector() != workOrder.getAppointInspector() && workOrder.getActualInspector() != null){
                    SysUser actualInspector = sysUserMapper.selectUserById(workOrder.getActualInspector());
                    workOrderVo.setActualInspectorName(actualInspector.getNickName());
                } else {
                    workOrderVo.setActualInspectorName(appointInspector.getNickName());
                }

                workOrderVoList.add(workOrderVo);
            }
        }
        return workOrderVoList;
    }


    /**
     * 查询工单基础信息列表
     *
     * @param tWorkOrderForm 工单基础信息
     * @return 工单基础信息
     */
    @Override
    public PageInfo<WorkOrderVo> selectTWorkOrderPage(TWorkOrderForm tWorkOrderForm) throws Exception
    {
        List<TWorkOrder> workOrderList = tWorkOrderMapper.selectTWorkOrderList(tWorkOrderForm);
        PageInfo<WorkOrderVo> pageVo = PageInfoUtil.pageInfo2PageInfoDTO(new PageInfo<>(workOrderList),WorkOrderVo.class);
        if(pageVo.getList().size() != 0){

            for(WorkOrderVo workOrder : pageVo.getList()){

                // 获取巡检员姓名
                SysUser appointInspector = sysUserMapper.selectUserById(workOrder.getAppointInspector());
                workOrder.setAppointInspectorName(appointInspector.getNickName());

                if(workOrder.getActualInspector() != workOrder.getAppointInspector() && workOrder.getActualInspector() != null){
                    SysUser actualInspector = sysUserMapper.selectUserById(workOrder.getActualInspector());
                    workOrder.setActualInspectorName(actualInspector.getNickName());
                } else {
                    workOrder.setActualInspectorName(appointInspector.getNickName());
                }
            }
        }
        return pageVo;
    }

    /**
     * 代办工单
     * @param userId
     * @return
     */
    @Override
    public PageInfo<TWorkOrder> selectWaitingWorkOrder(String userId,Integer type,String searchStr,Integer waitingtype){
        List<TWorkOrder> workOrderList = tWorkOrderMapper.selectWaitingWorkOrder(userId,type,searchStr,waitingtype);
        for(TWorkOrder t :workOrderList){
            if(t.getOrderType().equals("3")){
                String address = tDeviceAlarmMapper.selectAddressByOrderId(t.getOrderId());
                t.setAddress(address);
            }
            if(t.getOrderType().equals("1")){
                t.setLatitude(tInspectionDataMapper.selectFinishTInspectionData(t.getResourceId())+"");
                TInspectionPlan plan = tInspectionPlanMapper.selectTInspectionPlanById(t.getResourceId());
                if(plan!=null){
                    t.setLongitude((plan.getDeviceIds().split(",").length/2)+"");
                }
            }
        }
        PageInfo<TWorkOrder> pageInfo = new PageInfo<>(workOrderList);
        return pageInfo;
    }
    /**
     * 新增工单基础信息
     * 
     * @param tWorkOrder 工单基础信息
     * @return 结果
     */
    @Override
    public String insertTWorkOrder(TWorkOrder tWorkOrder) throws Exception
    {
        String orderId = tWorkOrderMapper.getWorkOrderId();
        int resourceId = tWorkOrder.getResourceId();
        tWorkOrder.setOrderId(orderId);
        tWorkOrder.setOrderStatus("0");
        tWorkOrder.setAllotTime(DateUtils.getNowDate());

        if("1".equals(tWorkOrder.getOrderType())){
            // 修改巡检计划状态为已下发
            TInspectionPlan plan = new TInspectionPlan();
            plan.setPlanId(resourceId);
            plan.setOrderId(orderId);
            plan.setPlanStatus("1");
            plan.setUpdateTime(DateUtils.getNowDate());
            tInspectionPlanMapper.updateTInspectionPlan(plan);

        } else if ("2".equals(tWorkOrder.getOrderType())) {
            THiddenTrouble trouble = new THiddenTrouble();
            trouble.setTroubleId(resourceId);
            trouble.setOrderId(orderId);
            trouble.setUpdateTime(DateUtils.getNowDate());
            tHiddenTroubleMapper.updateTHiddenTrouble(trouble);

        } else if ("3".equals(tWorkOrder.getOrderType())) {
            TDeviceAlarm alarm = new TDeviceAlarm();
            alarm.setAlarmId(resourceId);
            alarm.setOrderId(orderId);
            alarm.setUpdateTime(DateUtils.getNowDate());
            tDeviceAlarmMapper.updateTDeviceAlarm(alarm);
        }

        tWorkOrderMapper.insertTWorkOrder(tWorkOrder);
        return orderId;
    }

    /**
     * 修改工单基础信息
     * 
     * @param tWorkOrder 工单基础信息
     * @return 结果
     */
    @Override
    public int updateTWorkOrder(TWorkOrder tWorkOrder) throws Exception
    {
        if("1".equals(tWorkOrder.getOrderStatus())){

            int planId = tWorkOrder.getResourceId();
            // 修改巡检计划状态为进行中
            TInspectionPlan plan = new TInspectionPlan();
            plan.setPlanId(planId);
            plan.setPlanStatus("2");
            plan.setUpdateTime(DateUtils.getNowDate());
            tInspectionPlanMapper.updateTInspectionPlan(plan);

            tWorkOrder.setActualTime(DateUtils.getNowDate());

        } else if ("3".equals(tWorkOrder.getOrderStatus())){

            int planId = tWorkOrder.getResourceId();
            // 修改巡检计划状态为已完成
            TInspectionPlan plan = new TInspectionPlan();
            plan.setPlanId(planId);
            plan.setPlanStatus("3");
            plan.setUpdateTime(DateUtils.getNowDate());
            tInspectionPlanMapper.updateTInspectionPlan(plan);

        }
        tWorkOrder.setUpdateTime(DateUtils.getNowDate());
        return tWorkOrderMapper.updateTWorkOrder(tWorkOrder);
    }

    /**
     * 批量删除工单基础信息
     * 
     * @param orderIds 需要删除的工单基础信息ID
     * @return 结果
     */
    @Override
    public int deleteTWorkOrderByIds(String[] orderIds)
    {
        return tWorkOrderMapper.deleteTWorkOrderByIds(orderIds);
    }

    /**
     * 删除工单基础信息信息
     * 
     * @param orderId 工单基础信息ID
     * @return 结果
     */
    @Override
    public int deleteTWorkOrderById(String orderId)
    {
        return tWorkOrderMapper.deleteTWorkOrderById(orderId);
    }
    @Override
    public TWorkOrder orderDtail(String orderId){
        TWorkOrder  order = tWorkOrderMapper.selectTWorkOrderById(orderId);
        return   tWorkOrderMapper.orderdtail(orderId,order.getOrderType());
    }
}
