package com.xhpc.activity.service.impl;

import com.xhpc.common.api.SmsService;
import com.xhpc.common.core.domain.R;
import com.xhpc.common.core.exception.CustomException;
import com.xhpc.common.core.utils.StringUtils;
import com.xhpc.activity.domain.*;
import com.xhpc.activity.mapper.*;
import com.xhpc.activity.service.WorkOrderService;
import com.xhpc.activity.service.WorkUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Slf4j
@Service
@Transactional
public class WorkOrderServiceImpl implements WorkOrderService {

    @Resource
    XhpcWorkOrderMapper orderMapper;

    @Resource
    XhpcStationDeviceMapper deviceMapper;

    @Resource
    XhpcWorkOrderPushMessageMapper messageMapper;

    @Resource
    XhpcWorkOrderImageMapper imageMapper;

    @Resource
    SmsService smsService;

    @Resource
    WorkUserService workUserService;

    @Override
    public List<Map<String, Object>> getOrderPage(Map<String,Object> params){
        return orderMapper.findOrderListByParams(params);
    }

    @Override
    public XhpcWorkOrderDomain selectOrderById(Long orderId){

        XhpcWorkOrderDomain orderDomain = orderMapper.selectByPrimaryKey(orderId);
        orderDomain.setUserList(workUserService.findByOrderId(orderId));
        orderDomain.setQuestionImgList(imageMapper.selectByOrderIdAndType(orderId, 1));
        orderDomain.setReplyImgList(imageMapper.selectByOrderIdAndType(orderId, 2));

        return orderDomain;
    }


    private Boolean insertDomain(XhpcWorkOrderDomain domain){
        List<XhpcWorkUserDomain> userDomains = new ArrayList<>();
        if(domain.getUserList() != null){
            for(XhpcWorkUserDomain userDomain: domain.getUserList()){
                userDomain = workUserService.findByPk(userDomain.getWorkUserId());
                userDomains.add(userDomain);
            }
            domain.setUserList(userDomains);
        }

        if(StringUtils.isNotEmpty(domain.getSerialNumber())){
            XhpcStationDeviceDomain deviceDomain = deviceMapper.selectStationGunDeviceBySerialNumber(domain.getSerialNumber());
            if (deviceDomain == null){
                throw new RuntimeException("设备编码不存在");
            }
        }

        orderMapper.insertSelective(domain);

        // 上传文件
        for(XhpcWorkOrderImageDomain imageDomain : domain.getQuestionImgList()){
            imageDomain.setOrderId(domain.getWorkOrderId());
            imageDomain.setType(Short.valueOf("1"));
            imageDomain.setDelFlag(Short.valueOf("0"));
            imageMapper.insertSelective(imageDomain);
        }

        // 绑定人员
        List<XhpcWorkOrderUserDomain> orderUserDomainList = new ArrayList<>();
        StringBuilder userIdList = new StringBuilder();
        for (XhpcWorkUserDomain userDomain: domain.getUserList()){
            XhpcWorkOrderUserDomain orderUserDomain = new XhpcWorkOrderUserDomain();
            orderUserDomain.setOrderId(domain.getWorkOrderId());
            orderUserDomain.setUserId(userDomain.getWorkUserId());
            orderUserDomainList.add(orderUserDomain);
            userIdList.insert(0, userDomain.getWorkUserId() + ",");
        }

        if(orderUserDomainList.size() > 0){
            orderMapper.insertOrderUser(orderUserDomainList);
        }
        if(StringUtils.isNotEmpty(userIdList.toString()) && domain.getStatus() != null && domain.getStatus()==1){
            sendSms(userIdList.toString(), domain.getWorkOrderId().toString());
        }
        return true;
    }

    private Boolean updateDomain(XhpcWorkOrderDomain domain){
        orderMapper.updateByPrimaryKeySelective(domain);

        List<Long> imageIds = imageMapper.selectImageIdByOrderIdAndType(domain.getWorkOrderId(), 1);

        for (XhpcWorkOrderImageDomain imageDomain: domain.getQuestionImgList()){
            if( imageDomain.getOrderImageId() == null || StringUtils.isEmpty(imageDomain.getOrderImageId().toString())){
                imageDomain.setOrderId(domain.getWorkOrderId());
                imageDomain.setType(Short.valueOf("1"));
                imageDomain.setDelFlag(Short.valueOf("0"));
                imageMapper.insertSelective(imageDomain);
            } else {
                if(imageIds.contains(imageDomain.getOrderImageId())){
                    imageIds.remove(imageDomain.getOrderImageId());
                }
            }
        }
        if(imageIds.size() > 0){
            imageMapper.deleteByImageIds(imageIds);
        }

        // 更新处理人
        StringBuilder userIdList = new StringBuilder();
        orderMapper.deleteOrderUserByOrderId(domain.getWorkOrderId());
        List<XhpcWorkOrderUserDomain> orderUserDomainList = new ArrayList<>();
        for(XhpcWorkUserDomain userDomain: domain.getUserList()){
            XhpcWorkOrderUserDomain orderUserDomain = new XhpcWorkOrderUserDomain();
            orderUserDomain.setOrderId(domain.getWorkOrderId());
            orderUserDomain.setUserId(userDomain.getWorkUserId());
            orderUserDomainList.add(orderUserDomain);

            userIdList.insert(0, userDomain.getWorkUserId() + ",");
        }

        if(orderUserDomainList.size() > 0){
            orderMapper.insertOrderUser(orderUserDomainList);
        }

        if(StringUtils.isNotEmpty(userIdList.toString()) && domain.getStatus() != null && domain.getStatus()==1){
            sendSms(userIdList.toString(), domain.getWorkOrderId().toString());
        }
        return true;
    }


