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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
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 com.ruoyi.common.utils.poi.ExcelUtil;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import yangtz.cs.liu.activiti.domain.HistoricActivity;
import yangtz.cs.liu.activiti.service.IProcessService;
import yangtz.cs.liu.campus.domain.schoolDepartmentBudget.SchoolDepartmentBudget;
import yangtz.cs.liu.campus.domain.temp.DepartmentBudgetTemplate;
import yangtz.cs.liu.campus.domain.temp.LeaveResultTemplate;
import yangtz.cs.liu.campus.service.schoolDepartmentBudget.ISchoolDepartmentBudgetService;
import yangtz.cs.liu.campus.service.teacher.ISchoolTeacherService;
import yangtz.cs.liu.campus.util.VxTemlateSendApi;
import yangtz.cs.liu.campus.vo.schoolDepartmentBudget.SchoolDepartmentBudgetVo;
import yangtz.cs.liu.wechat.service.api.IWxApiService;

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 static com.core.constant.ProcessDefinition.DEPARTMENTBUDGET;

/**
 * 科室预算填报Controller
 *
 * @author ruoyi
 * @date 2023-07-11
 */
@RestController
@RequestMapping("/departmentBudget")
public class SchoolDepartmentBudgetController extends BaseController
{
    @Autowired
    private ISchoolDepartmentBudgetService schoolDepartmentBudgetService;
    @Autowired
    private IProcessService processService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private ISchoolTeacherService teacherService;
    @Autowired
    private IWxApiService wxApiService;

    /**
     * 查询全部科室预算填报列表
     */
//    @PreAuthorize("@ss.hasPermi('departmentBudget:budget:list')")
    @GetMapping("/list")
    public TableDataInfo list(SchoolDepartmentBudget schoolDepartmentBudget)
    {
        startPage();
        List<SchoolDepartmentBudgetVo> list = schoolDepartmentBudgetService.selectSchoolDepartmentBudgetList(schoolDepartmentBudget);
        return getDataTable(list);
    }

    /**
     * 查询本单位科室预算填报列表
     */
//    @PreAuthorize("@ss.hasPermi('departmentBudget:budget:list')")
    @GetMapping("/listDw")
    public TableDataInfo listDw(SchoolDepartmentBudget schoolDepartmentBudget)
    {
        startPage();
        List<SchoolDepartmentBudgetVo> list = schoolDepartmentBudgetService.selectSchoolDepartmentBudgetListDw(schoolDepartmentBudget);
        return getDataTable(list);
    }

    /**
     * 导出科室预算填报列表
     */
//    @PreAuthorize("@ss.hasPermi('departmentBudget:budget:export')")
    @Log(title = "科室预算填报", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SchoolDepartmentBudget schoolDepartmentBudget)
    {
        List<SchoolDepartmentBudgetVo> list = schoolDepartmentBudgetService.selectSchoolDepartmentBudgetList(schoolDepartmentBudget);
        ExcelUtil<SchoolDepartmentBudgetVo> util = new ExcelUtil<SchoolDepartmentBudgetVo>(SchoolDepartmentBudgetVo.class);
        util.exportExcel(response, list, "科室预算填报数据");
    }

    /**
     * 获取科室预算填报详细信息
     */
//    @PreAuthorize("@ss.hasPermi('departmentBudget:budget:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(schoolDepartmentBudgetService.selectSchoolDepartmentBudgetById(id));
    }

    /**
     * 新增科室预算填报
     */
//    @PreAuthorize("@ss.hasPermi('departmentBudget:budget:add')")
    @Log(title = "科室预算填报", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody SchoolDepartmentBudgetVo schoolDepartmentBudget)
    {
        return toAjax(schoolDepartmentBudgetService.insertSchoolDepartmentBudget(schoolDepartmentBudget));
    }

    /**
     * 修改科室预算填报
     */
//    @PreAuthorize("@ss.hasPermi('departmentBudget:budget:edit')")
    @Log(title = "科室预算填报", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody SchoolDepartmentBudgetVo schoolDepartmentBudget)
    {
        return toAjax(schoolDepartmentBudgetService.updateSchoolDepartmentBudget(schoolDepartmentBudget));
    }

    /**
     * 删除科室预算填报
     */
