package com.gxwebsoft.apps.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.gxwebsoft.apps.constants.TowerConstants;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.param.UserParam;
import com.gxwebsoft.common.system.service.UserService;
import com.gxwebsoft.shop.entity.Category;
import com.gxwebsoft.shop.param.CategoryParam;
import com.gxwebsoft.shop.service.CategoryService;
import com.gxwebsoft.tower.entity.*;
import com.gxwebsoft.tower.param.*;
import com.gxwebsoft.tower.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.beetl.android.util.ArrayMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


@Api(tags = "派单管理")
@RestController
@RequestMapping("/api/apps/worksheet")
public class TowerWorksheetFrontController extends BaseController {
    @Resource
    private TowerWorksheetService towerWorksheetService;
    @Resource
    private TowerWorksheetDetailService towerWorksheetDetailService;
    @Resource
    private TowerWorksheetSetUpService towerWorksheetSetUpService;
    @Resource
    private TowerWorksheetPartsService towerWorksheetPartsService;
    @Resource
    private TowerWorksheetCarDispatchService towerWorksheetCarDispatchService;
    @Resource
    private TowerWorksheetCheckService towerWorksheetCheckService;
    @Resource
    private TowerProjectService towerProjectService;
    @Resource
    private TowerEquipmentService towerEquipmentService;
    @Resource
    private UserService userService;
    @Resource
    private CategoryService categoryService;
    @Resource
    private TowerWorksheetAuditService towerWorksheetAuditService;
    @Resource
    private TowerProjectUserService towerProjectUserService;
    @Resource
    private TowerProjectOrderService towerProjectOrderService;

    @ApiOperation("首页数据")
    @PostMapping("/index-data")
    public ApiResult<?> getData() {
        User user = getLoginUser();
        Map<String, Integer> data = new HashMap<>();
        data.put("all", sumData(user, -1));
        // 待派单
        data.put("to_be_send", sumData(user, 1));
        // 待整理资料
        data.put("to_document", sumData(user, 2));
        // 待到场
        data.put("to_reach", sumData(user, 3));
        // 待确认
        data.put("to_confirm", sumData(user, 4));
        // 已完成
        data.put("done", sumData(user, 5));
        // 审核中
        data.put("auditing", sumData(user, -2));
        // 资料员已完成
        data.put("done_for_document", sumData(user, 2, true));
        return success("成功", data);
    }

    @ApiOperation("派单列表")
    @PostMapping("/worksheet/list")
    public ApiResult<?> worksheetList(@RequestBody TowerWorksheetParam param) {
        User user = getLoginUser();
        Integer status = param.getStatus();
        if (user.getUserLevel().equals(TowerConstants.USER_LEVEL_NONE)) return fail("无权限");
        MPJLambdaWrapper<TowerWorksheet> mpjLambdaWrapper = new MPJLambdaWrapper<>();
        if (user.getUserLevel().equals(TowerConstants.USER_LEVEL_CLASS_MANAGER)) {
            mpjLambdaWrapper.eq("class_manager", user.getUserId());
        } else if (user.getUserLevel().equals(TowerConstants.USER_LEVEL_DOCUMENTER)) {
            mpjLambdaWrapper.eq("document_uid", user.getUserId());
        } else if (user.getUserLevel().equals(TowerConstants.USER_LEVEL_OPERATOR)) {
            mpjLambdaWrapper.eq("start_uid", user.getUserId());
        } else if (user.getUserLevel().equals(TowerConstants.USER_LEVEL_PRODUCTION_MANAGER)) {
            mpjLambdaWrapper.eq("production_manger_uid", user.getUserId());
        } else if (user.getUserLevel().equals(TowerConstants.USER_LEVEL_ASSET)) {
            mpjLambdaWrapper.eq("asset_uid", user.getUserId());
        } else if (user.getUserLevel().equals(TowerConstants.USER_LEVEL_CAR_DISPATCH)) {
            mpjLambdaWrapper.eq("car_dispatch_uid", user.getUserId());
        } else if (user.getUserLevel().equals(TowerConstants.USER_LEVEL_FIX)) {
            mpjLambdaWrapper.eq("fix_uid", user.getUserId());
        }
        if (!status.equals(-1)) {
            if (status.equals(-2)) mpjLambdaWrapper.eq("t.audit_status", 1);
            else mpjLambdaWrapper.eq("t.status", status);
        }
        mpjLambdaWrapper.selectAll(TowerWorksheet.class)
                .select(TowerProject::getProjectName)
                .leftJoin(TowerProject.class, TowerProject::getProjectId, TowerWorksheet::getProjectId);
        PageParam<TowerWorksheet, TowerWorksheetParam> page = new PageParam<>(param);
        page.setDefaultOrder("update_time desc");
        IPage<TowerWorksheet> towerWorksheetIPage = towerWorksheetService.page(page, mpjLambdaWrapper);
        List<TowerWorksheet> towerWorksheets = towerWorksheetIPage.getRecords();
        for (TowerWorksheet towerWorksheet : towerWorksheets) {
            formatWorksheet(towerWorksheet, false);
            if (towerWorksheet.getStatus().equals(2) && towerWorksheet.getAuditStatus().equals(1)
                    && (user.getUserLevel().equals(5) || user.getUserLevel().equals(9))) {
                TowerWorksheetAudit audit = towerWorksheetAuditService.getOne(
                        new LambdaQueryWrapper<TowerWorksheetAudit>()
                                .eq(TowerWorksheetAudit::getWorksheetId, towerWorksheet.getWorksheetId())
                                .eq(TowerWorksheetAudit::getUserId, getLoginUserId())
                );
                if (audit != null) towerWorksheet.setNeedAudit(audit.getStatus().equals(0));
            }
            towerWorksheet.setHasCarDispatch(
                    towerWorksheetCarDispatchService.count(
                            new LambdaQueryWrapper<TowerWorksheetCarDispatch>()
                                    .eq(TowerWorksheetCarDispatch::getWorksheetId, towerWorksheet.getWorksheetId())
                    ) > 0
            );
        }
        IPage<TowerWorksheet> pages = new Page<>(param.getPage(), param.getLimit());
        pages.setRecords(towerWorksheets);
        pages.setTotal(towerWorksheetIPage.getTotal());
        return success(pages);
    }

