package com.ruoyi.project.invoice.controller;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.approve.damain.DevTask;
import com.ruoyi.project.invoice.domain.TApproveReserveInvoice;
import com.ruoyi.project.invoice.domain.TInvoiceBookingworkticket;
import com.ruoyi.project.invoice.service.ITApproveReserveInvoiceService;
import com.ruoyi.project.invoice.service.ITInvoiceBookingworkticketService;
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.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 预约开票申请Controller
 *
 * @author ruoyi
 * @date 2022-08-29
 */
@RestController
@RequestMapping("/approve/invoice")
public class TApproveReserveInvoiceController extends BaseController {
    @Autowired
    private ITApproveReserveInvoiceService tApproveReserveInvoiceService;
    @Autowired
    private ITInvoiceBookingworkticketService workService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private RuntimeService runtimeService;


    /**
     * 查询预约开票申请列表
     */
    @PreAuthorize("@ss.hasPermi('invoice:invoice:list')")
    @GetMapping("/list")
    public TableDataInfo list(TApproveReserveInvoice tApproveReserveInvoice) {
        startPage();
        List<TApproveReserveInvoice> list = tApproveReserveInvoiceService.selectTApproveReserveInvoiceList(tApproveReserveInvoice);
        for (TApproveReserveInvoice tApprove : list) {
            String[] ids;
            ids = tApprove.getInvoiceId().split(",");
            List<Object> devList = new ArrayList<>();
            for (String id : ids) {
                TInvoiceBookingworkticket book = workService.getById(id);
                devList.add(book);
            }
            tApprove.setDevList(devList);
        }
        return getDataTable(list);
    }

    /**
     * 导出预约开票申请列表
     */
    @PreAuthorize("@ss.hasPermi('invoice:invoice:export')")
    @Log(title = "预约开票申请", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TApproveReserveInvoice tApproveReserveInvoice) {
        List<TApproveReserveInvoice> list = tApproveReserveInvoiceService.selectTApproveReserveInvoiceList(tApproveReserveInvoice);
        ExcelUtil<TApproveReserveInvoice> util = new ExcelUtil<TApproveReserveInvoice>(TApproveReserveInvoice.class);
        return util.exportExcel(list, "invoice");
    }

    /**
     * 获取预约开票申请详细信息
     */
    @PreAuthorize("@ss.hasPermi('invoice:invoice:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        TApproveReserveInvoice tApprove = tApproveReserveInvoiceService.selectTApproveReserveInvoiceById(id);
        String[] ids;
        ids = tApprove.getInvoiceId().split(",");
        List<Object> devList = new ArrayList<>();
        for (String inId : ids) {
            TInvoiceBookingworkticket book = workService.getById(inId);
            devList.add(book);
        }
        tApprove.setDevList(devList);
        return AjaxResult.success(tApprove);
    }

    /**
     * 新增预约开票申请
     */
    @PreAuthorize("@ss.hasPermi('invoice:invoice:add')")
    @Log(title = "预约开票申请", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TApproveReserveInvoice tApproveReserveInvoice) {
        Long userid = getUserId();
        tApproveReserveInvoice.setUserId(userid);
        tApproveReserveInvoice.setApNo(DateUtils.dateTimeNow() + userid);
        Authentication.setAuthenticatedUserId(userid.toString());
        tApproveReserveInvoiceService.insertTApproveReserveInvoice(tApproveReserveInvoice);
        long bussniseeKey = tApproveReserveInvoice.getId();
        String[] ids;
        ids = tApproveReserveInvoice.getInvoiceId().split(",");
        for (String id : ids) {
            TInvoiceBookingworkticket invoice = workService.getById(id);
            invoice.setStatus(1L);
            workService.updateById(invoice);
        }
        //开始工作流、监听
        Map<String, Object> variables = new HashMap<>();
        variables.put("applyUser", userid.toString());
        variables.put("yhzgusers", tApproveReserveInvoice.getUserSupId());//用户主管
        variables.put("zzzgusers", tApproveReserveInvoice.getDevSupId());//装置主管
        if ("1".equals(tApproveReserveInvoice.getIsToday()))
            variables.put("zzgcsusers", tApproveReserveInvoice.getDevEngineerId());//装置工程师
        if ("1".equals(tApproveReserveInvoice.getIsSpecial()))
            variables.put("zzjlusers", tApproveReserveInvoice.getManagerconId());//装置经理
        variables.put("bzusers", tApproveReserveInvoice.getMonitorId());//装置经理
        //采用key来启动流程定义并设置流程变量，返回流程实例
        ProcessInstance pi = runtimeService.startProcessInstanceByKey("reserveInvoice", String.valueOf(bussniseeKey), variables);
        logger.info("流程部署id：" + pi.getDeploymentId());
        logger.info("流程定义id：" + pi.getProcessDefinitionId());
        logger.info("流程实例id：" + pi.getProcessInstanceId());
        tApproveReserveInvoice.setProcessId(pi.getProcessInstanceId());
        tApproveReserveInvoiceService.updateTApproveReserveInvoice(tApproveReserveInvoice);
        return AjaxResult.success();
    }

    @Log(title = "预约开票审核处理", businessType = BusinessType.UPDATE)
    @PutMapping("/handle")
    public AjaxResult handle(@RequestBody DevTask devTask) {
        //流程审批意见
        String symbol = "";
        if (devTask.getComment() != "") {
            symbol = "，";
        }
        //使用任务服务完成任务(提交任务)
        String taskId = devTask.getTaskId();
        // 使用任务id,获取任务对象，获取流程实例id
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        //利用任务对象，获取流程实例id
        String processInstancesId = task.getProcessInstanceId();
        TApproveReserveInvoice invoice = tApproveReserveInvoiceService.selectTApproveReserveInvoiceById(Long.parseLong(devTask.getBusinessKey()));
        if (devTask.getCondition().equals("1")) {
            devTask.setComment("通过" + symbol + devTask.getComment());
            invoice.setStatus(2L);
            invoice.setEnddate(new Date());
        } else if (devTask.getCondition().equals("0")) {
            devTask.setComment("未通过" + symbol + devTask.getComment());
            invoice.setStatus(3L);
            invoice.setEnddate(new Date());
        }
        String[] ids;
        ids = invoice.getInvoiceId().split(",");
        for (String id : ids) {
            TInvoiceBookingworkticket invoiceBook = workService.getById(id);
            invoiceBook.setStatus(0L);
            workService.updateById(invoiceBook);
        }
        Map<String, Object> param = new HashMap<>();
        param.put("condition", devTask.getCondition());
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = processEngine.getTaskService();
        //认领任务
        processEngine.getTaskService()
                .claim(taskId, getUserId().toString());
        taskService.addComment(taskId, processInstancesId, devTask.getComment());
        taskService.complete(taskId, param);
        return AjaxResult.success();
    }

    /**
     * 修改预约开票申请
     */
    @PreAuthorize("@ss.hasPermi('invoice:invoice:edit')")
    @Log(title = "预约开票申请", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TApproveReserveInvoice tApproveReserveInvoice) {
        return toAjax(tApproveReserveInvoiceService.updateTApproveReserveInvoice(tApproveReserveInvoice));
    }

    /**
     * 删除预约开票申请
     */
    @PreAuthorize("@ss.hasPermi('invoice:invoice:remove')")
    @Log(title = "预约开票申请", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tApproveReserveInvoiceService.deleteTApproveReserveInvoiceByIds(ids));
    }
}
