package com.sqx.modules.message.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Query;
import com.sqx.common.utils.Result;
import com.sqx.map.CommonMapUtils;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.artificer.entity.Artificer;
import com.sqx.modules.artificer.service.ArtificerService;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.message.dao.MessageInfoDao;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.message.service.MessageService;
import com.sqx.modules.risk.entity.Risk;
import com.sqx.modules.risk.service.RiskService;
import com.sqx.modules.utils.AppNotifyUtil;
import com.sqx.modules.utils.HttpClientUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 消息
 */
@Service
public class MessageServiceImpl extends
        ServiceImpl<MessageInfoDao, MessageInfo> implements MessageService {

    @Autowired
    private MessageInfoDao messageInfoDao;
    @Autowired
    private ArtificerService artificerService;
    @Autowired
    private RiskService riskService;
    @Autowired
    private UserService userService;
    @Autowired
    private CommonInfoService commonInfoService;

    @Override
    public Result selectCityList(Integer page,Integer limit,String content){
        IPage<Map<String, Object>> mapIPage = messageInfoDao.selectCityList(new Page<>(page, limit), content);
        return Result.success().put("data",new PageUtils(mapIPage));
    }

    @Override
    public Result auditMessage(String ids, Integer status, String auditContent){
        for(String id:ids.split(",")){
            MessageInfo messageInfo = baseMapper.selectById(Long.parseLong(id));
            if("0".equals(messageInfo.getType())){
                if(status==1){
                    Artificer artificer = artificerService.selectArtificerByUserId(Long.parseLong(messageInfo.getByUserId()));
                    MessageInfo type = baseMapper.selectById(messageInfo.getTypeId());
                    BigDecimal subtract = artificer.getCreditScore().subtract(new BigDecimal(type.getContent()));
                    artificer.setCreditScore(subtract);
                    artificerService.updateById(artificer);
                    MessageInfo messageInfo1=new MessageInfo();
                    messageInfo1.setState("8");
                    messageInfo1.setTitle(type.getTitle());
                    messageInfo1.setContent("扣除信誉分："+type.getContent());
                    messageInfo1.setUserId(messageInfo.getByUserId());
                    saveBody(messageInfo1);
                    UserEntity byId = userService.getById(artificer.getUserId());
                    userService.sendMsg(byId.getPhone(),"touSu");
                    String value = commonInfoService.findOne(385).getValue();
                    BigDecimal minScore = new BigDecimal(value);
                    if(artificer.getCreditScore().doubleValue()<minScore.doubleValue()){
                        artificer.setStatus(2);
                    }
                    artificerService.updateById(artificer);
                }
                messageInfo.setAuditContent(auditContent);
                messageInfo.setType(String.valueOf(status));
                baseMapper.updateById(messageInfo);

            }else if(StringUtils.isEmpty(messageInfo.getType())){
                messageInfo.setAuditContent(auditContent);
                messageInfo.setType(String.valueOf(status));
                baseMapper.updateById(messageInfo);
            }
        }
        return Result.success();
    }


    @Override
    public PageUtils selectMessageList(Map<String,Object> params){
        Long userId = (Long)params.get("userId");
        Integer state = (Integer)params.get("state");
        Integer type = (Integer)params.get("type");
        IPage<MessageInfo> page = this.page(
                new Query<MessageInfo>().getPage(params),
                new QueryWrapper<MessageInfo>()
                        .eq(userId!=null,"user_id", userId)
                        .eq(state!=null,"state", state)
                        .eq(type!=null,"type", type).orderByDesc("create_at")
        );
        return new PageUtils(page);
    }

    @Override
    public PageUtils selectMessageLists(Map<String,Object> params){
        Long userId = (Long)params.get("userId");
        Integer state = (Integer)params.get("state");
        Integer type = (Integer)params.get("type");
        IPage<MessageInfo> page = this.page(
                new Query<MessageInfo>().getPage(params),
                new QueryWrapper<MessageInfo>()
                        .eq(userId!=null,"user_id", userId)
                        .eq(state!=null,"state", state)
                        .eq("is_see", "0")
                        .eq(type!=null,"type", type).orderByDesc("create_at")
        );
        return new PageUtils(page);
    }

    @Override
    public int saveBody(MessageInfo messageInfo){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        messageInfo.setCreateAt(sdf.format(now));
        if(StringUtils.isNotBlank(messageInfo.getState()) && "7".equals(messageInfo.getState())){
            Risk risk=new Risk();
            risk.setUserId(Long.parseLong(messageInfo.getByUserId()));
            risk.setContent("用户被举报："+messageInfo.getContent());
            risk.setRiskType(6);
            risk.setCreateTime(DateUtils.format(new Date()));
            riskService.save(risk);
        }
        if(StringUtils.isNotEmpty(messageInfo.getState()) && "9".equals(messageInfo.getState())){
            String address = CommonMapUtils.getLocationToAddress(messageInfo.getTypeId(), messageInfo.getTypeName());//按坐标获取地理位置
            messageInfo.setContent(address);
            int returncount = messageInfoDao.insert(messageInfo);
            if(returncount == 1) {
                //技师电话通知业务
                //accountId
                String accountId = commonInfoService.findOne(428).getValue();
                //token
                String token = commonInfoService.findOne(429).getValue();
                //templateId 模板id
                String templateId = commonInfoService.findOne(431).getValue();
                //呼救手机号
                String calleeNumber = commonInfoService.findOne(432).getValue();
                //呼叫
                AppNotifyUtil.AppNotify(calleeNumber, accountId, token, templateId);
            }
            return returncount;
        }
        return messageInfoDao.insert(messageInfo);
    }

    @Override
    public Result insertArtificerLocation(MessageInfo messageInfo){
        messageInfo.setState("12");
        Artificer artificer = artificerService.selectArtificerByUserId(Long.parseLong(messageInfo.getUserId()));
        if(artificer!=null){
            UserEntity userEntity = userService.selectUserById(artificer.getUserId());
            if(userEntity!=null && userEntity.getIsAuthentication()!=null || userEntity.getIsAuthentication()==2){
                if(StringUtils.isNotEmpty(messageInfo.getTypeId()) && StringUtils.isNotEmpty(messageInfo.getTypeName())){
                    artificer.setLongitude(messageInfo.getTypeId());
                    artificer.setLatitude(messageInfo.getTypeName());

                    JSONObject adInfo = CommonMapUtils.getLocationToAdInfo(messageInfo.getTypeId(), messageInfo.getTypeName());//根据坐标获取行政区划信息
                    String address = adInfo.getString("address");
                    messageInfo.setContent(address);
                    artificer.setAddress(address);
                    String city = adInfo.getString("city");
                    artificer.setCity(city);

                    artificer.setUpdateTime(DateUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                    artificerService.updateById(artificer);
                    messageInfo.setCreateAt(DateUtils.format(new Date()));
                    baseMapper.insert(messageInfo);
                }else {
                    return Result.error("请检查定位权限");
                }
            }
        }
        return Result.success();
    }


    @Override
    public int update(MessageInfo messageInfo){
        return messageInfoDao.updateById(messageInfo);
    }

    @Override
    public int delete(Long id){
        return messageInfoDao.deleteById(id);
    }

    @Override
    public MessageInfo selectMessageById(Long id){
        return messageInfoDao.selectById(id);
    }

    @Override
    public int updateSendState(Long userId, Integer state) {
        return messageInfoDao.updateSendState(userId, state);
    }

    @Override
    public MessageInfo selectMessageByUserIdAndTime(Long userId,String time){
        return baseMapper.selectOne(new QueryWrapper<MessageInfo>().eq("state",10).eq("user_id",userId).like("create_at",time));
    }

    @Override
    public Result selectSignList(Integer page,Integer limit,String address,String phone,Long userId){
        return Result.success().put("data",new PageUtils(baseMapper.selectSignList(new Page<>(page,limit),address,phone,userId)));
    }

    @Override
    public Result selectArtificerLocation(Integer page,Integer limit,String artificerName,String phone,Long userId){
        return Result.success().put("data",new PageUtils(baseMapper.selectArtificerLocation(new Page<>(page,limit),artificerName,phone,userId)));
    }

    @Override
    public Result selectArtificerScoreList(Integer page,Integer limit,String artificerName,String phone,Long userId){
        return Result.success().put("data",new PageUtils(baseMapper.selectArtificerScoreList(new Page<>(page,limit),artificerName,phone,userId)));
    }

    @Override
    public void sendNoticeByCall(Long userId){
        //技师电话通知业务
        UserEntity byId = userService.getById(userId);
        //accountId
        String accountId = commonInfoService.findOne(428).getValue();
        //token
        String token = commonInfoService.findOne(429).getValue();
        //templateId
        String templateId = commonInfoService.findOne(430).getValue();
        AppNotifyUtil.AppNotify(byId.getPhone(),accountId,token,templateId);
    }

}