    @ApiOperation("派单详情")
    @PostMapping("/worksheet/info")
    public ApiResult<TowerWorksheet> worksheetInfo(@RequestBody TowerWorksheetParam param) {
        User user = getLoginUser();
        MPJLambdaWrapper<TowerWorksheet> mpjLambdaWrapper = new MPJLambdaWrapper<>();
        mpjLambdaWrapper.eq(TowerWorksheet::getWorksheetId, param.getWorksheetId())
                .selectAll(TowerWorksheet.class)
                .select(TowerProject::getProjectName)
                .select(TowerProject::getProjectAddress)
                .select(TowerProject::getProjectRegion)
                .leftJoin(TowerProject.class, TowerProject::getProjectId, TowerWorksheet::getProjectId);
        TowerWorksheet towerWorksheet = towerWorksheetService.getOne(mpjLambdaWrapper);
        if (towerWorksheet.getStatus().equals(2) && towerWorksheet.getAuditStatus().equals(1)
                && (user.getUserLevel().equals(5) || user.getUserLevel().equals(9))) {
            TowerWorksheetAudit audit = towerWorksheetAuditService.getOne(
                    new LambdaQueryWrapper<TowerWorksheetAudit>()
                            .eq(TowerWorksheetAudit::getWorksheetId, towerWorksheet.getWorksheetId())
                            .eq(TowerWorksheetAudit::getUserId, getLoginUserId())
            );
            if (audit != null) towerWorksheet.setNeedAudit(audit.getStatus().equals(0));
        }
        formatWorksheet(towerWorksheet, true);
        return success(towerWorksheet);
    }

    @ApiOperation("派单修改状态")
    @PostMapping("/worksheet/change-status")
    public ApiResult<?> worksheetChangeStatus(@RequestBody TowerWorksheet towerWorksheet) {
        towerWorksheetService.updateById(towerWorksheet);
        if (towerWorksheet.getStatus().equals(TowerConstants.WORKSHEET_STATUS_TO_ARRIVE)) {
            QueryWrapper<TowerWorksheetCheck> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("worksheet_id", towerWorksheet.getWorksheetId());
            towerWorksheetCheckService.remove(queryWrapper);
        } else if (towerWorksheet.getStatus().equals(TowerConstants.WORKSHEET_STATUS_DONE)) {
            TowerWorksheetDetail detail = towerWorksheetDetailService.getOne(
                    new LambdaQueryWrapper<TowerWorksheetDetail>()
                            .eq(TowerWorksheetDetail::getWorksheetId, towerWorksheet.getWorksheetId())
            );
            // 拆卸单修改设备状态
            if (detail.getWorkType().equals(2)) {
                towerEquipmentService.update(
                        new LambdaUpdateWrapper<TowerEquipment>()
                                .eq(TowerEquipment::getEquipmentId, detail.getEquipmentId())
                                .set(TowerEquipment::getStatus, 0)
                );
                TowerProject project = towerProjectService.getById(detail.getProjectId());
                project.setProjectStatus("完工");
                towerProjectService.updateById(project);
            }
        }
        return success("修改成功");
    }

    @ApiOperation("派单修改完成")
    @PostMapping("/worksheet/change-done")
    public ApiResult<?> worksheetChangeDone(@RequestBody TowerWorksheet towerWorksheet) {
        if (towerWorksheet.getDocumentHasDone() != null) towerWorksheet.setDocumentDoneTime(LocalDateTime.now());
        if (towerWorksheet.getAssetHasDone() != null) towerWorksheet.setAssetDoneTime(LocalDateTime.now());
        if (towerWorksheet.getFixHasDone() != null) towerWorksheet.setFixDoneTime(LocalDateTime.now());
        towerWorksheetService.updateById(towerWorksheet);
        TowerWorksheet towerWorksheet1 = towerWorksheetService.getById(towerWorksheet.getWorksheetId());
//        int carDispatchNum = towerWorksheetCarDispatchService.count(
//                new LambdaQueryWrapper<TowerWorksheetCarDispatch>().eq(TowerWorksheetCarDispatch::getWorksheetId, towerWorksheet.getWorksheetId())
//        );
        if (towerWorksheet1.getAssetHasDone().equals(1) && towerWorksheet1.getDocumentHasDone().equals(1) && towerWorksheet1.getFixHasDone().equals(1))
            towerWorksheet.setStatus(1);
        towerWorksheetService.updateById(towerWorksheet);
        return success("修改成功");
    }

