package com.ruoyi.project.invoice.controller;

import com.alibaba.fastjson.JSON;
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.*;
import com.ruoyi.project.invoice.service.ITApproveReserveInvoiceService;
import com.ruoyi.project.invoice.service.ITInvoiceBookingworkticketService;
import com.ruoyi.project.invoice.service.ITInvoiceDeviceService;
import com.ruoyi.project.invoice.service.ITInvoiceWorkcontentService;
import com.ruoyi.project.listener.invoiceApprove.*;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.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.beans.factory.annotation.Autowired;
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 ITInvoiceDeviceService deviceService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private ITInvoiceWorkcontentService invoiceWorkcontentMapper;

    @Autowired
    private ISysUserService iSysUserService;


    /**
     * 查询预约开票申请列表
     */

    @GetMapping("/list")
    public TableDataInfo list(TApproveReserveInvoice tApproveReserveInvoice) {
        startPage();
        List<TApproveReserveInvoice> list = tApproveReserveInvoiceService.selectTApproveReserveInvoiceList(tApproveReserveInvoice);
        if (list.size() > 0) {
            for (TApproveReserveInvoice tApprove : list) {
                String[] ids;
                ids = tApprove.getInvoiceId().split(",");
                List<Object> devList = new ArrayList<>();
                for (String id : ids) {
                    List<TInvoiceBookingworkticketVo> book = workService.selectDetailById(Long.valueOf(id));
                    devList.addAll(book);
                }
                tApprove.setDevList(devList);
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出预约开票申请列表
     */

    @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");
    }

    /**
     * 获取预约开票申请详细信息
     */

    @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) {
            List<TInvoiceBookingworkticketVo> book = workService.selectDetailById(Long.valueOf(inId));
            devList.addAll(book);
        }
        tApprove.setDevList(devList);
        return AjaxResult.success(tApprove);
    }

    /**
     * 新增预约开票申请
     */

    @Log(title = "预约开票申请", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TApproveReserveInvoice tApproveReserveInvoice) {
        Long userid = getUserId();
        tApproveReserveInvoice.setUserId(userid);
        tApproveReserveInvoice.setApNo(DateUtils.dateTimeNow() + userid);
        tApproveReserveInvoiceService.insertTApproveReserveInvoice(tApproveReserveInvoice);
        long bussniseeKey = tApproveReserveInvoice.getId();
        String[] ids;
        ids = tApproveReserveInvoice.getInvoiceId().split(",");
        String devSupId = "";
        String applyUser = "";
        for (String id : ids) {
            TInvoiceBookingworkticket invoice = workService.getById(id);
            tApproveReserveInvoice.setUserId(invoice.getCreaterCode());
            applyUser = invoice.getCreaterCode().toString();
//            invoice.setStatus(0L);
//            workService.updateById(invoice);
//            switch (invoice.getWorkArea()) {
//                case "310裂解区":
//                case "700开关锅炉":
//                case "320裂解区":
//                case "250管廊-700":
//                    devSupId = "20253,20257";
//                    break;
//                case "330压缩区":
//                case "废水处理":
//                case "600废碱":
//                case "250管廊-600":
//                    devSupId = "20249,20317";
//                    break;
//                case "380分离区":
//                case "360分离区":
//                case "350分离区":
//                case "340分离区":
//                    devSupId = "20252";
//                    break;
//                case "400汽油加氢":
//                case "250管廊-400":
//                    devSupId = "20248";
//                    break;
//                case "500芳烃抽提":
//                case "250管廊-500":
//                    devSupId = "20244";
//                    break;
//                case "D301控制楼":
//                case " D201变电所":
//                case " 维修厂房":
//                case "危废车库":
//                    devSupId = "20332,20250,20276";
//                    break;
            TInvoiceDevice device = new TInvoiceDevice();
            device.setWorkArea(invoice.getWorkArea());
            TInvoiceDevice tInvoiceDevice = deviceService.selectRegionalHeadByWorkArea(invoice.getWorkArea());
            logger.info("========tInvoiceDevice:" + JSON.toJSONString(tInvoiceDevice));
            devSupId = tInvoiceDevice.getRegionalHead();
            logger.info("========devSupId:" + devSupId);
        }
        //开始工作流、监听
        Authentication.setAuthenticatedUserId(applyUser);//设置当前申请人
        Map<String, Object> variables = new HashMap<>();
        variables.put("applyUser", applyUser);
        variables.put("yhzgusers", tApproveReserveInvoice.getUserSupId().toString());//用户主管
        variables.put("zzzgusers", devSupId);//装置主管
        SysUser sysUser = new SysUser();
        sysUser.setDeptId(103L);

        //添加装置工程师
        String devEngineerId = "";
        sysUser.setRoleId(20003L);//装置工程师
        List<SysUser> sysUsers = iSysUserService.selectUserListByRoleAndDept(sysUser);
        for (SysUser user : sysUsers) {
            devEngineerId += user.getUserId() + ",";
        }
        devEngineerId = devEngineerId.substring(0, devEngineerId.length() - 1);
        variables.put("zzgcsusers", devEngineerId);

        //添加装置经理（副）
        String managerconId = "";
        sysUser.setRoleId(20013L);//装置副经理
        sysUsers = iSysUserService.selectUserListByRoleAndDept(sysUser);
        sysUser.setRoleId(20006L);//装置经理
        sysUsers.addAll(iSysUserService.selectUserListByRoleAndDept(sysUser));
        for (SysUser user : sysUsers) {
            managerconId += user.getUserId() + ",";
        }
        managerconId = managerconId.substring(0, managerconId.length() - 1);
        variables.put("zzjlusers", managerconId);

        variables.put("yhzgTaskCreateListener", new YhzgTaskCreateListener());//用户主管监听发送邮件
        variables.put("zzzgTaskCreateListener", new ZzzgTaskCreateListener());//装置主管监听发送邮件
        variables.put("zzgcsTaskCreateListener", new ZzgcsTaskCreateListener());//装置工程师监听发送邮件
        variables.put("zzjlTaskCreateListener", new ZzjlTaskCreateListener());//装置经理监听发送邮件
        variables.put("invoiceEndSuccessListener", new InvoiceEndSuccessListener());//流程结束监听发送邮件
        variables.put("invoiceEndFailListener", new InvoiceEndFailListener());//流程结束监听发送邮件
        //采用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()));
        TInvoiceBookingworkticket invoiceBook = workService.getById(invoice.getInvoiceId());
        if (devTask.getCondition().equals("1")) {
            devTask.setComment("通过" + symbol + devTask.getComment());
            invoice.setStatus(2L);
            invoice.setEnddate(new Date());
        }
        if (devTask.getCondition().equals("2")) {
            devTask.setCondition("0");
            devTask.setComment("作废并修改流程" + symbol + devTask.getComment());
            invoice.setStatus(-1L);
            invoice.setContent("作废并修改流程");
            invoice.setEnddate(new Date());
        }
        Map<String, Object> param = new HashMap<>();
        List<TInvoiceWorkcontent> workcontents = invoiceWorkcontentMapper.selectTInvoiceWorkcontentBybookingticketId(Long.valueOf(invoice.getInvoiceId()));
        if (task.getName().equals("装置主管签字确认")) {
            invoice.setDevSupId(getUserId());
        }
        if (task.getName().equals("装置工程师签字确认")) {
            invoice.setDevEngineerId(getUserId());
        }
        if (task.getName().equals("装置经理签字确认")) {
            invoice.setManagerconId(getUserId());
        }
        if (DateUtils.dateTime(invoiceBook.getCreatedate()).equals(DateUtils.dateTime(invoiceBook.getWorkStartTime()))) {
            param.put("istoday", "1");
            out:for (TInvoiceWorkcontent workcontent : workcontents) {
                for (String workType : workcontent.getWorkType().split(",")) {
                    if (workType.equals("1")||workType.equals("15")) {
                        param.put("isspecial", "1");
                        break out;
                    } else {
                        param.put("isspecial", "0");
                    }
                }
            }
        } else {
            param.put("istoday", "0");
            param.put("isspecial", "0");
        }
        param.put("condition", devTask.getCondition());
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = processEngine.getTaskService();
        tApproveReserveInvoiceService.updateTApproveReserveInvoice(invoice);
        workService.updateTInvoiceBookingworkticket(invoiceBook);
        //认领任务
        processEngine.getTaskService()
                .claim(taskId, getUserId().toString());
        taskService.addComment(taskId, processInstancesId, devTask.getComment());
        taskService.complete(taskId, param);
        return AjaxResult.success();
    }

    /**
     * 修改预约开票申请
     */

    @Log(title = "预约开票申请", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TApproveReserveInvoice tApproveReserveInvoice) {
        return toAjax(tApproveReserveInvoiceService.updateTApproveReserveInvoice(tApproveReserveInvoice));
    }

    /**
     * 删除预约开票申请
     */

    @Log(title = "预约开票申请", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tApproveReserveInvoiceService.deleteTApproveReserveInvoiceByIds(ids));
    }
}
