package com.cftech.order.job;

import com.cftech.accounts.model.MpAccountsEntity;
import com.cftech.accounts.model.SysJob;
import com.cftech.accounts.service.JobService;
import com.cftech.accounts.service.MpAccountsService;
import com.cftech.base.org.api.QyMsgUtil;
import com.cftech.base.org.model.Qyuser;
import com.cftech.base.org.service.QyuserService;
import com.cftech.core.sql.Conds;
import com.cftech.core.util.Constants;
import com.cftech.core.util.SpringContextHolder;
import com.cftech.core.util.StringUtils;
import com.cftech.core.util.SystemConfig;
import com.cftech.order.model.Order;
import com.cftech.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 订单跟进提醒 前7天、当天、后7天 关闭提醒
 * Created by 16444 on 2020/11/29.
 */
@Slf4j
public class OrderFollowupRemindJob implements Job {

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        boolean isCluster = Boolean.valueOf(SystemConfig.p.getProperty("quartz.isCluster"));
        if (!isCluster) {
            return;
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Long accounts = Long.parseLong(SystemConfig.p.getProperty("QY_SEND_APPID"));
        MpAccountsService mpAccountsService= SpringContextHolder.getBean(MpAccountsService.class);
        MpAccountsEntity accountsEntity = mpAccountsService.getDetail(accounts);
        Long agenId = Long.parseLong(accountsEntity.getAgentId());
        String msg = SystemConfig.p.getProperty("QY_SEND_SERVICE_FOLLOWUP_MSG");

        Conds orderConds = new Conds();
        orderConds.equal("o.del_flag", Constants.DEL_FLAG_0);
        orderConds.notNull("o.remind_type");
        orderConds.notEqual("o.remind_type", "0");
        OrderService orderService = SpringContextHolder.getBean(OrderService.class);
        List<Order> list = orderService.fetchSearchByPage(orderConds, null, 0, 0);
        for (Order order: list) {
            //未设置提醒或关闭提醒跳出循环
            if (StringUtils.isBlank(order.getRemindType()) || StringUtils.equals(order.getRemindType(), "0")) {
                continue;
            }

            String frequency = order.getTakeFrequency();//药品服用频率
            if (StringUtils.isBlank(frequency) || !frequency.contains("/")) {
                continue;
            }

            try {
                String[] arr = frequency.split("/");
                BigDecimal sum = new BigDecimal(arr[1]);//药品总数
                BigDecimal avg = new BigDecimal(arr[0]);//每日服用数量
                BigDecimal result = sum.divide(avg, 0, BigDecimal.ROUND_HALF_UP);
                Date date = sdf.parse(order.getAcceptExpressDateStr());
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);

                int day = 0;
                if (StringUtils.equals(order.getRemindType(), "1")) {//7天前
                    day = result.intValue() - 7;
                } else if (StringUtils.equals(order.getRemindType(), "2")) {//当天
                    day = result.intValue();
                } else if (StringUtils.equals(order.getRemindType(), "3")) {//7天后
                    day = result.intValue() + 7;
                } else {
                    continue;
                }

                calendar.set(Calendar.MONTH, day);
                date = calendar.getTime();

                Date nowDate = sdf.parse(sdf.format(new Date()));
                if (date.compareTo(nowDate) == 0) {
                    QyuserService qyuserService = SpringContextHolder.getBean(QyuserService.class);
                    Qyuser serverUser = qyuserService.fetchById(order.getServiceId());
                    List<Qyuser> serviceUsers = new ArrayList();
                    serviceUsers.add(serverUser);
                    QyMsgUtil qyMsgUtil = SpringContextHolder.getBean(QyMsgUtil.class);
                    msg += msg + order.getNumber();
                    qyMsgUtil.sendText(accounts, false, serviceUsers, null, null, agenId, msg, false);
                }
            } catch (ParseException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.getMessage();
            }
        }


        //获得明细数据
        JobDataMap jobInfo = context.getJobDetail().getJobDataMap();
        String id = jobInfo.get("uid") == null ? "" : jobInfo.getString("uid");//这个也是ID主键
        log.info("任务ID：" + id);

        //执行更新操作
        if (context.getNextFireTime() != null) {
            log.info("订单跟进提醒任务：下次执行时间=====" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(context.getNextFireTime()) + "==============");
        } else {
            JobService jobService = SpringContextHolder.getBean(JobService.class);
            SysJob sysJob = new SysJob();
            sysJob.setJobuid(id);
            sysJob.setStatus("0");
            jobService.updateStatus(sysJob);
            log.info("订单跟进提醒任务，已执行完成！");
        }
    }




}