    @ApiOperation("派单设置车辆")
    @PostMapping("/worksheet/set-car-dispatch")
    public ApiResult<?> worksheetSetCarDispatch(@RequestBody Map<String, ?> postBody) {
        Integer worksheetId = (Integer) postBody.get("worksheetId");
//        TowerWorksheet towerWorksheet1 = towerWorksheetService.getById(worksheetId);
        towerWorksheetCarDispatchService.remove(
                new LambdaQueryWrapper<TowerWorksheetCarDispatch>()
                        .eq(TowerWorksheetCarDispatch::getWorksheetId, worksheetId)
        );
        List<TowerWorksheetCarDispatch> carDispatchList = JSON.parseArray(JSON.toJSONBytes(postBody.get("carDispatchList")), TowerWorksheetCarDispatch.class);
        towerWorksheetCarDispatchService.saveBatch(carDispatchList);
//        if (towerWorksheet1.getAssetHasDone().equals(1) && towerWorksheet1.getDocumentHasDone().equals(1))
//            towerWorksheet1.setStatus(1);
//        towerWorksheetService.updateById(towerWorksheet1);
        return success("设置成功");
    }

    @ApiOperation("派单核验详情")
    @PostMapping("/worksheet/check/info")
    public ApiResult<?> worksheetCheckInfo(@RequestBody TowerWorksheetCheck towerWorksheetCheck) {
        return success(towerWorksheetCheckService.getOne(
                new LambdaQueryWrapper<TowerWorksheetCheck>()
                        .eq(TowerWorksheetCheck::getWorksheetId, towerWorksheetCheck.getWorksheetId())
                        .eq(TowerWorksheetCheck::getDeleted, 0)
        ));
    }

    @ApiOperation("派单核验")
    @PostMapping("/worksheet/check")
    public ApiResult<?> worksheetCheck(@RequestBody TowerWorksheetCheck towerWorksheetCheck) {
        towerWorksheetCheckService.remove(
                new LambdaQueryWrapper<TowerWorksheetCheck>()
                        .eq(TowerWorksheetCheck::getWorksheetId, towerWorksheetCheck.getWorksheetId())
        );
        towerWorksheetCheckService.save(towerWorksheetCheck);
        if (towerWorksheetCheck.getSave()) {
            TowerWorksheet towerWorksheet = new TowerWorksheet();
            towerWorksheet.setWorksheetId(towerWorksheetCheck.getWorksheetId());
            towerWorksheet.setStatus(TowerConstants.WORKSHEET_STATUS_TO_CONFIRM);
            towerWorksheetService.updateById(towerWorksheet);
            return success("核验成功");
        }
        return success("保存成功");
    }

