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

import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.Service.CustomerEntryService;
import com.sifang.modules.flowable.service.ItemManageService;
import com.sifang.modules.sunshine.SystemSetting.dao.CrmPlatformEmpDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmPlatformEmployee;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.web.BaseController;
import com.sifang.modules.taskdispatch.dao.CrmReviewGroupMemberDao;
import com.sifang.modules.taskdispatch.service.CrmReviewGroupMemberService;
import com.sifang.modules.taskdispatch.service.autod.ItemTaskEventBus;
import com.sifang.modules.taskdispatch.util.BatchItem;
import com.sifang.modules.taskdispatch.util.ReviewGroupUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 审核组成员信息Controller
 * @author gaols
 */
@Controller
@RequestMapping(value = "${adminPath}/taskdispatch/crmReviewGroupMember")
public class CrmReviewGroupMemberController extends BaseController {

    @Autowired
    private CrmReviewGroupMemberService crmReviewGroupMemberService;
    @Autowired
    CrmPlatformEmpDao platformEmpDao;
    @Autowired
    CrmReviewGroupMemberDao reviewGroupMemberDao;
    @Autowired
    ItemManageService itemManageService;
    @Autowired
    CustomerEntryService entryService;
    @Autowired
    ItemTaskEventBus itemTaskEventBus;

    @RequestMapping(value = {"listData"})
    @ResponseBody
    public String listData(HttpServletRequest request) {
        LayuiPage<Record> page = new LayuiPage<>(request);
        Map<String, String> params = getParams(request);
        crmReviewGroupMemberService.listData(page, params);
        return page.renderJson();
    }

    @RequestMapping(value = {"signin"})
    @ResponseBody
    public Result signin(HttpServletRequest request) {
        User user = UserUtils.getUser();
        try {
            String signinTime = crmReviewGroupMemberService.signin(user.getId());
            itemTaskEventBus.notifyUserSignIn(user.getId());
            Result<String> ret = new Result<>();
            ret.setOk();
            ret.setData(signinTime);
            return ret;
        } catch (BusinessException ex) {
            return Result.fail(ex.getMessage());
        }
    }

    @RequestMapping(value = {"signinPage"})
    public String signinPage(HttpServletRequest request) {
        return "modules/yangguang/systemSetting/flowable/item/projsignin";
    }

    @RequestMapping(value = {"signoutPage"})
    public String signoutPage(HttpServletRequest request, Model model) {
        User user = UserUtils.getUser();
        CrmPlatformEmployee employee = platformEmpDao.findByUserId(user.getId());
        if (employee == null) {
            model.addAttribute("error", "用户不存在！");
            return "modules/yangguang/systemSetting/flowable/item/projsignout";
        }
        List<Record> members = reviewGroupMemberDao.findByEmployeeId(employee.getId());
        if (CollectionUtils.isEmpty(members)) {
            model.addAttribute("error", "成员不存在！");
            return "modules/yangguang/systemSetting/flowable/item/projsignout";
        }
        Record member = getSigninMember(members);
        if (member == null) {
            model.addAttribute("error", "尚未签到！");
            return "modules/yangguang/systemSetting/flowable/item/projsignout";
        }
        Date signinTime = member.getDate("signin_time");
        String fmtSigninTime = DateUtils.formatDate(signinTime, "yyyy-MM-dd HH:mm");
        model.addAttribute("signinTime", fmtSigninTime);
        // 计算在岗时长
        List<Long> durations = DateUtils.calcBetween(signinTime, new Date());
        String d = "";
        if (durations.get(0) > 0) {
            d += String.format("%d天", durations.get(0));
        }
        d += String.format("%d时", durations.get(1));
        d += String.format("%d分", durations.get(2));
        model.addAttribute("duration", d);
        return "modules/yangguang/systemSetting/flowable/item/projsignout";
    }

    private Record getSigninMember(List<Record> members) {
        for (Record member : members) {
            Date signinTime = member.getDate("signin_time");
            if (signinTime != null) {
                return member;
            }
        }
        return null;
    }

    @RequestMapping(value = {"signout"})
    @ResponseBody
    public Result signout(HttpServletRequest request) {
        User user = UserUtils.getUser();
        try {
            String signoutTime = crmReviewGroupMemberService.signout(user.getId());
            Result<String> ret = new Result<>();
            ret.setOk();
            ret.setData(signoutTime);
            return ret;
        } catch (BusinessException ex) {
            return Result.fail(ex.getMessage());
        }
    }

    /**
     * 根据申请类型，获取审核组的成员。
     */
    @RequestMapping(value = {"groupMembers"})
    @ResponseBody
    public Result groupMembers(@RequestParam("itemIds") String itemIds) {
        String[] itemIdArr = itemIds.split(",");
        BatchItem batchItem = null;
        try {
            batchItem = new BatchItem(Arrays.asList(itemIdArr));
        } catch (BusinessException ex) {
            return Result.fail(ex.getMessage());
        }

        String groupId = null;
        try {
            groupId = ReviewGroupUtil.mapFormKey2GroupId(batchItem.getFormKey(), batchItem.getPartnerId());
        } catch (BusinessException ex) {
            return Result.fail(ex.getMessage());
        }
        List<Record> members = crmReviewGroupMemberService.groupMembers(groupId);
        Result<List<Record>> ret = new Result<>();
        ret.setData(members);
        ret.setOk();
        return ret;
    }

}
