package com.mortals.xhx.module.care.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.framework.util.EntityUtil;
import com.mortals.framework.util.HttpUtil;
import com.mortals.xhx.base.system.user.model.UserEntity;
import com.mortals.xhx.base.system.user.service.UserService;
import com.mortals.xhx.busiz.req.SmsThirdPartyReq;
import com.mortals.xhx.busiz.rsp.ApiSmsResp;
import com.mortals.xhx.common.code.UserType;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.common.key.ParamKey;
import com.mortals.xhx.module.care.dao.CareRecordsDao;
import com.mortals.xhx.module.care.model.*;
import com.mortals.xhx.module.care.service.CareConfigService;
import com.mortals.xhx.module.care.service.CareConstraintService;
import com.mortals.xhx.module.care.service.CareRecordsService;
import com.mortals.xhx.module.notice.model.NoticeEntity;
import com.mortals.xhx.module.notice.service.NoticeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * CareRecordsService
 * 预约关怀记录 service实现
 *
 * @author zxfei
 * @date 2023-04-09
 */
@Service("careRecordsService")
@Slf4j
public class CareRecordsServiceImpl extends AbstractCRUDServiceImpl<CareRecordsDao, CareRecordsEntity, Long> implements CareRecordsService {
    @Autowired
    private UserService userService;
    @Autowired
    private CareConfigService careConfigService;
    @Autowired
    private CareConstraintService careConstraintService;
    @Autowired
    private NoticeService noticeService;


    @Value("${sms.smsSendUrl:http://192.168.0.98:8089/api/index/index}")
    private String smsSendUrl;

    @Value("${sms.apiId:''}")
    private String apiId;


    @Override
    public Rest<String> notice(CareRecordsEntity careRecordsEntity, Context context) {
        UserEntity userEntity = new UserEntity();
        userEntity.setUserType(UserType.SYSTEM.getValue());
        List<UserEntity> userEntities = userService.find(userEntity);
        List<NoticeEntity> noticeList = userEntities.stream().map(user -> {
            NoticeEntity noticeEntity = new NoticeEntity();
            noticeEntity.initAttrValue();
            noticeEntity.setTitle("群众关怀信息");
            noticeEntity.setExpireTime(DateUtils.addHours(new Date(), 1));
            noticeEntity.setUserId(user.getId());
            String content = "";
            noticeEntity.setContent(content);

            noticeEntity.setCreateTime(new Date());
            noticeEntity.setCreateUserId(1L);
            noticeEntity.setCreateUserName("system");

            return noticeEntity;
        }).collect(Collectors.toList());

        if (ObjectUtils.isEmpty(noticeList)) {
            noticeService.save(noticeList);
        }

        return Rest.ok("通知负责人成功");
    }

    @Override
    public Rest<String> toCare(CareRecordsEntity careRecordsEntity, Context context) {
        if (ObjectUtils.isEmpty(careRecordsEntity.getContact())) {
            return Rest.fail("手机号码不存在");

        }
        CareConfigEntity careConfigEntity = careConfigService.selectOne(new CareConfigQuery());
        CareConstraintEntity careConstraintEntity = careConstraintService.selectOne(new CareConstraintQuery().idCard(careRecordsEntity.getIdCard()));
        if (!ObjectUtils.isEmpty(careConstraintEntity)) {
            //校验服务频次
            if (careConstraintEntity.getServiceFrequency() > careConfigEntity.getAlertServiceNum()) {
                //todo 超过服务预警频次
            }
            CareConstraintQuery constraintQuery = new CareConstraintQuery();
            constraintQuery.serviceFrequencyIncrement(1L);
            constraintQuery.setId(careConstraintEntity.getId());
            careConstraintService.update(constraintQuery);
        }

        String resp = null;
        try {
            SmsThirdPartyReq smsThirdPartyReq = new SmsThirdPartyReq();
            smsThirdPartyReq.setAppid(apiId);
            smsThirdPartyReq.setPhone(careRecordsEntity.getContact());
            smsThirdPartyReq.setType(ParamKey.SYS_PARAM_SMS_PERSON_CARE_TYPE);
            smsThirdPartyReq.setJson("[]");

            Map<String, Object> form = BeanUtil.beanToMap(smsThirdPartyReq, false, true);
            log.info("sms req sendUrl:{}     params:{}", smsSendUrl, JSON.toJSONString(form));
            resp = cn.hutool.http.HttpUtil.post(smsSendUrl, form);
            log.info("sms resp:{}", resp);
            // resp = HttpUtil.doPost(smsSendUrl, form);
            ApiSmsResp<Void> apiSmsResp = JSON.parseObject(resp, new TypeReference<ApiSmsResp<Void>>() {
            });
            //更新发送数量
            CareRecordsQuery condition = new CareRecordsQuery();
            condition.setId(careRecordsEntity.getId());
            condition.setSmsCountIncrement(1);
            condition.setCareCount(1);
            if (apiSmsResp.getCode() == YesNoEnum.YES.getValue()) {
                this.update(condition, context);
                return Rest.ok();
            } else {
                this.update(condition, context);
                return Rest.fail(apiSmsResp.getMessage());
            }

        } catch (Exception e) {
            log.error("发送短信异常:", e);
            return Rest.fail(e.getMessage());
        }
    }
}