    @ApiOperation("派单操作")
    @PostMapping("/worksheet/action")
    public ApiResult<?> worksheetAction(@RequestBody Map<String, ?> postBody) {
        Integer projectId = (Integer) postBody.get("projectId");
        Integer equipmentType = (Integer) postBody.get("equipmentType");
        Integer workType = (Integer) postBody.get("workType");
        TowerWorksheetDetail towerWorksheetDetail = JSON.parseObject(JSON.toJSONBytes(postBody.get("detail")), TowerWorksheetDetail.class);
        TowerWorksheet towerWorksheet;
        if (postBody.get("worksheetId") == null) {
            // 检查安装单
            TowerWorksheetDetail hasWorkType0 = towerWorksheetDetailService
                    .getOne(new QueryWrapper<TowerWorksheetDetail>()
                            .eq("work_type", TowerConstants.WORKSHEET_DETAIL_WORK_TYPE_0)
                            .eq("project_id", projectId)
                            .eq("equipment_id", towerWorksheetDetail.getEquipmentId())
                            .last("limit 1")
                    );
//            if (hasWorkType0 != null) {
//                if (workType.equals(TowerConstants.WORKSHEET_DETAIL_WORK_TYPE_0)) return fail("已存在安装单");
//            } else {
            if (hasWorkType0 == null && !workType.equals(TowerConstants.WORKSHEET_DETAIL_WORK_TYPE_0))
                return fail("没有安装单,无法创建");
//            }

            if (workType.equals(TowerConstants.WORKSHEET_DETAIL_WORK_TYPE_2)) {
                // 检查拆卸单
                int workType2num = towerWorksheetDetailService
                        .count(new QueryWrapper<TowerWorksheetDetail>()
                                .eq("work_type", TowerConstants.WORKSHEET_DETAIL_WORK_TYPE_2)
                                .eq("project_id", projectId)
                                .eq("equipment_id", towerWorksheetDetail.getEquipmentId())
                        );
                System.out.println("workType2num: " + workType2num);
                if (workType2num > 0) return fail("已有拆卸单,无法创建");
            }
            towerWorksheet = new TowerWorksheet();
        } else towerWorksheet = towerWorksheetService.getById((Integer) postBody.get("worksheetId"));
        towerWorksheet.setType((Integer) postBody.get("type"));
        towerWorksheet.setStartUid((Integer) postBody.get("startUid"));
        towerWorksheet.setProjectId(projectId);
        towerWorksheet.setReceiveDate((String) postBody.get("receiveDate"));
        towerWorksheet.setProductionMangerUid((Integer) postBody.get("productionMangerUid"));
        towerWorksheet.setWorkType(workType);
        towerWorksheet.setEquipmentType(equipmentType);
        towerWorksheet.setPlanInDateInit((String) postBody.get("planInDateInit"));
        towerWorksheet.setContactPhone((String) postBody.get("contactPhone"));
        towerWorksheet.setDocumentUid((Integer) postBody.get("documentUid"));
        towerWorksheet.setAssetUid((Integer) postBody.get("assetUid"));
        towerWorksheet.setCarDispatchUid((Integer) postBody.get("carDispatchUid"));
        towerWorksheet.setFixUid((Integer) postBody.get("fixUid"));
        towerWorksheet.setParentWorksheetId((Integer) postBody.get("parentWorksheetId"));
        towerWorksheet.setAddress((String) postBody.get("address"));

        List<TowerWorksheetAudit> auditList = JSON.parseArray(JSON.toJSONBytes(postBody.get("auditList")), TowerWorksheetAudit.class);
        boolean hasAudit = !auditList.isEmpty();
        if (hasAudit) towerWorksheet.setAuditStatus(1);
        else towerWorksheet.setAuditStatus(0);
        if (towerWorksheet.getWorksheetId() == null) towerWorksheetService.save(towerWorksheet);
        else towerWorksheetService.updateById(towerWorksheet);
        Integer worksheetId = towerWorksheet.getWorksheetId();
        towerWorksheetDetail.setWorksheetId(worksheetId);
        towerWorksheetDetail.setProjectId(projectId);
        if (!hasAudit) towerEquipmentService.update(
                new LambdaUpdateWrapper<TowerEquipment>()
                        .eq(TowerEquipment::getEquipmentId, towerWorksheetDetail.getEquipmentId())
                        .set(TowerEquipment::getStatus, 4)
        );
        if (towerWorksheetDetail.getDetailId() == null) towerWorksheetDetailService.save(towerWorksheetDetail);
        else towerWorksheetDetailService.updateById(towerWorksheetDetail);
        // 更新设备为在用
        TowerEquipment equipment = towerEquipmentService.getById(towerWorksheetDetail.getEquipmentId());
        equipment.setStatus(4);
        towerEquipmentService.updateById(equipment);
        // 审核人
        if (hasAudit) {
            for (TowerWorksheetAudit audit : auditList) {
                audit.setWorksheetId(worksheetId);
            }
            towerWorksheetAuditService.remove(
                    new LambdaQueryWrapper<TowerWorksheetAudit>().eq(TowerWorksheetAudit::getWorksheetId, worksheetId)
            );
            towerWorksheetAuditService.saveBatch(auditList);
        }
        // 项目成员
        List<TowerProjectUser> projectUserList = new ArrayList<>();
        TowerProjectUser startUser = new TowerProjectUser();
        startUser.setUserId((Integer) postBody.get("startUid"));
        startUser.setRole(20);
        startUser.setProjectId(projectId);
        projectUserList.add(startUser);

        TowerProjectUser productionMangerUser = new TowerProjectUser();
        productionMangerUser.setUserId((Integer) postBody.get("productionMangerUid"));
        productionMangerUser.setRole(30);
        productionMangerUser.setProjectId(projectId);
        projectUserList.add(startUser);

        TowerProjectUser documentUser = new TowerProjectUser();
        documentUser.setUserId((Integer) postBody.get("documentUid"));
        documentUser.setRole(20);
        documentUser.setProjectId(projectId);
        projectUserList.add(documentUser);

        TowerProjectUser assetUser = new TowerProjectUser();
        assetUser.setUserId((Integer) postBody.get("assetUid"));
        assetUser.setRole(20);
        assetUser.setProjectId(projectId);
        projectUserList.add(assetUser);

        TowerProjectUser carDispatchUser = new TowerProjectUser();
        carDispatchUser.setUserId((Integer) postBody.get("carDispatchUid"));
        carDispatchUser.setRole(20);
        carDispatchUser.setProjectId(projectId);
        projectUserList.add(carDispatchUser);


        towerProjectUserService.saveBatch(projectUserList);
        return success("创建成功");
    }

