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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.core.domain.PageBaseInfo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
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.domain.vehicle.SchoolVehicleApplication;
import yangtz.cs.liu.campus.service.office.ISchoolOfficePurchaseService;
import yangtz.cs.liu.campus.vo.office.OfficeTodoListVO;
import yangtz.cs.liu.campus.vo.vehicle.VehicleApplicationVO;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotNull;
import static com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank;
import static com.core.constant.ProcessCommon.ROLEKEY;
import static com.core.constant.ProcessDefinition.OFFICEPURCHASE;
import static com.core.constant.ProcessDefinition.VEHICLEAPPLICATION;
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("/purchase")
public class SchoolOfficePurchaseController extends BaseController {
    @Autowired
    private ISchoolOfficePurchaseService schoolOfficePurchaseService;

    @Autowired
    private IProcessService processService;

    /**
     * 查询办公申购列表
     */
    @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) {
        schoolOfficePurchase.setType("officePurchase");
        schoolOfficePurchase.setApplyId(getUserId());
        return toAjax(schoolOfficePurchaseService.save(schoolOfficePurchase));
    }

    /**
     * 提交申请
     */
    @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));
    }

    /**
     * 修改办公申购
     */
    @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("/export")
    public void exportAll(HttpServletResponse response,String submitState, SchoolOfficePurchase schoolOfficePurchase) {
        List<OfficeTodoListVO> list = schoolOfficePurchaseService.queryList(submitState,schoolOfficePurchase);
        ExcelUtil<OfficeTodoListVO> util = new ExcelUtil<OfficeTodoListVO>(OfficeTodoListVO.class);
        util.exportExcel(response, list, "办公申购数据");
    }

    /**
     * 导出
     *
     * @param ids
     * @return
     */
    @PostMapping("/export/{ids}")
    public void export(HttpServletResponse response, @PathVariable("ids") List<Long> ids) {
        LambdaQueryWrapper<SchoolOfficePurchase> lqw = new LambdaQueryWrapper<>();
        lqw.in(SchoolOfficePurchase::getId,ids).orderByDesc(SchoolOfficePurchase::getCreateTime);
        List<SchoolOfficePurchase> list = schoolOfficePurchaseService.list(lqw);
        ExcelUtil<SchoolOfficePurchase> util = new ExcelUtil<>(SchoolOfficePurchase.class);
        util.exportExcel(response, list, "办公申购数据");
    }

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

    /**
     * 组待办事项列表
     */
    @GetMapping("/taskList")
    public TableDataInfo taskList(SchoolOfficePurchase entity) {
        String userId = getUserId().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)variables.get("pass")){
            purchase.setState(PASS);
        }else {
            purchase.setState(REFUSE);
        }
        schoolOfficePurchaseService.updateById(purchase);
        return AjaxResult.success();
    }

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