package com.mortals.xhx.daemon.task;

import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.service.ITask;
import com.mortals.framework.service.ITaskExcuteService;
import com.mortals.framework.util.HttpUtil;
import com.mortals.framework.util.StringUtils;
import com.mortals.xhx.base.system.param.service.ParamService;
import com.mortals.xhx.module.staff.model.StaffCareEntity;
import com.mortals.xhx.module.staff.model.StaffEntity;
import com.mortals.xhx.module.staff.service.StaffCareService;
import com.mortals.xhx.module.staff.service.StaffService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

import static com.mortals.xhx.common.key.ParamKey.STAFF_CARE_BIRTHDAY_SEND;
import static com.mortals.xhx.common.key.ParamKey.STAFF_CARE_ENTRYDATE_SEND;

/**
 * 员工关怀短信发送
 */
@Slf4j
@Service("SendStaffCareSMSTask")
public class SendStaffCareSMSTaskImpl implements ITaskExcuteService {

    @Autowired
    private StaffCareService staffCareService;
    @Autowired
    private ParamService paramService;
    @Autowired
    private StaffService staffService;
    @Value("${sms.smsSendUrl:http://sms.wx3.com.cn/api/index/index}")
    private String smsApiUrl;
    @Value("${sms.apiId:ADsUXLrS81vZDU95}")
    private String appid;
    /**
     * 短信模板ID
     **/
    private static String SMS_TPYE = "44";

    @Override
    public void excuteTask(ITask task) throws AppException {
        Calendar calendar = Calendar.getInstance();
        int month = calendar.get(Calendar.MONTH)+1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        if(month==1 && day==1){
            //每年1月1日重置关怀短信发送状态
            staffCareService.getDao().initSendStatus();
        }
        StaffCareEntity query =  new StaffCareEntity();
        query.setMonth(month);
        query.setDay(day);
        String StaffCareBirthdaySend = paramService.getValueByKey(STAFF_CARE_BIRTHDAY_SEND);
        if(StringUtils.isEmpty(StaffCareBirthdaySend)){
            StaffCareBirthdaySend="1";
        }
        String StaffCareEntryDateSend = paramService.getValueByKey(STAFF_CARE_ENTRYDATE_SEND);
        if(StringUtils.isEmpty(StaffCareEntryDateSend)){
            StaffCareEntryDateSend="1";
        }
        List<StaffCareEntity> staffCareList = staffCareService.getStaffCareList(query);
        List<StaffCareEntity> updateList = new ArrayList<>();
        if(StaffCareBirthdaySend.equals("1")) {
            query.setCareType(1);
            if (CollectionUtils.isNotEmpty(staffCareList)) {
                for (StaffCareEntity item : staffCareList) {
                    StaffEntity staffEntity = staffService.getCache(item.getStaffId().toString());
                    if (staffEntity != null) {
                        String mobileNumber = staffEntity.getPhoneNumber();
                        if (StringUtils.isEmpty(mobileNumber)) {
                            continue;
                        }
                        if (PhoneUtil.isPhone(mobileNumber)) {
                            Map<String, String> params = new HashMap<>();
                            params.put("appid", appid);
                            params.put("phone", mobileNumber);
                            params.put("type", SMS_TPYE);

                            String[] json = new String[1];
                            json[0] = String.format("亲爱的[%s]，祝你生日快乐！愿你在新的一岁里健康、快乐、成功！公司永远是你坚强的后盾。", item.getStaffName());
                            params.put("json", JSONObject.toJSON(json).toString());
                            try {
                                String resp = HttpUtil.doPost(smsApiUrl, params);
                                JSONObject respJson = JSONObject.parseObject(resp);
                                if (respJson.getIntValue("code") == 0) {
                                    log.info("短信发送失败:" + respJson.getString("message"));
                                } else {
                                    item.setSendStatus(1);
                                    item.setExcuteTime(new Date());
                                    item.setUpdateTime(new Date());
                                    updateList.add(item);
                                }

                            } catch (Exception e) {
                                log.error("短信发送异常", e);
                            }
                        }
                    }

                }
            }
        }
        if(StaffCareEntryDateSend.equals("1")) {
            query.setCareType(2);
            staffCareList = staffCareService.getStaffCareList(query);
            for (StaffCareEntity item : staffCareList) {
                StaffEntity staffEntity = staffService.getCache(item.getStaffId().toString());
                if (staffEntity != null) {
                    String mobileNumber = staffEntity.getPhoneNumber();
                    if (StringUtils.isEmpty(mobileNumber)) {
                        continue;
                    }
                    if (PhoneUtil.isPhone(mobileNumber)) {
                        Map<String, String> params = new HashMap<>();
                        params.put("appid", appid);
                        params.put("phone", mobileNumber);
                        params.put("type", SMS_TPYE);

                        String[] json = new String[1];
                        json[0] = String.format("亲爱的[%s]，入职周年快乐！愿你一路走来的每一步都铺就了成功的基石，未来继续高飞，前程似锦！", item.getStaffName());
                        params.put("json", JSONObject.toJSON(json).toString());
                        try {
                            String resp = HttpUtil.doPost(smsApiUrl, params);
                            JSONObject respJson = JSONObject.parseObject(resp);
                            if (respJson.getIntValue("code") == 0) {
                                log.info("短信发送失败:" + respJson.getString("message"));
                            } else {
                                item.setSendStatus(1);
                                item.setExcuteTime(new Date());
                                item.setUpdateTime(new Date());
                                updateList.add(item);
                            }

                        } catch (Exception e) {
                            log.error("短信发送异常", e);
                        }
                    }
                }
            }
        }
        if(updateList.size()>0){
            staffCareService.update(updateList);
        }
    }

    @Override
    public void stopTask(ITask task) throws AppException {

    }
}