    @ApiOperation("派单")
    @PostMapping("/worksheet/send")
    public ApiResult<?> worksheetSend(@RequestBody Map<String, ?> postBody) {
        TowerWorksheet towerWorksheet = postBody.get("worksheet") != null ? JSON.parseObject(JSON.toJSONBytes(postBody.get("worksheet")), TowerWorksheet.class) : null;
        TowerWorksheetDetail towerWorksheetDetail = postBody.get("detail") != null ? JSON.parseObject(JSON.toJSONBytes(postBody.get("detail")), TowerWorksheetDetail.class) : null;
        TowerWorksheetSetUp towerWorksheetSetUp = postBody.get("setUp") != null ? JSON.parseObject(JSON.toJSONBytes(postBody.get("setUp")), TowerWorksheetSetUp.class) : null;
        List<TowerWorksheetParts> towerWorksheetParts = postBody.get("parts") != null ? JSON.parseArray(JSON.toJSONBytes(postBody.get("parts")), TowerWorksheetParts.class) : null;
        List<TowerWorksheetCarDispatch> towerWorksheetCarDispatches = postBody.get("carDispatchList") != null ? JSON.parseArray(JSON.toJSONBytes(postBody.get("carDispatchList")), TowerWorksheetCarDispatch.class) : null;

        if (towerWorksheet != null) towerWorksheetService.updateById(towerWorksheet);
        if (towerWorksheetDetail != null) towerWorksheetDetailService.updateById(towerWorksheetDetail);
        if (towerWorksheetSetUp != null) towerWorksheetSetUpService.save(towerWorksheetSetUp);
        if (towerWorksheetParts != null) towerWorksheetPartsService.saveBatch(towerWorksheetParts);
        if (towerWorksheetCarDispatches != null)
            towerWorksheetCarDispatchService.saveBatch(towerWorksheetCarDispatches);

        return success("派单成功");
    }

    @ApiOperation("取消")
    @PostMapping("/worksheet/cancel")
    public ApiResult<?> worksheetCancel(@RequestBody TowerWorksheet towerWorksheet) {
        TowerWorksheet worksheet = towerWorksheetService.getById(towerWorksheet.getWorksheetId());
        if (!worksheet.getAuditStatus().equals(2) && worksheet.getStatus().equals(2)) {
            if (towerWorksheetService.removeById(towerWorksheet)) return success("取消成功");
        }
        return fail("无法取消");
    }

    @ApiOperation("配件列表")
    @PostMapping("/cate")
    public ApiResult<List<Category>> cateList(@RequestBody CategoryParam param) {
        List<Category> list = categoryService.listRel(param);
        for (Category category : list) {
            QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("parent_id", category.getCategoryId());
            category.setChildren(categoryService.list(queryWrapper));
        }
        return success(list);
    }

    @ApiOperation("生产主管列表")
    @PostMapping("/user/list-by-user-level")
    public ApiResult<List<User>> productionManagerList(@RequestBody UserParam userParam) {
        userParam.setDeleted(0);
        System.out.println("userParam   " + userParam);
        return success(userService.listRel(userParam));
    }

    @ApiOperation("项目列表")
    @PostMapping("/project/list")
    public ApiResult<PageResult<TowerProject>> getProjectList(@RequestBody TowerProjectParam param) {
        param.setDeleted(0);
        PageResult<TowerProject> list = towerProjectService.pageRel(param);
        // 检查各种派单数量
        for (TowerProject towerProject : list.getList()) {
            Map<Integer, Integer> resList = new ArrayMap<>();
            QueryWrapper<TowerWorksheet> queryWrapper0 = new QueryWrapper<>();
            queryWrapper0.eq("type", TowerConstants.WORKSHEET_TYPE_SET_UP)
                    .eq("equipment_type", param.getWorksheetEquipType())
                    .eq("work_type", TowerConstants.WORKSHEET_DETAIL_WORK_TYPE_0);
            resList.put(TowerConstants.WORKSHEET_DETAIL_WORK_TYPE_0, towerWorksheetService.count(queryWrapper0));

            QueryWrapper<TowerWorksheet> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("type", TowerConstants.WORKSHEET_TYPE_SET_UP)
                    .eq("equipment_type", param.getWorksheetEquipType())
                    .eq("work_type", TowerConstants.WORKSHEET_DETAIL_WORK_TYPE_1);
            resList.put(TowerConstants.WORKSHEET_DETAIL_WORK_TYPE_1, towerWorksheetService.count(queryWrapper1));

            QueryWrapper<TowerWorksheet> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("type", TowerConstants.WORKSHEET_TYPE_SET_UP)
                    .eq("equipment_type", param.getWorksheetEquipType())
                    .eq("work_type", TowerConstants.WORKSHEET_DETAIL_WORK_TYPE_2);
            resList.put(TowerConstants.WORKSHEET_DETAIL_WORK_TYPE_2, towerWorksheetService.count(queryWrapper2));
            towerProject.setWorksheetWorkTypeNumList(resList);
            towerProject.setOrders(
                    new HashSet<>(
                            towerProjectOrderService.list(
                                    new MPJLambdaWrapper<TowerProjectOrder>()
                                            .selectAll(TowerProjectOrder.class)
                                            .select(TowerEquipment::getManufactor, TowerEquipment::getScrapDate)
                                            .leftJoin(TowerEquipment.class, TowerEquipment::getEquipmentId, TowerProjectOrder::getEquipmentId)
                                            .eq(TowerProjectOrder::getProjectId, towerProject.getProjectId())
                                            .eq(TowerProjectOrder::getDeleted, 0)
                                            .orderByDesc(TowerProjectOrder::getCreateTime)
                            )
                    )

            );
        }
        return success(list);
    }

