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

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.impl.persistence.entity.TaskEntityImpl;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import yangtz.cs.liu.activiti.domain.HistoricActivity;
import yangtz.cs.liu.activiti.service.IProcessService;
import yangtz.cs.liu.campus.domain.auditorium.SchoolAuditorium;
import yangtz.cs.liu.campus.domain.teacher.SchoolTeacherLeave;
import yangtz.cs.liu.campus.domain.temp.AuditoriumTemplate;
import yangtz.cs.liu.campus.domain.temp.LeaveResultTemplate;
import yangtz.cs.liu.campus.domain.temp.TeacherLeaveTemplate;
import yangtz.cs.liu.campus.service.auditorium.ISchoolAuditoriumService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import yangtz.cs.liu.campus.service.teacher.ISchoolTeacherService;
import yangtz.cs.liu.campus.vo.auditorium.SchoolAuditoriumVo;
import yangtz.cs.liu.campus.vo.teacher.TeacherLeaveVO;
import yangtz.cs.liu.wechat.service.api.IWxApiService;

import static com.core.constant.ProcessDefinition.*;
import static yangtz.cs.liu.campus.constant.ProcessState.*;
import static yangtz.cs.liu.campus.constant.ProcessState.ZHUYAO;

/**
 * 学校礼堂预约Controller
 *
 * @author ruoyi
 * @date 2023-06-14
 */
@RestController
@RequestMapping("/auditorium")
public class SchoolAuditoriumController extends BaseController
{
    @Autowired
    private ISchoolAuditoriumService schoolAuditoriumService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private IProcessService processService;
    @Autowired
    private ISchoolTeacherService teacherService;
    @Autowired
    private IWxApiService wxApiService;

    /**
     * 查询全部学校礼堂预约列表
     */
//    @PreAuthorize("@ss.hasPermi('auditorium:auditorium:list')")
    @GetMapping("/list")
    public TableDataInfo list(SchoolAuditoriumVo schoolAuditorium)
    {
        startPage();
        List<SchoolAuditoriumVo> list = schoolAuditoriumService.selectSchoolAuditoriumList(schoolAuditorium);
        return getDataTable(list);
    }

    /**
     * 查询个人学校礼堂预约列表
     */
//    @PreAuthorize("@ss.hasPermi('auditorium:auditorium:list')")
    @GetMapping("/listGr")
    public TableDataInfo listGr(SchoolAuditoriumVo schoolAuditorium)
    {
        startPage();
        List<SchoolAuditoriumVo> list = schoolAuditoriumService.selectSchoolAuditoriumListGr(schoolAuditorium);
        return getDataTable(list);
    }

    /**
     * 导出学校礼堂预约列表
     */
//    @PreAuthorize("@ss.hasPermi('auditorium:auditorium:export')")
    @Log(title = "学校礼堂预约", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SchoolAuditoriumVo schoolAuditorium)
    {
        List<SchoolAuditoriumVo> list = schoolAuditoriumService.selectSchoolAuditoriumList(schoolAuditorium);
        ExcelUtil<SchoolAuditoriumVo> util = new ExcelUtil<SchoolAuditoriumVo>(SchoolAuditoriumVo.class);
        util.exportExcel(response, list, "学校礼堂预约数据");
    }

    /**
     * 获取学校礼堂预约详细信息
     */
//    @PreAuthorize("@ss.hasPermi('auditorium:auditorium:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(schoolAuditoriumService.selectSchoolAuditoriumById(id));
    }

    /**
     * 新增学校礼堂预约
     */
//    @PreAuthorize("@ss.hasPermi('auditorium:auditorium:add')")
    @Log(title = "学校礼堂预约", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody SchoolAuditorium schoolAuditorium)
    {
        return toAjax(schoolAuditoriumService.insertSchoolAuditorium(schoolAuditorium));
    }

    /**
     * 修改学校礼堂预约
     */
//    @PreAuthorize("@ss.hasPermi('auditorium:auditorium:edit')")
    @Log(title = "学校礼堂预约", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody SchoolAuditorium schoolAuditorium)
    {
        return toAjax(schoolAuditoriumService.updateSchoolAuditorium(schoolAuditorium));
    }

    /**
     * 删除学校礼堂预约
     */
