package com.fs.app.controller;

import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.R;
import com.fs.company.service.ICompanyUserService;
import com.fs.course.mapper.FsCourseWatchLogMapper;
import com.fs.qw.domain.QwUser;
import com.fs.qw.domain.QwWorkTask;
import com.fs.qw.param.SelectQwWorkTaskListParam;
import com.fs.qw.service.IQwExternalContactService;
import com.fs.qw.service.IQwUserService;
import com.fs.qw.service.IQwWorkTaskService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@Api(tags = "企微任务看板接口")
@RestController
@RequestMapping("/app/qw/workTask")
@AllArgsConstructor
public class QwWorkTaskController extends BaseController {

    private final IQwWorkTaskService qwWorkTaskService;
    private final IQwUserService qwUserService;

    @Autowired
    ICompanyUserService companyUserService;

    @Autowired
    private FsCourseWatchLogMapper fsCourseWatchLogMapper;

    @Autowired
    private IQwExternalContactService qwExternalContactService;

    @PostMapping("/list")
    @ApiOperation("企微任务看板列表")
    public R selectQwWorkTaskList(@RequestBody SelectQwWorkTaskListParam param) {

        log.info("企微任务看板列表: {}",param);

        QwUser qwUser = qwExternalContactService.getQwUserByRedis(param.getCorpId().trim(), param.getQwUserId().trim());

        if (qwUser == null || qwUser.getCompanyId() == null) {
            return R.error("员工未绑定 销售公司 或 未获取到员工信息，请重试！");
        }

        param.setUserId(qwUser.getId());

        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<QwWorkTask> list = qwUserService.selectQwWorkTaskList(param);

        for (QwWorkTask qwWorkTask : list) {
            List<Integer> logs = fsCourseWatchLogMapper.selectFsCourseWatchLog7DayByExtId(qwWorkTask.getExtId());
            qwWorkTask.setLogs(logs);
        }

        PageInfo<QwWorkTask> pageInfo = new PageInfo<>(list);
        return R.ok().put("data",pageInfo);
    }

    /**
     * 处理催课
     */
    @GetMapping("/updateWorkTaskStatus/{id}")
    public R updateWorkTaskStatus(@PathVariable("id") Long id) {

        try {
            QwWorkTask qwWorkTask=new QwWorkTask();
            qwWorkTask.setId(id);
            qwWorkTask.setStatus(1);
            int i = qwWorkTaskService.updateQwWorkTask(qwWorkTask);
            if (i>0) {
                return R.ok();
            }else {
                return R.error("更新失败，请重试！");
            }
        }catch (Exception e){
            return R.error("更新失败，请重试！");
        }
    }



}