    @ApiOperation("型号列表")
    @PostMapping("/equipment/list")
    public ApiResult<List<TowerEquipment>> getEquipmentList(@RequestBody TowerEquipmentParam param) {
        return success(towerEquipmentService.listRel(param));
    }

    @ApiOperation("审核详情")
    @PostMapping("/worksheet/audit-info")
    public ApiResult<TowerWorksheetAudit> worksheetAuditInfo(@RequestBody TowerWorksheetAuditParam param) {
        TowerWorksheetAudit towerWorksheetAudit = towerWorksheetAuditService.getOne(
                new LambdaQueryWrapper<TowerWorksheetAudit>()
                        .eq(TowerWorksheetAudit::getWorksheetId, param.getWorksheetId())
                        .eq(TowerWorksheetAudit::getUserId, getLoginUserId())
        );
        return success(towerWorksheetAudit);
    }

    @ApiOperation("审核列表")
    @PostMapping("/worksheet/audit-list")
    public ApiResult<List<TowerWorksheetAudit>> worksheetAuditList(@RequestBody TowerWorksheetAuditParam param) {
        List<TowerWorksheetAudit> list = towerWorksheetAuditService.listRel(param);
        for (TowerWorksheetAudit towerWorksheetAudit : list) {
            towerWorksheetAudit.setUser(userService.getById(towerWorksheetAudit.getUserId()));
        }
        return success(list);
    }

    @ApiOperation("审核")
    @PostMapping("/worksheet/audit")
    public ApiResult<?> doWorksheetAudit(@RequestBody TowerWorksheetAudit towerWorksheetAudit) {
        TowerWorksheet towerWorksheet = towerWorksheetService.getById(towerWorksheetAudit.getWorksheetId());
        TowerWorksheetAudit towerWorksheetAudit1 = towerWorksheetAuditService.getOne(
                new LambdaQueryWrapper<TowerWorksheetAudit>()
                        .eq(TowerWorksheetAudit::getWorksheetId, towerWorksheetAudit.getWorksheetId())
                        .eq(TowerWorksheetAudit::getUserId, getLoginUserId())
        );
        if (towerWorksheetAudit1 == null) return fail("无法操作审核");
        int status = 2;
        if (towerWorksheetAudit.getStatus().equals(2)) {
            status = 3;
            towerWorksheet.setRefuseReason(towerWorksheetAudit.getRefuseReason());
        }
        towerWorksheetAudit1.setStatus(towerWorksheet.getAuditStatus());
        towerWorksheetAudit1.setRefuseReason(towerWorksheetAudit.getRefuseReason());
        towerWorksheetAuditService.updateById(towerWorksheetAudit1);
        List<TowerWorksheetAudit> auditList = towerWorksheetAuditService.list(
                new LambdaQueryWrapper<TowerWorksheetAudit>()
                        .eq(TowerWorksheetAudit::getWorksheetId, towerWorksheetAudit.getWorksheetId())
        );
        int passNum = 0;
        int unAuditNum = 0;
        for (TowerWorksheetAudit audit : auditList) {
            if (audit.getStatus().equals(1)) passNum++;
            else if (audit.getStatus().equals(0)) unAuditNum++;
        }
        if (unAuditNum == 0 && passNum == auditList.size()) status = 2;
        else if (unAuditNum == 0 && passNum < auditList.size()) status = 3;
        towerWorksheet.setAuditStatus(status);
        if (status == 2) {
            TowerWorksheetDetail towerWorksheetDetail = towerWorksheetDetailService.getOne(
                    new LambdaQueryWrapper<TowerWorksheetDetail>()
                            .eq(TowerWorksheetDetail::getWorksheetId, towerWorksheetAudit.getWorksheetId())
            );
            towerEquipmentService.update(
                    new LambdaUpdateWrapper<TowerEquipment>()
                            .eq(TowerEquipment::getEquipmentId, towerWorksheetDetail.getEquipmentId())
                            .set(TowerEquipment::getStatus, 4)
            );
        }
        towerWorksheetService.updateById(towerWorksheet);
        return success();
    }

    @ApiOperation("审核")
    @PostMapping("/equipment")
    public ApiResult<?> equipment(@RequestBody TowerEquipmentParam towerEquipmentParam) {
        return success(towerEquipmentService.getById(towerEquipmentParam.getEquipmentId()));
    }

    private Integer sumData(User user, Integer status) {
        return sumData(user, status, false);
    }

    private Integer sumData(User user, Integer status, boolean statusIsNeq) {
        MPJLambdaWrapper<TowerWorksheet> queryWrapper = makeQueryWrapper(user, status, statusIsNeq);
        if (queryWrapper != null) return towerWorksheetService.count(queryWrapper);
        else return -1;
    }

