package com.ruoyi.web.controller.branch;

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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.branch.domain.TBranchMemTransfer;
import com.ruoyi.branch.domain.approve.DevTask;
import com.ruoyi.branch.service.ITBranchMemTransferService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.service.ISysUserService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.identity.Authentication;
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.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 com.ruoyi.branch.domain.TBranchMember;
import com.ruoyi.branch.service.ITBranchMemberService;
import com.ruoyi.common.utils.poi.ExcelUtil;

/**
 * 支部成员管理Controller
 *
 * @author ruoyi
 * @date 2023-06-15
 */
@RestController
@RequestMapping("/branch/member")
public class TBranchMemberController extends BaseController
{
    @Autowired
    private ITBranchMemberService tBranchMemberService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private ITBranchMemTransferService transferService;

    /**
     * 审批处理
     *
     * @param devTask
     * @return
     */
    @PreAuthorize("@ss.hasPermi('branch:member:edit')")
    @PutMapping("/handle")
    public AjaxResult handle(@RequestBody DevTask devTask) {
        TBranchMember member = tBranchMemberService.selectTBranchMemberByMemberId(devTask.getObjId());
        String taskId = devTask.getTaskId();
        String taskName = devTask.getTaskName();
        String condition = devTask.getCondition();
        Map<String, Object> param = new HashMap<>();
        param.put("condition", condition);

        if (devTask.getComment() == null) {
            devTask.setComment("");
        }

        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = processEngine.getTaskService();
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        String processInstancesId = task.getProcessInstanceId();
        processEngine.getTaskService().claim(taskId, getUserId().toString());
        taskService.addComment(taskId, processInstancesId, devTask.getComment());
        taskService.complete(taskId, param);

        if (taskName.equals("支部申请")) {
            if (condition.equals("1")) {
                // 修改 xxx对象的属性后，前端会把 xxx对象转为 LinkedHashMap类型，
                // 为了避免出现 java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to xxx 类型转换异常，
                // 将 LinkedHashMap转为 JSON字符串，再转回 xxx类型。
                TBranchMember newMember = JSONObject.parseObject(JSON.toJSONString(devTask.getObj()), TBranchMember.class);
                member.setNewDeptId(newMember.getNewDeptId());
            } else {
                member.setApStatus("1");
            }
        } else if (taskName.equals("党支部审核")) {

        } else if (taskName.equals("党总支审核")) {
            if (condition.equals("1")) {
                // 新增一条党员关系转移记录
                TBranchMemTransfer transfer = new TBranchMemTransfer();
                transfer.setOldDeptId(member.getOldDeptId());
                transfer.setNewDeptId(member.getNewDeptId());
                transfer.setDeptId(member.getNewDeptId());
                transfer.setTransferTime(new Date());
                transfer.setUserId(member.getUserId());
                transferService.insertTBranchMemTransfer(transfer);

                member.setApStatus("1");
                member.setDeptId(member.getNewDeptId());

                // 更新用户表
                SysUser user = userService.selectUserById(member.getUserId());
                user.setDeptId(member.getNewDeptId());
                userService.updateUser(user);
            } else {

            }
        }
        // 更新支部成员表
        tBranchMemberService.updateTBranchMember(member);

        return AjaxResult.success();
    }

    /**
     * 转移申请
     */
    @PreAuthorize("@ss.hasPermi('branch:member:edit')")
    @PutMapping("/apply")
    public AjaxResult apply(@RequestBody TBranchMember tBranchMember)
    {
        String userId = getUserId().toString();

        // 开始流程
        Authentication.setAuthenticatedUserId(userId);
        Map<String, Object> variables = new HashMap<>();
        variables.put("applicant", userId);
        variables.put("verifier1", "120");
        variables.put("verifier2", "139");
        long businessKey = tBranchMember.getMemberId();
        ProcessInstance pi = runtimeService.startProcessInstanceByKey("commonProcess", String.valueOf(businessKey), variables);

        // 提交申请
        Map<String, Object> param = new HashMap<>();
        param.put("condition", "1");
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = processEngine.getTaskService();
        List<Task> list = taskService.createTaskQuery().taskCandidateOrAssigned(userId).list();
        String taskId = null;
        String processInstanceId = null;
        for (Task task : list) {
            processInstanceId = task.getProcessInstanceId();
            if (processInstanceId.equals(pi.getProcessInstanceId())) {
                taskId = task.getId();
            }
        }
        processEngine.getTaskService().claim(taskId, getUserId().toString());
        taskService.addComment(taskId, processInstanceId, "无");
        taskService.complete(taskId, param);

        // 更新支部成员表
        tBranchMember.setProcessId(pi.getProcessInstanceId());
        tBranchMember.setApNo(DateUtils.dateTimeNow() + userId);
        tBranchMember.setApStatus("0");
        tBranchMemberService.updateTBranchMember(tBranchMember);

        return AjaxResult.success();
    }

    /**
     * 查询支部成员政治生日列表
     */
    @PreAuthorize("@ss.hasPermi('branch:member:list')")
    @GetMapping("/listPoliticalBirthday")
    public AjaxResult listPoliticalBirthday(TBranchMember tBranchMember)
    {
        return AjaxResult.success(tBranchMemberService.selectPoliticalBirthdayList(tBranchMember));
    }

    /**
     * 查询支部成员管理列表
     */
    @PreAuthorize("@ss.hasPermi('branch:member:list')")
    @GetMapping("/list")
    public AjaxResult list(TBranchMember tBranchMember)
    {
//        startPage();
//        List<TBranchMember> list = tBranchMemberService.selectTBranchMemberList(tBranchMember);
//        return getDataTable(list);
        return AjaxResult.success(tBranchMemberService.selectTBranchMemberList(tBranchMember));
    }

    /**
     * 导出支部成员管理列表
     */
    @PreAuthorize("@ss.hasPermi('branch:member:export')")
    @Log(title = "支部成员管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TBranchMember tBranchMember)
    {
        List<TBranchMember> list = tBranchMemberService.selectTBranchMemberList(tBranchMember);
        ExcelUtil<TBranchMember> util = new ExcelUtil<TBranchMember>(TBranchMember.class);
        util.exportExcel(response, list, "支部成员管理数据");
    }

    /**
     * 获取支部成员管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('branch:member:query')")
    @GetMapping(value = "/{memberId}")
    public AjaxResult getInfo(@PathVariable("memberId") Long memberId)
    {
        return success(tBranchMemberService.selectTBranchMemberByMemberId(memberId));
    }

    /**
     * 新增支部成员管理
     */
    @PreAuthorize("@ss.hasPermi('branch:member:add')")
    @Log(title = "支部成员管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TBranchMember tBranchMember)
    {
        Long userId = getUserId();
        Long deptId = userService.selectUserById(userId).getDeptId();
        tBranchMember.setDeptId(deptId);
        return toAjax(tBranchMemberService.insertTBranchMember(tBranchMember));
    }

    /**
     * 修改支部成员管理
     */
    @PreAuthorize("@ss.hasPermi('branch:member:edit')")
    @Log(title = "支部成员管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TBranchMember tBranchMember)
    {
        return toAjax(tBranchMemberService.updateTBranchMember(tBranchMember));
    }

    /**
     * 删除支部成员管理
     */
    @PreAuthorize("@ss.hasPermi('branch:member:remove')")
    @Log(title = "支部成员管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{memberIds}")
    public AjaxResult remove(@PathVariable Long[] memberIds)
    {
        return toAjax(tBranchMemberService.deleteTBranchMemberByMemberIds(memberIds));
    }
}