//    @PreAuthorize("@ss.hasPermi('departmentBudget:budget:remove')")
    @Log(title = "科室预算填报", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(schoolDepartmentBudgetService.deleteSchoolDepartmentBudgetByIds(ids));
    }

    /**
     * 提交申请
     */
    @PostMapping("/submitApply/{id}")
    public AjaxResult submitApply(@PathVariable("id") Long id){
        SchoolDepartmentBudget schoolDepartmentBudget = schoolDepartmentBudgetService.getById(id);
        if (StringUtils.isNull(schoolDepartmentBudget)) {
            throw new ServiceException("提交申请失败,未查询到相关信息");
        }
        //获取当前登录用户
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //设置申请人id
        schoolDepartmentBudget.setApplyId(user.getUserId());
        //设置申请人
        schoolDepartmentBudget.setApplyName(user.getUserName());
        //设置申请时间
        schoolDepartmentBudget.setApplyTime(DateUtils.getNowDate());
        String userName = user.getUserName();
        schoolDepartmentBudgetService.submitApply(schoolDepartmentBudget,userName,DEPARTMENTBUDGET,new HashMap<>());

        /**发送模板消息到分管领导*/
        //转换时间
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date time = schoolDepartmentBudget.getApplyTime();
        String applyTime = format.format(time);

        //获取openid
        String openId = teacherService.getOpenIdByUserId(schoolDepartmentBudget.getLeadershipId());
        Map<String,Object> map = new HashMap<>();
        map.put("toUserOpenId",openId);
        map.put("applyTime",applyTime);
        map.put("remark","请您尽快处理。");
        map.put("applyUser",schoolDepartmentBudget.getApplyName());
        map.put("content",schoolDepartmentBudget.getYear() + "年度" + schoolDepartmentBudget.getDeptName() + "预算申请");
        map.put("first","您好，您有科室预算申请等待审批。");
        VxTemlateSendApi.sendVxTemlate(map);

//        DepartmentBudgetTemplate template = new DepartmentBudgetTemplate();
//        template.setToUserOpenId(openId);
//        template.setFirst("您好，您有科室预算申请等待审批。");
//        template.setApplyUser(schoolDepartmentBudget.getApplyName());
//        template.setContent(schoolDepartmentBudget.getYear() + "年度" + schoolDepartmentBudget.getDeptName() + "预算申请");
//        template.setApplyTime(schoolDepartmentBudget.getApplyTime());
//        template.setRemark("请您尽快处理。");
//        wxApiService.sendDepartmentBudgetTemplate(template);
        return AjaxResult.success("提交成功");
    }

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

    /**
     * 已办事项列表
     */
    @GetMapping("/taskDoneList")
    public TableDataInfo taskDoneList(SchoolDepartmentBudget entity) {
        String userId = getUserId().toString();
        List<SchoolDepartmentBudgetVo> list = schoolDepartmentBudgetService.findDoneTasks(DEPARTMENTBUDGET, 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<SchoolDepartmentBudget> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SchoolDepartmentBudget::getInstanceId,instanceId);
        SchoolDepartmentBudget leave = schoolDepartmentBudgetService.getOne(wrapper);
        Boolean flag = Boolean.parseBoolean(variables.get("pass").toString());

        /**判断流程是否结束,如果结束则更新科室预算状态*/
        ProcessInstance rpi = runtimeService
                .createProcessInstanceQuery()//创建流程实例查询对象
                .processInstanceId(instanceId)
                .singleResult();
        if(flag == false){
            leave.setState("3");

            /** 修改任务结果 */
            schoolDepartmentBudgetService.updateById(leave);

            /**发送模板消息到申请人，审批结果*/
            //获取申请人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("审批完成");
        }
        //说明流程实例结束了
        if(rpi==null){
            if(flag){
                leave.setState("2");
            }else {
                leave.setState("3");
            }
            /** 修改任务结果 */
            schoolDepartmentBudgetService.updateById(leave);

            /**发送模板消息到申请人，审批结果*/
            //获取申请人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("审批完成");
    }

    /**
     * 获取当前登录人信息
     */
    @GetMapping("/getUserXx")
    public AjaxResult getUserXx(){
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Map<String,Object> map = new HashMap<>();
        map.put("userId",user.getUserId());
        map.put("userName",user.getUserName());
        map.put("deptId",user.getDeptId());
        map.put("deptName",user.getDept().getDeptName());
        return AjaxResult.success(map);
    }
}