    private MPJLambdaWrapper<TowerWorksheet> makeQueryWrapper(User user, Integer status, boolean statusIsNeq) {
        MPJLambdaWrapper<TowerWorksheet> towerWorksheetLambdaQueryWrapper = new MPJLambdaWrapper<>();
        if (!status.equals(-2)) {
            if (user.getUserLevel().equals(TowerConstants.USER_LEVEL_NONE)) return null;
            else if (user.getUserLevel().equals(TowerConstants.USER_LEVEL_CLASS_MANAGER)) {
                towerWorksheetLambdaQueryWrapper.eq("class_manager", user.getUserId());
            } else if (user.getUserLevel().equals(TowerConstants.USER_LEVEL_DOCUMENTER)) {
                towerWorksheetLambdaQueryWrapper.eq("document_uid", user.getUserId());
            } else if (user.getUserLevel().equals(TowerConstants.USER_LEVEL_OPERATOR)) {
                towerWorksheetLambdaQueryWrapper.eq("start_uid", user.getUserId());
            } else if (user.getUserLevel().equals(TowerConstants.USER_LEVEL_PRODUCTION_MANAGER)) {
                towerWorksheetLambdaQueryWrapper.eq("production_manger_uid", user.getUserId());
            } else if (user.getUserLevel().equals(TowerConstants.USER_LEVEL_ASSET)) {
                towerWorksheetLambdaQueryWrapper.eq("asset_uid", user.getUserId());
            } else if (user.getUserLevel().equals(TowerConstants.USER_LEVEL_CAR_DISPATCH)) {
                towerWorksheetLambdaQueryWrapper.eq("car_dispatch_uid", user.getUserId());
            } else if (user.getUserLevel().equals(TowerConstants.USER_LEVEL_FIX)) {
                towerWorksheetLambdaQueryWrapper.eq("fix_uid", user.getUserId());
            }
        }
        towerWorksheetLambdaQueryWrapper.leftJoin(TowerProject.class, TowerProject::getProjectId, TowerWorksheet::getProjectId);
        if (!status.equals(-1)) {
            if (status.equals(-2)) {
                towerWorksheetLambdaQueryWrapper.eq(TowerWorksheet::getAuditStatus, 1);
            } else {
                if (!statusIsNeq) towerWorksheetLambdaQueryWrapper.eq(TowerWorksheet::getStatus, status);
                else towerWorksheetLambdaQueryWrapper.ne(TowerWorksheet::getStatus, status);
            }
        }
        return towerWorksheetLambdaQueryWrapper;
    }