    @Override
    public Boolean updateOrder(XhpcWorkOrderDomain domain){
        if(domain.getWorkOrderId() == null || domain.getWorkOrderId() < 1L){
            return insertDomain(domain);
        } else {
            return updateDomain(domain);
        }
    }


    @Override
    public Boolean replyOrder(XhpcWorkOrderDomain domain){
        XhpcWorkOrderDomain orderDomain = orderMapper.selectByPrimaryKey(domain.getWorkOrderId());
        if(orderDomain == null){
            throw new RuntimeException("订单不存在");
        }

        orderDomain.setReason(domain.getReason());
        orderDomain.setDisposalMethod(domain.getDisposalMethod());
        orderDomain.setStatus(Short.valueOf("2"));
        orderDomain.setRemark(domain.getRemark());
        orderMapper.updateByPrimaryKeySelective(orderDomain);

        for(XhpcWorkOrderImageDomain imageDomain: domain.getReplyImgList()){
            imageDomain.setOrderId(domain.getWorkOrderId());
            imageDomain.setType(Short.valueOf("2"));
            imageDomain.setDelFlag(Short.valueOf("0"));
            imageMapper.insertSelective(imageDomain);
        }
        return true;
    }


    @Override
    public Boolean insertOrder(XhpcWorkOrderDomain domain){
        if(domain.getWorkOrderId() == null || domain.getWorkOrderId() < 1L){
            return insertDomain(domain);
        } else {
            return updateDomain(domain);
        }
    }


    @Override
    public Boolean deleteOrder(Long orderId) throws Exception {
        XhpcWorkOrderDomain domain = orderMapper.selectByPrimaryKey(orderId);
        if(domain == null){
            throw new Exception("工单不存在");
        }
        orderMapper.deleteByPrimaryKey(orderId);
        orderMapper.deleteOrderUserByOrderId(orderId);
        return true;
    }

    @Override
    public Boolean addNewOrder(String type, String title, String content, Date faultTime, String reason) {
        try{
            XhpcWorkOrderDomain domain =new XhpcWorkOrderDomain();
            domain.setType(Short.parseShort(type));
            domain.setTitle(title);
            domain.setContent(content);
            domain.setFaultTime(faultTime);
            domain.setContent(content);
            domain.setCreateTime(faultTime);
            Short s =0;
            domain.setStatus(s);
            orderMapper.insertSelective(domain);

        }catch (Exception e){
            e.printStackTrace();
        }

        return true;
    }

    @Override
    public R workOrderMessage(Integer type, String time) {
        int i = orderMapper.workOrderMessage(type, time);
        if(i>0){
            return R.fail();
        }
        return R.ok();
    }


    private void sendSms(String userIds, String orderId){

        String phoneList = workUserService.getPhoneListByUserIds(userIds);
        if(StringUtils.isEmpty(phoneList)){
            throw new CustomException("没有待发送短信");
        }

        HashMap<String, String> paramMap = new HashMap<>();
        paramMap.put("orderNo", orderId);
        paramMap.put("phone", phoneList);
        paramMap.put("content", "【小华充电】您好，您有新的工单(工单号:"+ orderId +")待处理，请及时登陆后台查看并处理，谢谢。");
        R r = smsService.sendNotice(paramMap);

        XhpcWorkOrderPushMessageDomain messageDomain = new XhpcWorkOrderPushMessageDomain();
        messageDomain.setContent(paramMap.get("content"));
        messageDomain.setTarget(phoneList);
        messageDomain.setType(Short.valueOf("1"));
        if (r!= null && r.getCode() != 200){
            messageDomain.setFailMsg("发送失败");
            messageDomain.setStatus(Short.valueOf("2"));
        } else {
            messageDomain.setFailMsg("发送成功");
            messageDomain.setStatus(Short.valueOf("1"));
        }
        messageMapper.insertSelective(messageDomain);
    }

}
