package com.xhpc.activity.service.impl;

import com.xhpc.activity.domain.XhpcStationDeviceDomain;
import com.xhpc.activity.domain.XhpcWorkOrderDomain;
import com.xhpc.activity.domain.XhpcWorkOrderImageDomain;
import com.xhpc.activity.domain.XhpcWorkOrderPushMessageDomain;
import com.xhpc.activity.domain.XhpcWorkOrderUserDomain;
import com.xhpc.activity.domain.XhpcWorkTypeDictDomain;
import com.xhpc.activity.domain.XhpcWorkUserDomain;
import com.xhpc.activity.mapper.XhpcStationDeviceMapper;
import com.xhpc.activity.mapper.XhpcWorkOrderImageMapper;
import com.xhpc.activity.mapper.XhpcWorkOrderMapper;
import com.xhpc.activity.mapper.XhpcWorkOrderPushMessageMapper;
import com.xhpc.activity.service.WorkOrderService;
import com.xhpc.activity.service.WorkTypeService;
import com.xhpc.activity.service.WorkUserService;
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.common.security.service.TokenService;
import com.xhpc.common.util.UserTypeUtil;
import com.xhpc.system.api.domain.SysUser;
import com.xhpc.system.api.model.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@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;
    @Resource
    WorkTypeService typeService;
    @Autowired
    private TokenService tokenService;
    @Override
    public List<Map<String, Object>> getOrderPage(Map<String, Object> params) {
        LoginUser loginUser = tokenService.getLoginUser();
        Long sysUserId = loginUser.getUserid();
        SysUser sysUser = loginUser.getSysUser();
        //获取登陆用户
        if(!UserTypeUtil.SYS_USER_TYPE_ADMIN.equals(sysUser.getUserId())){
            if(UserTypeUtil.SYS_USER_TYPE_ONE.equals(sysUser.getUserType())){
                Long logOperatorId = sysUser.getOperatorId();
                params.put("type", 1);
                params.put("userId", logOperatorId);

                //运营商看自己的场站
                return orderMapper.findOrderListByParams(params);
            }else{
                params.put("type", 2);
                params.put("userId", sysUserId);
                //查询赋值的场站
                return orderMapper.findOrderListByParams(params);
            }
        }else{
            params.put("type", 0);
            params.put("userId", sysUserId);
            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);

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

        // 绑定人员
        if (domain.getUserList() != null && !domain.getUserList().isEmpty()) {
            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);

        if (domain.getQuestionImgList() != null && !domain.getQuestionImgList().isEmpty()) {
            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);
            }
        }

        if (domain.getUserList() != null && !domain.getUserList().isEmpty()) {
            // 更新处理人
            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) {
        // 是否自动派送
        XhpcWorkTypeDictDomain typeDictDomain = typeService.getInfoByPk(domain.getType());
        if (typeDictDomain != null) {
            if (typeDictDomain.getAutoSend() == 1 && domain.getUserList().isEmpty()) {
                XhpcWorkUserDomain userDomain = new XhpcWorkUserDomain();
                userDomain.setWorkUserId(Long.parseLong(typeDictDomain.getUserId() + ""));
                domain.getUserList().add(userDomain);
                domain.setStatus(Short.valueOf("1"));
            }

            if (typeDictDomain.getAutoRun() == 1) {
                domain.setStatus(Short.valueOf("1"));
            }
        }
        if (StringUtils.isNotEmpty(domain.getSerialNumber())) {
            XhpcStationDeviceDomain deviceDomain = deviceMapper.selectBySerialNumber(domain.getSerialNumber());
            domain.setStationId(deviceDomain.getStationId());
        }
        if (domain.getWorkOrderId() == null || domain.getWorkOrderId() < 1L) {
            insertDomain(domain);
        } else {
            updateDomain(domain);
        }
        return true;
    }


    @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) {
        // 是否自动派送
        XhpcWorkTypeDictDomain typeDictDomain = typeService.getInfoByPk(domain.getType());
        if (typeDictDomain != null) {
            if (typeDictDomain.getAutoSend() == 1 && domain.getUserList().isEmpty()) {
                XhpcWorkUserDomain userDomain = new XhpcWorkUserDomain();
                userDomain.setWorkUserId(Long.parseLong(typeDictDomain.getUserId() + ""));
                domain.getUserList().add(userDomain);
                domain.setStatus(Short.valueOf("1"));
            }

            if (typeDictDomain.getAutoRun() == 1) {
                domain.setStatus(Short.valueOf("1"));
            }
        }

        if (StringUtils.isNotEmpty(domain.getSerialNumber())) {
            XhpcStationDeviceDomain deviceDomain = deviceMapper.selectBySerialNumber(domain.getSerialNumber());
            domain.setStationId(deviceDomain.getStationId());
        }

        if (domain.getWorkOrderId() == null || domain.getWorkOrderId() < 1L) {
            insertDomain(domain);
        } else {
            updateDomain(domain);
        }
        return true;
    }


    @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, String reason, String stationId, String deviceType, String serialNumber) {
        try {
            XhpcWorkOrderDomain domain = new XhpcWorkOrderDomain();
            domain.setType(Integer.parseInt(type));
            domain.setTitle(title);
            domain.setContent(content);
            Date date = new Date(System.currentTimeMillis());
            domain.setFaultTime(date);
            domain.setContent(content);
            domain.setCreateTime(date);
            if (stationId != null && !"".equals(stationId)) {
                domain.setStationId(Long.valueOf(stationId));
            }
            if (deviceType != null && !"".equals(deviceType)) {
                domain.setDeviceType(deviceType);
            }
            if (serialNumber != null && !"".equals(serialNumber)) {
                domain.setSerialNumber(serialNumber);
                XhpcStationDeviceDomain deviceDomain = deviceMapper.selectBySerialNumber(domain.getSerialNumber());
                domain.setStationId(deviceDomain.getStationId());
            }
            insertDomain(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);
    }

}
