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

import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
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.util.VxTemlateSendApi;
import yangtz.cs.liu.campus.vo.auditorium.SchoolAuditoriumVo;
import yangtz.cs.liu.campus.vo.teacher.TeacherLeaveVO;
import yangtz.cs.liu.dingding.utils.DingMessageUtils;
import yangtz.cs.liu.dingding.vo.DingMessageVo;
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;
    @Autowired
    private DingMessageUtils dingMessageUtils;

    /**
     * 查询全部学校礼堂预约列表
     */
//    @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<>());

//        /** 发送发送钉钉审批实例 */
//        String ddInstanceId = schoolAuditoriumService.sendDdInstance(schoolAuditorium);
//
//        //转换时间
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//        Date time = schoolAuditorium.getApplyTime();
//        String applyTime = format.format(time);

//        //发送钉钉消息到分管领导
//        //获取钉钉用户id
//        String ddUserId = teacherService.getDdUserIdByUserId(schoolAuditorium.getLeadershipId());
//        //发送钉钉消息给分管领导
//        DingMessageVo messageVo = new DingMessageVo();
//        OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
//        msg.setOa(new OapiMessageCorpconversationAsyncsendV2Request.OA());
//        msg.getOa().setHead(new OapiMessageCorpconversationAsyncsendV2Request.Head());
//        msg.getOa().getHead().setText("智慧校园");
//        msg.getOa().setBody(new OapiMessageCorpconversationAsyncsendV2Request.Body());
//        msg.getOa().getBody().setAuthor(schoolAuditorium.getApplyName());
//        msg.getOa().getBody().setContent("申请内容:" + schoolAuditorium.getActivityName());
//        msg.getOa().getBody().setTitle("您好，您有礼堂预约申请等待审批!");
//        OapiMessageCorpconversationAsyncsendV2Request.Form form1 = new OapiMessageCorpconversationAsyncsendV2Request.Form();
//        form1.setKey("申请时间:");
//        form1.setValue(applyTime);
//        msg.getOa().getBody().setForm(Arrays.asList(form1));
//        msg.getOa().setPcMessageUrl("https://open.dingtalk.com/");
//        msg.getOa().setMessageUrl("https://open.dingtalk.com/");
//        msg.setMsgtype("oa");
//        OapiMessageCorpconversationAsyncsendV2Request.StatusBar statusBar = new OapiMessageCorpconversationAsyncsendV2Request.StatusBar();
//        statusBar.setStatusBg("0xFFF65E5E");
//        statusBar.setStatusValue("进行中");
//        msg.getOa().setStatusBar(statusBar);
//        messageVo.setMsg(msg);
//        messageVo.setToAllUser(false);
//        messageVo.setUseridList(ddUserId);
//        Long ddTaskId = dingMessageUtils.sendMessage(messageVo);
//        //更新消息任务id、钉钉流程实例id
//        SchoolAuditorium auditorium = new SchoolAuditorium();
//        auditorium.setId(id);
//        auditorium.setDdTaskId(ddTaskId);
//        auditorium.setDdInstanceId(ddInstanceId);
//        schoolAuditoriumService.updateById(auditorium);
        /**发送模板消息到分管领导*/
        //获取用户openid
//        String openId = teacherService.getOpenIdByUserId(schoolAuditorium.getLeadershipId());
//        Map<String,Object> map = new HashMap<>();
//        map.put("toUserOpenId",openId);
//        map.put("applyTime",applyTime);
//        map.put("remark","请您尽快处理。");
//        map.put("applyUser",schoolAuditorium.getApplyName());
//        map.put("content",schoolAuditorium.getActivityName());
//        map.put("first","您好，您有礼堂预约申请等待审批!");
//        VxTemlateSendApi.sendVxTemlate(map);

//        AuditoriumTemplate template = new AuditoriumTemplate();
//        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);

            /** 发送消息通知到申请人，审批结果 */
            //获取钉钉用户id
            String ddUserId = teacherService.getDdUserIdByUserId(leave.getApplyId());
            //发送钉钉消息给分管领导
            DingMessageVo messageVo = new DingMessageVo();
            OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
            msg.setOa(new OapiMessageCorpconversationAsyncsendV2Request.OA());
            msg.getOa().setHead(new OapiMessageCorpconversationAsyncsendV2Request.Head());
            msg.getOa().getHead().setText("智慧校园");
            msg.getOa().setBody(new OapiMessageCorpconversationAsyncsendV2Request.Body());
            msg.getOa().getBody().setAuthor(leave.getLeadershipName());
            msg.getOa().getBody().setContent(flag ? "已通过" : "已驳回");
            msg.getOa().getBody().setTitle("您好，您的礼堂预约申请已回复。");
            msg.getOa().setPcMessageUrl("https://open.dingtalk.com/");
            msg.getOa().setMessageUrl("https://open.dingtalk.com/");
            msg.setMsgtype("oa");
            messageVo.setMsg(msg);
            messageVo.setToAllUser(false);
            messageVo.setUseridList(ddUserId);
            dingMessageUtils.sendMessage(messageVo);

            //修改消息任务状态为已完成
            dingMessageUtils.updateStatusBar(leave.getDdTaskId(), "已完成", "0xFF78C06E");

            /**发送模板消息到申请人，审批结果*/
            //获取申请人openId
//            String openId = teacherService.getOpenIdByUserId(leave.getApplyId());
//            Map<String,Object> map = new HashMap<>();
//            map.put("toUserOpenId",openId);
//            map.put("first","您好，您的礼堂预约申请已回复。");
//            map.put("content",flag ? "已通过" : "已驳回");
//            map.put("remark","审批留言： "+ variables.get("comment"));
//            VxTemlateSendApi.sendVxTemlate(map);
//            LeaveResultTemplate template = new LeaveResultTemplate();
//            template.setFirst("您好，您的礼堂预约申请已回复。");
//            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("审批完成");
    }
}