//    @PreAuthorize("@ss.hasPermi('auditorium:auditorium:remove')")
    @Log(title = "学校礼堂预约", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteByIds/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(schoolAuditoriumService.deleteSchoolAuditoriumByIds(ids));
    }

    /**
     * 提交申请
     */
    @PostMapping("/submitApply/{id}")
    public AjaxResult submitApply(@PathVariable("id") Long id){
        SchoolAuditorium schoolAuditorium = schoolAuditoriumService.getById(id);
        if (StringUtils.isNull(schoolAuditorium)) {
            throw new ServiceException("提交申请失败,未查询到相关信息");
        }
        String userName = getUsername();
        schoolAuditorium.setApplyId(getUserId());
        schoolAuditorium.setApplyName(userName);
        schoolAuditorium.setApplyDeptId(getDeptId());
        schoolAuditorium.setApplyTime(DateUtils.getNowDate());
        schoolAuditoriumService.submitApply(schoolAuditorium, userName, AUDITORIUMAPPLY, new HashMap<>());

        /**发送模板消息到分管领导*/
        AuditoriumTemplate template = new AuditoriumTemplate();
        String openId = teacherService.getOpenIdByUserId(schoolAuditorium.getLeadershipId());
        template.setToUserOpenId(openId);
        template.setFirst("您好，您有礼堂预约申请等待审批。");
        template.setApplyUser(schoolAuditorium.getApplyName());
        template.setContent(schoolAuditorium.getActivityName());
        template.setApplyTime(schoolAuditorium.getApplyTime());
        template.setRemark("请您尽快处理。");
        wxApiService.sendAuditoriumTemplate(template);

        return AjaxResult.success("提交成功");
    }

    /**
     * 待办事项列表
     */
    @GetMapping("/taskList")
    public TableDataInfo taskList(SchoolAuditorium entity) {
        String userId = getUserId().toString();
        List<SchoolAuditoriumVo> list = schoolAuditoriumService.findTodoTasks(AUDITORIUMAPPLY, entity, userId);
        return getTaskTable(list, list.size());
    }

    /**
     * 已办事项列表
     */
    @GetMapping("/taskDoneList")
    public TableDataInfo taskDoneList(SchoolAuditorium entity) {
        String userId = getUserId().toString();
        List<SchoolAuditoriumVo> list = schoolAuditoriumService.findDoneTasks(AUDITORIUMAPPLY, entity, userId);
        return getTaskTable(list,list.size());
    }

    /**
     * 完成任务
     */
    @PostMapping("/complete/{taskId}/{instanceId}")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult complete(@PathVariable("taskId") String taskId, @PathVariable("instanceId") String instanceId, @RequestBody Map<String, Object> variables) {
        processService.completeTask(taskId, instanceId, variables);
        LambdaQueryWrapper<SchoolAuditorium> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SchoolAuditorium::getInstanceId,instanceId);
        SchoolAuditorium leave = schoolAuditoriumService.getOne(wrapper);
        Boolean flag = Boolean.parseBoolean(variables.get("pass").toString());

        /**判断流程是否结束,如果结束则更新礼堂预约状态*/
        ProcessInstance rpi = runtimeService
                .createProcessInstanceQuery()//创建流程实例查询对象
                .processInstanceId(instanceId)
                .singleResult();
        //说明流程实例结束了
        if(rpi==null){
            if(flag){
                leave.setState("2");
            }else {
                leave.setState("3");
            }
            /** 修改任务结果 */
            schoolAuditoriumService.updateById(leave);

            /**发送模板消息到申请人，审批结果*/
            LeaveResultTemplate template = new LeaveResultTemplate();
            template.setFirst("您好，您的礼堂预约申请已回复。");
            //获取申请人openId
            String openId = teacherService.getOpenIdByUserId(leave.getApplyId());
            template.setToUserOpenId(openId);
            template.setResult(flag ? "已通过" : "已驳回");
            template.setRemark("审批留言： "+ variables.get("comment"));
            List<HistoricActivity> list = processService.selectHistoryList(instanceId,new HistoricActivity());
            if(StringUtils.isNotNull(list) && list.size() > 0){
                HistoricActivity activity = list.get(0);
                template.setAuditTime(activity.getEndTime());
            }
            wxApiService.sendLeaveResultTemplate(template);

            return AjaxResult.success("审批完成");
        }
        return AjaxResult.success("审批完成");
    }
}