package com.gxwebsoft.tower.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.yulichang.query.MPJLambdaQueryWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.service.UserService;
import com.gxwebsoft.tower.entity.*;
import com.gxwebsoft.tower.service.*;
import com.gxwebsoft.tower.param.TowerWorksheetParam;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.annotation.OperationLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 派单管理控制器
 *
 * @author 科技小王子
 * @since 2023-07-02 16:15:31
 */
@Api(tags = "派单管理管理")
@RestController
@RequestMapping("/api/tower/tower-worksheet")
public class TowerWorksheetController extends BaseController {
    @Resource
    private TowerWorksheetService towerWorksheetService;
    @Resource
    private UserService userService;
    @Resource
    private TowerWorksheetDetailService towerWorksheetDetailService;
    @Resource
    private TowerWorksheetSetUpService towerWorksheetSetUpService;
    @Resource
    private TowerWorksheetCheckService towerWorksheetCheckService;
    @Resource
    private TowerWorksheetPartsService towerWorksheetPartsService;
    @Resource
    private TowerEquipmentService towerEquipmentService;
    @Resource
    private TowerWorksheetCarDispatchService  towerWorksheetCarDispatchService;
    @Resource
    private TowerWorksheetAuditService towerWorksheetAuditService;

    @PreAuthorize("hasAuthority('tower:towerWorksheet:list')")
    @OperationLog
    @ApiOperation("分页查询派单管理")
    @GetMapping("/page")
    public ApiResult<PageResult<TowerWorksheet>> page(TowerWorksheetParam param) {
        PageParam<TowerWorksheet, TowerWorksheetParam> page = new PageParam<>(param);
        page.setDefaultOrder("create_time desc");
        MPJLambdaWrapper<TowerWorksheet> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(TowerWorksheet.class)
                .select(TowerProject::getProjectName)
                .leftJoin(TowerProject.class, TowerProject::getProjectId, TowerWorksheet::getProjectId)
                .groupBy(TowerProject::getProjectId);
        IPage<TowerWorksheet> pageRes = towerWorksheetService.page(page, queryWrapper);
        for (TowerWorksheet towerWorksheet : pageRes.getRecords()) {
            if (towerWorksheet.getProductionMangerUid() != null) {
                towerWorksheet.setProductionMangerUser(userService.getById(towerWorksheet.getProductionMangerUid()));
            }
            if (towerWorksheet.getDocumentUid() != null) {
                towerWorksheet.setDocumentUser(userService.getById(towerWorksheet.getDocumentUid()));
            }
            if (towerWorksheet.getClassManager() != null) {
                towerWorksheet.setClassManagerUser(userService.getById(towerWorksheet.getClassManager()));
            }
            towerWorksheet.setStartUser(userService.getById(towerWorksheet.getStartUid()));
        }
        return success(pageRes);
        // 使用关联查询
        //return success(towerWorksheetService.pageRel(param));
    }

    @PreAuthorize("hasAuthority('tower:towerWorksheet:list')")
    @OperationLog
    @ApiOperation("查询全部派单管理")
    @GetMapping()
    public ApiResult<List<TowerWorksheet>> list(TowerWorksheetParam param) {
        PageParam<TowerWorksheet, TowerWorksheetParam> page = new PageParam<>(param);
        page.setDefaultOrder("create_time desc");
        return success(towerWorksheetService.list(page.getOrderWrapper()));
        // 使用关联查询
        //return success(towerWorksheetService.listRel(param));
    }

