package com.nbclass.szxgl.controller.mobile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nbclass.exception.ParameterException;
import com.nbclass.holder.SpringContextHolder;
import com.nbclass.system.controller.BaseController;
import com.nbclass.system.model.User;
import com.nbclass.szxgl.mapper.ListTypeMapper;
import com.nbclass.szxgl.model.ListType;
import com.nbclass.szxgl.model.ProjectTask;
import com.nbclass.szxgl.model.ProjectTaskJournal;
import com.nbclass.szxgl.service.ProjectService;
import com.nbclass.szxgl.service.ProjectTaskService;
import com.nbclass.util.PageUtil;
import com.nbclass.util.ResultUtil;
import com.nbclass.vo.base.ResponseVo;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author wangweifeng
 * @version 1.0 2021/3/15
 */
@Controller
@RequestMapping("/mobile/api/projectTask")
public class ProjectTaskController extends BaseController {

    @Resource
    private ProjectService service;

    @Resource
    private ProjectTaskService projectTaskService;

    @Resource
    private ListTypeMapper listTypeMapper;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    /**
     * 获取项目任务列表
     *
     * @param pid
     * @param limit
     * @param offset
     */
    @RequestMapping("/getList")
    @ResponseBody
    public ResponseVo selectProjectTaskList(String pid, String userId,
        @RequestParam(defaultValue = "100") Integer limit, @RequestParam(defaultValue = "1") Integer offset) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        if(user==null && SpringContextHolder.isProd()) {
            throw new ParameterException("登录失效，请重新登录!");
        }

        PageHelper.startPage(PageUtil.getPageNo(limit, offset), limit);
        List<ProjectTask> list = service.getTaskList(pid);
        PageInfo<ProjectTask> pages = new PageInfo<>(list);
        JSONObject obj = new JSONObject();
        JSONObject pageObj = toJSON(ResultUtil.table(list, pages.getTotal()));
        obj.putAll(pageObj);
        boolean allowModify = service.hasPowerForTask(pid);
        obj.put("allowModify", allowModify);

        obj.put("userId", user == null ? userId : user.getUserId());
        return ResultUtil.success("success", obj);
    }

    /**
     * 获取项目任务进度日志列表
     *
     * @param taskId
     */
    @RequestMapping("/journal/getList")
    @ResponseBody
    public ResponseVo selectProjectTaskJournalList(String taskId) {
        List<ProjectTaskJournal> list = service.getTaskJournalList(taskId);
        JSONObject obj = new JSONObject();
        obj.put("rows", list);
        return ResultUtil.success("success", obj);
    }

    /**
     * 删除任务
     *
     * @param ids
     */
    @RequestMapping("del")
    @ResponseBody
    public ResponseVo delete(String projectId, String[] ids) {
        projectTaskService.deleteProjectTask(projectId, ids);
        return ResultUtil.success("success");
    }

    /**
     * 添加项目任务
     *
     * @param t
     * @param errors
     * @param isSendMsg
     * @param userIds
     * @return
     */

    @RequestMapping("add")
    @ResponseBody
    public ResponseVo add(@Valid ProjectTask t, Errors errors, Integer isSendMsg, String[] userIds,String listValues) {
        if (errors.hasErrors()) {
            return ResultUtil.error("参数验证失败");
        }
        projectTaskService.addProjectTask(t, isSendMsg, userIds,listValues);
        return ResultUtil.success("success");
    }

    /**
     * 修改项目任务
     *
     * @param t
     * @param errors
     * @param isSendMsg
     * @param userIds
     */
    @RequestMapping("update")
    @ResponseBody
    public ResponseVo update(@Valid ProjectTask t, Errors errors, Integer isSendMsg, String[] userIds) {

        if (errors.hasErrors()) {
            return ResultUtil.error("参数验证失败");
        }
        projectTaskService.updateProjectTask(t, isSendMsg, userIds);
        return ResultUtil.success("success");
    }


    /**
     * 查询我的任务列表
     *
     * @param limit
     * @param offset
     * @return
     */
    @RequestMapping("/myTask/query")
    @ResponseBody
    public ResponseVo selectMyTaskList(@RequestParam(defaultValue = "10") Integer limit,
                                       @RequestParam(defaultValue = "1") Integer offset, String userid) {
        PageHelper.startPage(offset, limit);
        //正式环境不用传用户id
        if (userid == null) {
            User user = (User) SecurityUtils.getSubject().getPrincipal();
            if (user != null) {
                List<Map> list = projectTaskService.selectMyTaskList(user.getUserId());
                PageInfo<Map> pages = new PageInfo<>(list, limit);
                return ResultUtil.success("success", pages);

            } else {
                return ResultUtil.success("success");
            }
        } else {
            List<Map> list = projectTaskService.selectMyTaskList(userid);
            PageInfo<Map> pages = new PageInfo<>(list, limit);
            return ResultUtil.success("success", pages);
        }
    }


    /**
     * 添加任务进度日志
     *
     * @param j
     * @param errors
     * @param speed
     */
    @RequestMapping("/myTask/addJournal")
    @ResponseBody
    public ResponseVo addJournal(@Valid ProjectTaskJournal j,Errors errors,short speed) {

        if (errors.hasErrors()) {
            return ResultUtil.error("参数验证失败");
        }
        projectTaskService.addProjectTaskJournal(j, speed);
        return ResultUtil.success("success");
    }

    /**
     * 获取下拉列表
     * @return
     */
    @RequestMapping("/myTask/getComboBox")
    @ResponseBody
    public ResponseVo getComboBox(){
        List<ListType> listTypes = listTypeMapper.getComboBox();
        return ResultUtil.success(listTypes);
    }

}