    private void formatWorksheet(TowerWorksheet towerWorksheet, boolean withAll) {
        if (towerWorksheet.getProductionMangerUid() != null) {
            towerWorksheet.setProductionMangerUser(userService.getById(towerWorksheet.getProductionMangerUid()));
        }
        if (towerWorksheet.getDocumentUid() != null) {
            towerWorksheet.setDocumentUser(userService.getById(towerWorksheet.getDocumentUid()));
        }
        if (towerWorksheet.getAssetUid() != null) {
            towerWorksheet.setAssetUser(userService.getById(towerWorksheet.getAssetUid()));
        }
        if (towerWorksheet.getCarDispatchUid() != null) {
            towerWorksheet.setCarDispatchUser(userService.getById(towerWorksheet.getCarDispatchUid()));
        }
        if (towerWorksheet.getClassManager() != null) {
            towerWorksheet.setClassManagerUser(userService.getById(towerWorksheet.getClassManager()));
        }
        if (towerWorksheet.getFixUid() != null) {
            towerWorksheet.setFixUser(userService.getById(towerWorksheet.getFixUid()));
        }
        MPJLambdaWrapper<TowerWorksheetDetail> queryWrapperDetail = new MPJLambdaWrapper<>();
        queryWrapperDetail.eq(TowerWorksheetDetail::getWorksheetId, towerWorksheet.getWorksheetId())
                .selectAll(TowerWorksheetDetail.class)
                .select(TowerEquipment::getEquipmentNo, TowerEquipment::getFactoryNo, TowerEquipment::getModel)
                .selectAs(TowerEquipment::getName, TowerEquipment::getEquipmentName)
                .leftJoin(TowerEquipment.class, TowerEquipment::getEquipmentId, TowerWorksheetDetail::getEquipmentId);
        TowerWorksheetDetail towerWorksheetDetail = towerWorksheetDetailService.getOne(queryWrapperDetail);
        // 累计加高高度
        TowerWorksheetDetail towerWorksheetDetailOnlyAdd = towerWorksheetDetailService.getOne(
                new QueryWrapper<TowerWorksheetDetail>()
                        .select("SUM(`setup_height`) as `total_add_height`")
                        .eq("work_type", 1)
                        .eq("project_id", towerWorksheet.getProjectId())
                        .eq("equipment_id", towerWorksheetDetail.getEquipmentId())
                        .isNotNull("`setup_height`")
        );
        if (towerWorksheetDetailOnlyAdd != null)
            towerWorksheetDetail.setTotalAddHeight(towerWorksheetDetailOnlyAdd.getTotalAddHeight());
        else towerWorksheetDetail.setTotalAddHeight(BigDecimal.ZERO);
        towerWorksheetDetail.setEquipment(towerEquipmentService.getOne(
                new LambdaQueryWrapper<TowerEquipment>()
                        .eq(TowerEquipment::getEquipmentId, towerWorksheetDetail.getEquipmentId())
        ));

        if (!towerWorksheetDetail.getWorkType().equals(0)) {
            MPJLambdaWrapper<TowerWorksheetDetail> queryWrapperDetailType0 = new MPJLambdaWrapper<>();
            queryWrapperDetailType0.eq(TowerWorksheetDetail::getProjectId, towerWorksheet.getProjectId())
                    .eq(TowerWorksheetDetail::getWorkType, 0)
                    .eq(TowerWorksheetDetail::getEquipmentId, towerWorksheetDetail.getEquipmentId())
                    .selectAll(TowerWorksheetDetail.class)
                    .select(TowerEquipment::getEquipmentNo)
                    .select(TowerEquipment::getFactoryNo)
                    .selectAs(TowerEquipment::getName, TowerEquipment::getEquipmentName)
                    .select(TowerEquipment::getModel)
                    .leftJoin(TowerEquipment.class, TowerEquipment::getEquipmentId, TowerWorksheetDetail::getEquipmentId);
            TowerWorksheetDetail towerWorksheetDetailType0 = towerWorksheetDetailService.getOne(queryWrapperDetailType0);
            towerWorksheet.setDetailType0(towerWorksheetDetailType0);
            if (towerWorksheetDetail.getWorkType().equals(2)) {
                List<TowerWorksheetDetail> allDetail = towerWorksheetDetailService.list(
                        new LambdaQueryWrapper<TowerWorksheetDetail>()
                                .eq(TowerWorksheetDetail::getProjectId, towerWorksheetDetail.getProjectId())
                                .ne(TowerWorksheetDetail::getWorkType, 2)
                );
                BigDecimal finalSetupHeight = BigDecimal.ZERO;
                if (!allDetail.isEmpty()) {
                    for (TowerWorksheetDetail detail : allDetail) {
                        if (detail.getSetupHeight() != null)
                            finalSetupHeight = finalSetupHeight.add(detail.getSetupHeight());
                    }
                }
                towerWorksheetDetail.setFinalSetupHeight(finalSetupHeight);
            }
        }
        towerWorksheet.setDetail(towerWorksheetDetail);
        if (!towerWorksheet.getAuditStatus().equals(0)) {
            List<TowerWorksheetAudit> towerWorksheetAuditList = towerWorksheetAuditService.list(
                    new LambdaQueryWrapper<TowerWorksheetAudit>().eq(TowerWorksheetAudit::getWorksheetId, towerWorksheet.getWorksheetId())
            );
            List<User> auditUserList = userService.listByIds(towerWorksheetAuditList.stream().map(TowerWorksheetAudit::getUserId).collect(Collectors.toList()));
            for (User user : auditUserList) {
                user.setAuditStatus(towerWorksheetAuditList.stream().filter(audit -> audit.getUserId().equals(user.getUserId())).findFirst().get().getStatus());
            }
            towerWorksheet.setAuditList(auditUserList);
        }
        towerWorksheet.setCarDispatchList(towerWorksheetCarDispatchService.list(
                new LambdaQueryWrapper<TowerWorksheetCarDispatch>().eq(TowerWorksheetCarDispatch::getWorksheetId, towerWorksheet.getWorksheetId())
        ));
        if (withAll) {
            List<TowerWorksheetParts> towerWorksheetParts = towerWorksheetPartsService.list(
                    new MPJLambdaWrapper<TowerWorksheetParts>()
                            .selectAll(TowerWorksheetParts.class)
                            .select("parent.title as parent_parts_title")
                            .select("parts.title as parts_title")
                            .leftJoin("shop_category parent on parent.category_id = t.parent_id")
                            .leftJoin("shop_category parts on parts.category_id = t.cate_id")
                            .eq(TowerWorksheetParts::getWorksheetId, towerWorksheet.getWorksheetId()));
            towerWorksheet.setParts(towerWorksheetParts);

            TowerWorksheetCheck towerWorksheetCheck = towerWorksheetCheckService.getOne(
                    new MPJLambdaWrapper<TowerWorksheetCheck>()
                            .selectAll(TowerWorksheetCheck.class)
                            .select(User::getNickname)
                            .leftJoin(User.class, User::getUserId, TowerWorksheetCheck::getUserId)
                            .eq(TowerWorksheetCheck::getWorksheetId, towerWorksheet.getWorksheetId()));
            towerWorksheet.setCheck(towerWorksheetCheck);

            TowerWorksheetSetUp towerWorksheetSetUp = towerWorksheetSetUpService.getOne(
                    new LambdaQueryWrapper<TowerWorksheetSetUp>()
                            .eq(TowerWorksheetSetUp::getWorksheetId, towerWorksheet.getWorksheetId()));
            towerWorksheet.setSetUp(towerWorksheetSetUp);
        }
//        return towerWorksheet;
    }


}