    @PreAuthorize("hasAuthority('tower:towerWorksheet:list')")
    @OperationLog
    @ApiOperation("根据id查询派单管理")
    @GetMapping("/{id}")
    public ApiResult<TowerWorksheet> get(@PathVariable("id") Integer id) {
        MPJLambdaWrapper<TowerWorksheet> mpjLambdaWrapper = new MPJLambdaWrapper<>();
        mpjLambdaWrapper.eq(TowerWorksheet::getWorksheetId, id)
                .selectAll(TowerWorksheet.class)
                .select(TowerProject::getProjectName)
                .select(TowerProject::getProjectAddress)
                .select(TowerProject::getProjectRegion)
                .leftJoin(TowerProject.class, TowerProject::getProjectId, TowerWorksheet::getProjectId);
        TowerWorksheet towerWorksheet = towerWorksheetService.getOne(mpjLambdaWrapper);

        MPJLambdaWrapper<TowerWorksheetDetail> queryWrapperDetail = new MPJLambdaWrapper<>();
        queryWrapperDetail.eq(TowerWorksheetDetail::getWorksheetId, towerWorksheet.getWorksheetId())
                .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 towerWorksheetDetail = towerWorksheetDetailService.getOne(queryWrapperDetail);
        towerWorksheet.setDetail(towerWorksheetDetail);

        towerWorksheet.setSetUp(towerWorksheetSetUpService
                .getOne(new LambdaQueryWrapper<TowerWorksheetSetUp>()
                        .eq(TowerWorksheetSetUp::getWorksheetId, towerWorksheet.getWorksheetId())));
        towerWorksheet.setCheck(towerWorksheetCheckService
                .getOne(new LambdaQueryWrapper<TowerWorksheetCheck>()
                        .eq(TowerWorksheetCheck::getWorksheetId, towerWorksheet.getWorksheetId())));
        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);
        if (towerWorksheet.getProductionMangerUid() != null) {
            towerWorksheet.setProductionMangerUser(userService.getById(towerWorksheet.getProductionMangerUid()));
        }
        if (towerWorksheet.getDocumentUid() != null) {
            towerWorksheet.setDocumentUser(userService.getById(towerWorksheet.getDocumentUid()));
        }
        if (towerWorksheet.getClassManager() != null) {
            towerWorksheet.setClassManagerUser(userService.getById(towerWorksheet.getClassManager()));
        }
        towerWorksheet.setStartUser(userService.getById(towerWorksheet.getStartUid()));
        TowerWorksheetSetUp towerWorksheetSetUp = towerWorksheetSetUpService.getOne(
                new LambdaQueryWrapper<TowerWorksheetSetUp>()
                        .eq(TowerWorksheetSetUp::getWorksheetId, towerWorksheet.getWorksheetId()));
        towerWorksheet.setSetUp(towerWorksheetSetUp);
        return success(towerWorksheet);
        // 使用关联查询
        //return success(towerWorksheetService.getByIdRel(id));
    }

    @PreAuthorize("hasAuthority('tower:towerWorksheet:list')")
    @OperationLog
    @ApiOperation("根据id查询派单管理")
    @PostMapping("/by-work-type")
    public ApiResult<?> infoByWorkType(@RequestBody TowerWorksheet towerWorksheetParam) {
        MPJLambdaWrapper<TowerWorksheetDetail> queryWrapperDetail = new MPJLambdaWrapper<>();
        queryWrapperDetail.eq(TowerWorksheetDetail::getProjectId, towerWorksheetParam.getProjectId())
                .eq(TowerWorksheetDetail::getWorkType, towerWorksheetParam.getWorkType())
                .selectAll(TowerWorksheetDetail.class)
                .select(TowerEquipment::getEquipmentNo)
                .select(TowerEquipment::getFactoryNo)
                .selectAs(TowerEquipment::getName, TowerEquipment::getEquipmentName)
                .select(TowerEquipment::getModel)
                .leftJoin(TowerEquipment.class, TowerEquipment::getEquipmentId, TowerWorksheetDetail::getEquipmentId);
        List<TowerWorksheetDetail> towerWorksheetDetailList = towerWorksheetDetailService.list(queryWrapperDetail);

        if (towerWorksheetDetailList != null && !towerWorksheetDetailList.isEmpty()) {
            List<TowerWorksheet> worksheetList = new ArrayList<>();
            for (TowerWorksheetDetail towerWorksheetDetail : towerWorksheetDetailList) {
                MPJLambdaWrapper<TowerWorksheet> mpjLambdaWrapper = new MPJLambdaWrapper<>();
                mpjLambdaWrapper.eq(TowerWorksheet::getWorksheetId, towerWorksheetDetail.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);
                towerWorksheetDetail.setEquipment(towerEquipmentService.getById(towerWorksheetDetail.getEquipmentId()));
                towerWorksheet.setDetail(towerWorksheetDetail);


                towerWorksheet.setSetUp(towerWorksheetSetUpService
                        .getOne(new LambdaQueryWrapper<TowerWorksheetSetUp>()
                                .eq(TowerWorksheetSetUp::getWorksheetId, towerWorksheet.getWorksheetId())));
                TowerWorksheetCheck towerWorksheetCheck = towerWorksheetCheckService
                        .getOne(new LambdaQueryWrapper<TowerWorksheetCheck>()
                                .eq(TowerWorksheetCheck::getWorksheetId, towerWorksheet.getWorksheetId()));
                if (towerWorksheetCheck != null) towerWorksheetCheck.setNickname(userService.getById(towerWorksheetCheck.getUserId()).getNickname());
                towerWorksheet.setCheck(towerWorksheetCheck);
                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);
                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()));
                }
                towerWorksheet.setStartUser(userService.getById(towerWorksheet.getStartUid()));
                TowerWorksheetSetUp towerWorksheetSetUp = towerWorksheetSetUpService.getOne(
                        new LambdaQueryWrapper<TowerWorksheetSetUp>()
                                .eq(TowerWorksheetSetUp::getWorksheetId, towerWorksheet.getWorksheetId()));
                towerWorksheet.setSetUp(towerWorksheetSetUp);
                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())
                ));
                worksheetList.add(towerWorksheet);
            }
            return success(worksheetList);
        }else return fail("数据异常");
        // 使用关联查询
        //return success(towerWorksheetService.getByIdRel(id));
    }

    @PreAuthorize("hasAuthority('tower:towerWorksheet:save')")
    @OperationLog
    @ApiOperation("添加派单管理")
    @PostMapping()
    public ApiResult<?> save(@RequestBody TowerWorksheet towerWorksheet) {
        if (towerWorksheetService.save(towerWorksheet)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('tower:towerWorksheet:update')")
    @OperationLog
    @ApiOperation("修改派单管理")
    @PutMapping()
    public ApiResult<?> update(@RequestBody TowerWorksheet towerWorksheet) {
        if (towerWorksheetService.updateById(towerWorksheet)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('tower:towerWorksheet:remove')")
    @OperationLog
    @ApiOperation("删除派单管理")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (towerWorksheetService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('tower:towerWorksheet:save')")
    @OperationLog
    @ApiOperation("批量添加派单管理")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<TowerWorksheet> list) {
        if (towerWorksheetService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('tower:towerWorksheet:update')")
    @OperationLog
    @ApiOperation("批量修改派单管理")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<TowerWorksheet> batchParam) {
        if (batchParam.update(towerWorksheetService, "worksheet_id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('tower:towerWorksheet:remove')")
    @OperationLog
    @ApiOperation("批量删除派单管理")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (towerWorksheetService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

}
