package cn.ezhizao.project.business.workOrder.controller;

import cn.ezhizao.common.utils.poi.ExcelUtil;
import cn.ezhizao.framework.aspectj.lang.annotation.Log;
import cn.ezhizao.framework.aspectj.lang.enums.BusinessType;
import cn.ezhizao.framework.web.controller.BaseController;
import cn.ezhizao.framework.web.domain.AjaxResult;
import cn.ezhizao.framework.web.page.TableDataInfo;
import cn.ezhizao.project.business.entrust.domain.BizEntrust;
import cn.ezhizao.project.business.entrust.service.IBizEntrustService;
import cn.ezhizao.project.business.workOrder.domain.BizWorkOrder;
import cn.ezhizao.project.business.workOrder.domain.BizWorkOrderExport;
import cn.ezhizao.project.business.workOrder.service.IBizWorkOrderService;
import cn.ezhizao.project.system.domain.SysCurrentMonth;
import cn.ezhizao.project.system.service.ISysCurrentMonthService;
import cn.ezhizao.project.tenant.domain.Tenant;
import cn.ezhizao.project.tenant.service.ITenantService;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 下月委托工单Controller
 *
 * @author ruoyi
 * @date 2023-11-13
 */
@RestController
@RequestMapping("/business/workOrderNext")
public class WorkOrderNextController extends BaseController {
    @Resource
    IBizWorkOrderService bizWorkOrderService;
    @Resource
    ISysCurrentMonthService sysCurrentMonthService;
    @Resource
    IBizEntrustService bizEntrustService;
    @Resource
    ITenantService tenantService;

    /**
     * 查询工单信息列表
     */
    @PreAuthorize("@ss.hasPermi('business:entrust:workOrder:next:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizWorkOrder bizWorkOrder) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizWorkOrder);
        startPage();
        startOrderBy();
        bizWorkOrder.setIsStop(0);
        List<BizWorkOrder> list = bizWorkOrderService.getList(bizWorkOrder);
        List<SysCurrentMonth> months = sysCurrentMonthService.query().eq("tenant_id", getTenantId()).eq("type", 1).list();
        if (months.isEmpty()) {
            return getDataTable(new ArrayList<>());
        } else {
            BizEntrust bizEntrust = new BizEntrust();
            bizEntrust.setWorkOrderIds(list.stream().map(BizWorkOrder::getId).collect(Collectors.toList()));
            bizEntrust.setWorkMonth(DateTime.of(months.get(0).getYear() + "-" + months.get(0).getMonth() + "-01", "yyyy-MM-dd").toSqlDate());
            List<BizEntrust> entrusts = bizEntrustService.getList(bizEntrust);
            list.forEach(l -> {
                l.setEntrust(entrusts.stream().filter(v -> v.getWorkOrderId().equals(l.getId())).findFirst().orElse(null));
            });
            return getDataTable(list);
        }
    }

    /**
     * 查询工单信息列表
     */
    @PreAuthorize("@ss.hasPermi('business:entrust:workOrder:next:list')")
    @GetMapping("/listForFactory")
    public TableDataInfo listForFactory(BizWorkOrder bizWorkOrder) throws NoSuchFieldException, IllegalAccessException
    {
        bizWorkOrder.setToTenantId(getTenantId());
        startPage();
        bizWorkOrder.setIsStop(0);
        List<BizWorkOrder> list = bizWorkOrderService.getList(bizWorkOrder);
        List<SysCurrentMonth> months = sysCurrentMonthService.query().eq("tenant_id", getTenantId()).eq("type", 1).list();
        if (months.isEmpty()) {
            return getDataTable(new ArrayList<>());
        } else {
            BizEntrust bizEntrust = new BizEntrust();
            bizEntrust.setWorkOrderIds(list.stream().map(BizWorkOrder::getId).collect(Collectors.toList()));
            bizEntrust.setWorkMonth(DateTime.of(months.get(0).getYear() + "-" + months.get(0).getMonth() + "-01", "yyyy-MM-dd").toSqlDate());
            List<BizEntrust> entrusts = bizEntrustService.getList(bizEntrust);
            list.forEach(l -> {
                l.setEntrust(entrusts.stream().filter(v -> v.getWorkOrderId().equals(l.getId())).findFirst().orElse(null));
            });
            return getDataTable(list);
        }
    }
    @PreAuthorize("@ss.hasPermi('business:entrust:workOrder:current:edit')")
    @PostMapping("/addEntrust")
    public AjaxResult addEntrust(@RequestBody BizEntrust entrust) {
        List<BizEntrust> entrustList = bizEntrustService.getList(entrust);
        List<BizWorkOrder> bizWorkOrders = bizWorkOrderService.query().in("id", entrust.getWorkOrderIds().stream().filter(e -> entrustList.stream().noneMatch(t -> t.getWorkOrderId().equals(e))).collect(Collectors.toList())).list();
        entrustList.forEach(l -> {
            l.setToTenantId(entrust.getToTenantId());
        });
        List<BizEntrust> addEntrusts = new ArrayList<>();
        bizWorkOrders.forEach(l -> {
            BizEntrust bizEntrust = new BizEntrust();
            bizEntrust.setWorkOrderId(l.getId());
            bizEntrust.setCompanyId(l.getCompanyId());
            bizEntrust.setToTenantId(entrust.getToTenantId());
            bizEntrust.setTenantId(l.getTenantId());
            bizEntrust.setFromTenantId(l.getTenantId());
            if (l.getTaskTypeId() == 1L) {
                DateTime workMonth = DateTime.of(entrust.getWorkMonth());
                bizEntrust.setCurrentMonth(workMonth.offsetNew(DateField.MONTH, - 1).toSqlDate());
            } else {
                bizEntrust.setCurrentMonth(entrust.getWorkMonth());
            }
            bizEntrust.setWorkMonth(entrust.getWorkMonth());
            bizEntrust.setTaskTypeId(l.getTaskTypeId());
            bizEntrust.setTaskTypeDetailId(l.getTaskTypeDetailId());
            addEntrusts.add(bizEntrust);
        });
        // 添加委托
        return toAjax((entrustList.isEmpty() || bizEntrustService.updateBatchById(entrustList)) && (addEntrusts.isEmpty() || bizEntrustService.saveBatch(addEntrusts)));
    }

