/**
 *
 */
package com.sifang.modules.taskdispatch.dao;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.flowable.entity.ItemManage;
import com.sifang.modules.sys.common.persistence.BaseDao;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.util.SqlBuilder;
import com.sifang.modules.taskdispatch.constant.ReviewDispatchConst;
import com.sifang.modules.taskdispatch.entity.CrmReviewDispatch;
import com.sifang.modules.taskdispatch.service.autod.ItemTaskEventBus;
import com.sifang.modules.taskdispatch.util.ItemDispatchUtil;
import com.sifang.modules.taskdispatch.util.TimeDurationInfo;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.SQLQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 待办派工DAO接口
 * @author gaols
 */
@Repository
public class CrmReviewDispatchDao extends BaseDao<CrmReviewDispatch> {

    @Autowired
    ItemTaskEventBus listener;

    @Autowired
    CrmReviewGroupDao reviewGroupDao;

    public void listData(LayuiPage<Record> page, Map<String, String> params) {
        SqlBuilder sb = new SqlBuilder();
        sb.line("select * from crm_review_dispatch");
        sb.limit(page.getPage(), page.getLimit());
        List<Record> records = Db.find(sb.build(), sb.params());
        page.setData(records);
    }

    public void listDataCount(LayuiPage<Record> page, Map<String, String> params) {
        SqlBuilder sb = new SqlBuilder();
        sb.limit(page.getPage(), page.getLimit());
        page.setCount(Db.queryLong(sb.build(), sb.params()));
    }

    public int updateAsReAssigned(Date reDispatchTime, String dispatchId) {
        SqlBuilder sb = new SqlBuilder()
                .line("update crm_review_dispatch set status=:st,redispatch_time=:time")
                .line("where id=:id and status=:prev and redispatch_time is null");
        SQLQuery query = getSession().createSQLQuery(sb.build());
        query.setParameter("st", ReviewDispatchConst.STATUS_REDISPATCHED);
        query.setParameter("time", reDispatchTime);
        query.setParameter("id", dispatchId);
        query.setParameter("prev", ReviewDispatchConst.STATUS_ONGOING);
        return query.executeUpdate();
    }

    public void markDispatchFinish(ItemManage item) {
        if (StringUtils.isNotBlank(item.getLatestDispatchId())) {
            SqlBuilder sb = new SqlBuilder()
                    .line("update crm_review_dispatch set status=:st,finish_time=:time")
                    .line("where id=:id and finish_time is null");
            SQLQuery query = getSession().createSQLQuery(sb.build());
            query.setParameter("st", ReviewDispatchConst.STATUS_FINISHED);
            query.setParameter("time", item.getEndTime());
            query.setParameter("id", item.getLatestDispatchId());
            query.executeUpdate();

            // try to find user related group info
            Record group = reviewGroupDao.findByUserId(item.getAssignAuditUserId());
            if(group != null) {
                String st1 = group.getStr("work_time_st1");
                String st2 = group.getStr("work_time_st2");
                String end1 = group.getStr("work_time_end1");
                String end2 = group.getStr("work_time_end2");
                List<String> timeSpans = new ArrayList<>();
                if (StringUtils.isNotBlank(st1)) {
                    timeSpans.add(String.format("%s-%s", st1, end1));
                }
                if (StringUtils.isNotBlank(st2)) {
                    timeSpans.add(String.format("%s-%s", st2, end2));
                }
                Record groupLeader = reviewGroupDao.getGroupLeader(group.getStr("id"));
                if (groupLeader != null) {
                    item.setLeaderMemberId(groupLeader.getStr("id"));
                    item.setLeaderName(groupLeader.getStr("name"));
                }
                if (!CollectionUtils.isEmpty(timeSpans)) {
                    TimeDurationInfo dispatchDuration = ItemDispatchUtil.duration(item.getAssignTime(), item.getEndTime(), timeSpans);
                    item.setDispatchDuration(dispatchDuration.getHours() * 60 + dispatchDuration.getMinutes());
                    TimeDurationInfo taskDuration = ItemDispatchUtil.duration(item.getCreateTime(), item.getEndTime(), timeSpans);
                    item.setTaskDuration(taskDuration.getHours() * 60 + taskDuration.getMinutes());
                    item.setGroupId(group.getStr("id"));
                    item.setWorkTimeSt1(group.getStr("work_time_st1"));
                    item.setWorkTimeSt2(group.getStr("work_time_st2"));
                    item.setWorkTimeEnd1(group.getStr("work_time_end1"));
                    item.setWorkTimeEnd2(group.getStr("work_time_end2"));
                }
                notifyUserTaskDone(item.getAssignAuditUserId());
            }
        }
    }

    private void notifyUserTaskDone(String userId) {
        listener.notifyItemTaskFinish(userId);
    }
}
