package yangtz.cs.liu.wechat.controller.office;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.util.UserInfoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import yangtz.cs.liu.activiti.service.IProcessService;
import yangtz.cs.liu.campus.domain.office.SchoolOfficePurchase;
import yangtz.cs.liu.campus.service.office.ISchoolOfficePurchaseService;
import yangtz.cs.liu.campus.vo.office.OfficeTodoListVO;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.core.constant.ProcessCommon.ROLEKEY;
import static com.core.constant.ProcessDefinition.OFFICEPURCHASE;
import static yangtz.cs.liu.campus.constant.ProcessState.PASS;
import static yangtz.cs.liu.campus.constant.ProcessState.REFUSE;

/**
 * 教师-办公申购Controller
 *
 * @author xu
 * @date 2022-09-27
 */
@RestController
@RequestMapping("/wx/purchase")
public class WxSchoolOfficePurchaseController extends BaseController {
    @Autowired
    private ISchoolOfficePurchaseService schoolOfficePurchaseService;
    @Autowired
    private IProcessService processService;
    @Autowired
    private UserInfoUtil userInfoUtil;

    /**
     * 查询当前登录用户的办公申购列表
     */
    @GetMapping("/list")
    public TableDataInfo list(String submitState,SchoolOfficePurchase schoolOfficePurchase) {
        startPage();
        List<OfficeTodoListVO> list = schoolOfficePurchaseService.queryList(submitState,schoolOfficePurchase);
        return getDataTable(list);
    }

    /**
     * 获取办公申购详细信息
     */
    @GetMapping(value = "/getInfo/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(schoolOfficePurchaseService.getInfo(id));
    }

    /**
     * 新增办公申购
     */
    @PostMapping("/add")
    public AjaxResult add(@RequestBody @Validated SchoolOfficePurchase schoolOfficePurchase) {
        Long userId = userInfoUtil.getTeacherUserId();
        schoolOfficePurchase.setType("officePurchase");
        schoolOfficePurchase.setApplyId(userId);
        return toAjax(schoolOfficePurchaseService.save(schoolOfficePurchase));
    }

    /**
     * 修改办公申购
     */
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody @Validated SchoolOfficePurchase schoolOfficePurchase) {
        if (StringUtils.isNull(schoolOfficePurchase.getId())) {
            throw new ServiceException("id为空，修改失败");
        }
        return toAjax(schoolOfficePurchaseService.updateById(schoolOfficePurchase));
    }

    /**
     * 删除办公申购
     */
    @DeleteMapping("/delete/{ids}")
    public AjaxResult remove(@PathVariable("ids") List<Long> ids) {
        return toAjax(schoolOfficePurchaseService.removeByIds(ids));
    }

    /**
     * 提交申请
     */
    @PostMapping("/submitApply/{id}")
    public AjaxResult submitApply(@PathVariable("id") Long id) {
        SchoolOfficePurchase schoolOfficePurchase = schoolOfficePurchaseService.getById(id);
        if (StringUtils.isNull(schoolOfficePurchase)) {
            throw new ServiceException("提交申请失败,未查询到相关信息");
        }
        String userName = getUsername();
        schoolOfficePurchase.setApplyUser(userName);
        schoolOfficePurchase.setApplyTime(DateUtils.getNowDate());
        //设置流程角色组标识
        Map<String, Object> map = new HashMap<>();
        map.put(ROLEKEY, schoolOfficePurchase.getRoleKey());
        /**
         * @author lyric
         * @date 2021-09-30
         * @param schoolOfficePurchase 业务实体
         * @param username 提交申请人 记录到底是哪个人提交了申请
         * @param key 流程标识 用于指定到底启动的是哪个流程(请假流程 办公流程 会议流程等) 这里启动的是 办公流程
         * @param variables 变量集合 流程中指定一些变量,这里我们主要用于动态指定审批人
         */
        return toAjax(schoolOfficePurchaseService.submitApply(schoolOfficePurchase, userName, OFFICEPURCHASE,map));
    }

    /**
     * 我的待办列表
     */
    @GetMapping("/myTaskList")
    public TableDataInfo myTaskList(SchoolOfficePurchase entity) {
        String userId = userInfoUtil.getTeacherUserId().toString();
        List<OfficeTodoListVO> list = schoolOfficePurchaseService.findMyTodoTasks(OFFICEPURCHASE, entity, userId);
        return getDataTable(list);
    }

    /**
     * 组待办事项列表
     */
    @GetMapping("/taskList")
    public TableDataInfo taskList(SchoolOfficePurchase entity) {
        String userId = userInfoUtil.getTeacherUserId().toString();
        List<OfficeTodoListVO> list = schoolOfficePurchaseService.findTodoTasks(OFFICEPURCHASE, entity, userId);
        return getDataTable(list);
    }

    /**
     * 完成任务
     */
    @PostMapping("/complete/{taskId}/{instanceId}")
    public AjaxResult complete(@PathVariable("taskId") String taskId, @PathVariable("instanceId") String instanceId, @RequestBody Map<String, Object> variables) {
        processService.completeTask(taskId, instanceId, variables);
        LambdaQueryWrapper<SchoolOfficePurchase> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SchoolOfficePurchase::getInstanceId,instanceId);
        SchoolOfficePurchase purchase = schoolOfficePurchaseService.list(lqw).get(0);
        if(Boolean.parseBoolean(variables.get("pass").toString())){
            purchase.setState(PASS);
        }else {
            purchase.setState(REFUSE);
        }
        schoolOfficePurchaseService.updateById(purchase);
        return AjaxResult.success();
    }

    /**
     * 我的已办列表
     */
    @GetMapping("/taskDoneList")
    public TableDataInfo taskDoneList(SchoolOfficePurchase entity) {
        String userId = userInfoUtil.getTeacherUserId().toString();
        List<OfficeTodoListVO> list = schoolOfficePurchaseService.findDoneTasks(OFFICEPURCHASE, entity, userId);
        int total = processService.getDoneTotal(OFFICEPURCHASE, userId);
        return getTaskTable(list,total);
    }

}