    /**
     * 导出下月工单列表
     */
    @PreAuthorize("@ss.hasPermi('business:entrust:workOrder:next:export')")
    @Log(title = "下月工单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizWorkOrder bizWorkOrder) throws NoSuchFieldException, IllegalAccessException {
        if (bizWorkOrder.getToTenantId() == null) {
            setTenantId(bizWorkOrder);
        }

//        startPage();
        startOrderBy();
        bizWorkOrder.setIsStop(0);
        List<BizWorkOrder> list = bizWorkOrderService.getList(bizWorkOrder);
        List<BizWorkOrderExport> listExport = new ArrayList<>();

        List<SysCurrentMonth> months = sysCurrentMonthService.query().eq("tenant_id", getTenantId()).eq("type", 1).list();
        if (months.isEmpty()) {
            list = new ArrayList<>();
            if (bizWorkOrder.getTenantId() == null) {
                ExcelUtil<BizWorkOrderExport> util = new ExcelUtil<BizWorkOrderExport>(BizWorkOrderExport.class);
                util.exportExcel(response, listExport, "下月工单");
            } else {
                ExcelUtil<BizWorkOrder> util = new ExcelUtil<BizWorkOrder>(BizWorkOrder.class);
                util.exportExcel(response, list, "下月工单");
            }

        } else {
            BizEntrust bizEntrust = new BizEntrust();
            bizEntrust.setWorkOrderIds(list.stream().map(BizWorkOrder::getId).collect(Collectors.toList()));
            bizEntrust.setWorkMonth(DateTime.of(months.get(0).getYear() + "-" + months.get(0).getMonth() + "-01", "yyyy-MM-dd").toSqlDate());
            List<BizEntrust> entrusts = bizEntrustService.getList(bizEntrust);
            list.forEach(l -> {
                l.setEntrust(entrusts.stream().filter(v -> v.getWorkOrderId().equals(l.getId())).findFirst().orElse(null));
                l.setTypeName(l.getType() == 1 ? "循环工单" : "代办工单");
                l.setExecutor(l.getEntrust() == null ? l.getServiceName() : l.getEntrust().getToAccountName());
                if (bizWorkOrder.getTenantId() == null) {
                    BizWorkOrderExport export = new BizWorkOrderExport();
                    export.setCompanyName(l.getCompanyName());
                    export.setFromCompanyName(l.getFromCompanyName());
                    export.setSocialCreditCode(l.getSocialCreditCode());
                    export.setTypeName(l.getTypeName());
                    export.setTaskTypeName(l.getTaskTypeName());
                    export.setStartMonth(l.getStartMonth());
                    export.setEndMonth(l.getEndMonth());
                    export.setMonthNum(l.getMonthNum());
                    export.setExecutor(l.getExecutor());
                    listExport.add(export);
                }
            });

            if (bizWorkOrder.getTenantId() == null) {
                ExcelUtil<BizWorkOrderExport> util = new ExcelUtil<BizWorkOrderExport>(BizWorkOrderExport.class);
                util.exportExcel(response, listExport, "下月工单");
            } else {
                ExcelUtil<BizWorkOrder> util = new ExcelUtil<BizWorkOrder>(BizWorkOrder.class);
                util.exportExcel(response, list, "下月工单");
            }
        }

    }

    @PreAuthorize("@ss.hasPermi('business:entrust:workOrder:next:edit')")
    @PostMapping("/delEntrust")
    public AjaxResult delEntrust(@RequestBody BizEntrust bizEntrust) {
        List<BizEntrust> entrustList  = bizEntrustService.getList(bizEntrust);
        // 取消委托
        return toAjax(bizEntrustService.removeByIds(entrustList.stream().map(BizEntrust::getId).collect(Collectors.toList())));
    }


    @PreAuthorize("@ss.hasPermi('business:entrust:workOrder:next:edit')")
    @GetMapping("/getFactories")
    public AjaxResult getFactories() {
        List<Tenant> tenants = tenantService.getFactories();
        return success(tenants);
    }

    @PreAuthorize("@ss.hasPermi('business:entrust:workOrder:next:list')")
    @GetMapping("/checkCurrent")
    public AjaxResult checkCurrent() {
        List<SysCurrentMonth> months = sysCurrentMonthService.query().eq("tenant_id", getTenantId()).eq("type", 1).list();
        Map<String, Object> result = new HashMap<>();
        if (months.isEmpty())  {
            result.put("checkResult", false);
            return success(result);
        } else {
            result.put("checkResult", true);
            DateTime dateTime = new DateTime();
            dateTime.setField(DateField.YEAR, Integer.parseInt(months.get(0).getYear()));
            dateTime.setField(DateField.DAY_OF_MONTH, 1);
            dateTime.setField(DateField.MONTH, Integer.parseInt(months.get(0).getMonth()) - 1);
            result.put("currentMonth", dateTime.toString("yyyy-MM-dd"));
            return success(result);
        }
    }
}
