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

import cn.ezhizao.common.utils.poi.ExcelUtil;
import cn.ezhizao.fegin.FilterRequest;
import cn.ezhizao.fegin.IFeignClient;
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.domain.server.Sys;
import cn.ezhizao.framework.web.page.TableDataInfo;
import cn.ezhizao.project.business.company.service.IBizCompanyService;
import cn.ezhizao.project.business.entrust.domain.BizEntrust;
import cn.ezhizao.project.business.entrust.service.IBizEntrustService;
import cn.ezhizao.project.business.entrustExamine.domain.BizEntrustExamine;
import cn.ezhizao.project.business.entrustExamine.service.IBizEntrustExamineService;
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 com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.sql.Date;
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;
    @Resource
    private IBizEntrustExamineService entrustExamineService;

    @Resource
    private IBizCompanyService bizCompanyService;

    @Resource
    private IFeignClient entrustFeignClient;
    /**
     * 查询工单信息列表
     */
    @PreAuthorize("@ss.hasPermi('business:entrust:workOrder:next:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizWorkOrder bizWorkOrder) throws NoSuchFieldException, IllegalAccessException {
//        List<SysCurrentMonth> months = sysCurrentMonthService.list(new LambdaQueryWrapper<SysCurrentMonth>()
//                .eq(SysCurrentMonth::getTenantId, getTenantId())
//                .eq(SysCurrentMonth::getType, 1));
        setTenantId(bizWorkOrder);
        startPage();
        startOrderBy();
        bizWorkOrder.setIsStop(0);
//        List<SysCurrentMonth> months = sysCurrentMonthService.query().eq("tenant_id", getTenantId()).eq("type", 1).list();
//        Date date = DateTime.of(months.get(0).getYear() + "-" + months.get(0).getMonth() + "-01", "yyyy-MM-dd").toSqlDate();
        bizWorkOrder.setWorkDate(bizWorkOrder.getCurrentMonth());
        List<BizWorkOrder> list = bizWorkOrderService.getList(bizWorkOrder);


        BizEntrust bizEntrust = new BizEntrust();
        bizEntrust.setWorkOrderIds(list.stream().map(BizWorkOrder::getId).collect(Collectors.toList()));
        bizEntrust.setWorkMonth(DateTime.of(bizWorkOrder.getCurrentMonth()).toSqlDate());
        List<BizEntrust> entrusts = bizEntrustService.getList(bizEntrust);
        list.forEach(l -> {
            l.setEntrust(entrusts.stream().filter(v -> v.getWorkOrderId().equals(l.getId())).findFirst().orElse(null));
            BizEntrustExamine one = entrustExamineService.getOne(new LambdaQueryWrapper<BizEntrustExamine>()
                    .eq(BizEntrustExamine::getWorkOrderId, l.getId())
                    .orderByDesc(BizEntrustExamine::getCreateTime).last("limit 1"));
            l.setEntrustExamine(one);
        });
        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);
        bizWorkOrder.setWorkDate(bizWorkOrder.getCurrentMonth());
        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(bizWorkOrder.getCurrentMonth()).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, "下月工单");
//            }
//        }

    }

    @PostMapping("/delEntrust")
    public AjaxResult delEntrust(@RequestBody BizEntrust bizEntrust) {
        List<Long> workOrderIds1 = bizEntrust.getWorkOrderIds();
        for (Long id : workOrderIds1) {
            BizEntrustExamine one = entrustExamineService.getOne(new LambdaQueryWrapper<BizEntrustExamine>()
                    .eq(BizEntrustExamine::getWorkOrderId, id)
                    .orderByDesc(BizEntrustExamine::getCreateTime).last("limit 1"));
            if(one!= null && one.getStatus().equals(0)){

                String name = bizCompanyService.getById(one.getCompanyId()).getName();
                throw new RuntimeException(name+"工单正在取消委托审核中");
            }
        }
        FilterRequest filterRequest = new FilterRequest();
        filterRequest.setDate(bizEntrust.getWorkMonth());
        filterRequest.setWorkOrderIds(workOrderIds1);
        String s =  entrustFeignClient.filterCompletedOrders(filterRequest);
        Map<String,List<Long>> map = JSON.parseObject(s, Map.class);
        List<Long> workOrderIds = map.get("workOrderIds");
        List<Long> oneList = map.get("oneList");
        List<Long> twoList = map.get("twoList");
        List<Long> threeList = map.get("threeList");
        boolean status= false;
        List<Long> finishWorkIds = mergeLists(oneList, twoList, threeList);
        if (!CollectionUtils.isEmpty(workOrderIds)){
            bizEntrust.setWorkOrderIds(workOrderIds);
            bizEntrust.setCurrentMonth(bizEntrust.getCurrentMonth());
            List<BizEntrust> entrustList = bizEntrustService.getList(bizEntrust);
            status = bizEntrustService.removeByIds(entrustList.stream().map(BizEntrust::getId).collect(Collectors.toList()));
        }
        //说明当前状态工单任务都处于未完成
        if( CollectionUtils.isEmpty(finishWorkIds) ){
            // 取消委托
            return toAjax(status);
        }

        String companyName = finishWorkIds.stream().map(id -> {
            Long companyId = bizWorkOrderService.getById(id).getCompanyId();
            return bizCompanyService.getById(companyId).getName();

        }).collect(Collectors.joining(","));
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("companyName", companyName);
        hashMap.put("workOrderIds", finishWorkIds);
        return AjaxResult.success("操作成功",hashMap);
    }
    @PostMapping("/okDelEntrust")
    public AjaxResult okDelEntrust(@RequestBody BizEntrust bizEntrust) {
        bizEntrust.setCurrentMonth(bizEntrust.getCurrentMonth());
        List<BizEntrust> entrustList = bizEntrustService.getList(bizEntrust);
        BizEntrustExamine bizEntrustExamine = new BizEntrustExamine();
        bizEntrustExamine.setId(bizEntrust.getExamineId());
        bizEntrustExamine.setStatus(1);
        entrustExamineService.updateById(bizEntrustExamine);
        // 取消委托
        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);
        }
    }

    public static List<Long> mergeLists(List<Long>... lists) {
        List<Long> result = new ArrayList<>();
        for (List<Long> list : lists) {
            if (list != null) {
                result.addAll(list);
            }
        }
        return result;
    }
}
