package com.yeejoin.precontrol.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Joiner;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.DepartmentModel;
import com.yeejoin.precontrol.common.dto.CommonPageableDto;
import com.yeejoin.precontrol.common.entity.*;
import com.yeejoin.precontrol.common.enums.TaskPersonFileEnum;
import com.yeejoin.precontrol.common.enums.TaskPersonTypeEnum;
import com.yeejoin.precontrol.common.enums.TaskTypeEnum;
import com.yeejoin.precontrol.common.exception.BaseException;
import com.yeejoin.precontrol.common.service.*;
import com.yeejoin.precontrol.common.utils.StringUtil;
import com.yeejoin.precontrol.common.vo.visual.RiskJobItemInputVo;
import com.yeejoin.precontrol.common.vo.visual.WorkTicketVo;
import com.yeejoin.precontrol.controller.publics.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 可视化作业活动Api
 *
 * @author duanwei
 * @date 2020-11-16
 */
@RestController
@Api(tags = "可视化作业活动Api")
@RequestMapping(value = "/visual", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Slf4j
public class VisualizationController extends BaseController {
    /**
     * 任务服务
     */
    @Autowired
    ITaskService iTaskService;
    /**
     * 任务与附件关系服务
     */
    @Autowired
    ITaskPersonFileService iTaskPersonFileService;

    @Autowired
    IPersonAscriptionService iPersonAscriptionService;

    @Autowired
    ICompanyService iCompanyService;

    /**
     * 任务与人服务
     */
    @Autowired
    ITaskPersonService iTaskPersonService;
    /**
     * 三交三查服务
     */
    @Autowired
    ITaskPaycheckService iTaskPaycheckService;
    /**
     * 违章管理服务
     */
    @Autowired
    IBadManagementService iBadManagementService;
    /**
     * 人员服务
     */
    @Autowired
    IPersonService iPersonService;
    /**
     * 工程服务
     */
    @Autowired
    IProjectService iProjectService;


    @Autowired
    IHazardousWorkResultService iHazardousWorkResultService;


    @Autowired
    ITaskTechDocumentService iTaskTechDocumentService;

    /**
     * 三交三查可视化
     *
     * @return
     */
    @RequestMapping(value = "/task", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "列表分页查询", notes = "列表分页查询")
    public Object taskPayCheck(Long taskId) {
        Task task = iTaskService.getById(taskId);
        if (task.getType().equals(TaskTypeEnum.JOBDISCLOSURE.getValue())) {
            return iTaskService.visualJobdisclosure(task);
        }
        if (task.getType().equals(TaskTypeEnum.TASKPAYCHECK.getValue())) {
            return iTaskService.visualTaskPayCheck(task);
        }
        if (task.getType().equals(TaskTypeEnum.BAD.getValue())) {
            return iTaskService.visualBad(task);
        }
        return null;
    }


    /**
     * 违规管理内容
     *
     * @return
     */
    @RequestMapping(value = "/badBody", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "违规管理内容", notes = "违规管理内容")
    public Object badBody(Long taskId) {
        BadManagement badManagement =
                iBadManagementService.getOne(new LambdaQueryWrapper<BadManagement>().eq(BadManagement::getTaskId, taskId));
        return badManagement.getBody();
    }


    /**
     * 作业票
     *
     * @return
     */
    @RequestMapping(value = "/workTicket", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "作业票", notes = "作业票")
    public Object workTicket(Long taskId) {
        WorkTicketVo workTicketVo = new WorkTicketVo();
        TaskPaycheck taskPaycheck =
                iTaskPaycheckService.getOne(new LambdaQueryWrapper<TaskPaycheck>().eq(TaskPaycheck::getTaskId, taskId));
        if (taskPaycheck != null) {
            Long workTicketId = taskPaycheck.getWorkTicketId();
            String workTicketName = taskPaycheck.getWorkTicketName();
            workTicketVo.setWorkTicketId(workTicketId);
            workTicketVo.setWorkTicketName(workTicketName);
            List<TaskPersonFile> taskPersonFileList =
                    iTaskPersonFileService.list(new LambdaQueryWrapper<TaskPersonFile>().eq(TaskPersonFile::getTaskId, taskId)
                            .eq(TaskPersonFile::getPersonType, TaskPersonFileEnum.JOBTICKET.getValue()));

            if (StringUtil.isNotEmpty(taskPersonFileList)) {
                List<String> collect = taskPersonFileList.stream().map(taskPersonFile -> taskPersonFile.getFilePath()).collect(Collectors.toList());
                workTicketVo.setWorkTicketFile(collect);
            }
        }
        return workTicketVo;
    }


    /**
     * 风险作业与检查项
     *
     * @return
     */
    @RequestMapping(value = "/riskJobItemInput", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "风险作业与检查项", notes = "风险作业与检查项")
    public Object riskJobItemInput(Long taskId,
                                   Long userId, @ApiParam(value = "分页条件 isAll=0 具体分页必传") CommonPageableDto pageable) {
        if (pageable.getIsAll() == 1) {
            pageable.setPageNumber(0);
            pageable.setPageSize(Integer.MAX_VALUE);
        }
        Page<HazardousWorkResult> page = new Page<>(pageable.getPageNumber(), pageable.getPageSize());
        TaskPaycheck taskPaycheck = iTaskPaycheckService.getOne(new LambdaQueryWrapper<TaskPaycheck>().eq(TaskPaycheck::getTaskId, taskId));
        String riskType = taskPaycheck.getRiskType();
        //判断任务和角色 如果是项目部安全员就返回项目部安全员检查项数据
        TaskPerson taskPerson = iTaskPersonService.getOne(new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getTaskId,
                taskId).eq(TaskPerson::getPersonId, userId).notIn(TaskPerson::getType,
                TaskPersonTypeEnum.CREATEPERSON.getValue()));
        RiskJobItemInputVo riskJobItemInputVo = new RiskJobItemInputVo();
        riskJobItemInputVo.setRiskType(riskType);
        if (taskPerson != null) {
            Long type = taskPerson.getType();
            LambdaQueryWrapper<HazardousWorkResult> hazardousWorkResultLambdaQueryWrapper = new LambdaQueryWrapper<>();
            hazardousWorkResultLambdaQueryWrapper.eq(HazardousWorkResult::getHazardousWorkId, taskPaycheck.getRiskTypeId());
            hazardousWorkResultLambdaQueryWrapper.eq(HazardousWorkResult::getTaskId, taskId);
            // 项目部安全员
            if (type.equals(TaskPersonTypeEnum.PLATFORMSAFETYOFFICER.getValue())) {
                hazardousWorkResultLambdaQueryWrapper.eq(HazardousWorkResult::getWeight, 1L);
            } else if (type.equals(TaskPersonTypeEnum.SAFETYOFFICER.getValue())) {
                hazardousWorkResultLambdaQueryWrapper.eq(HazardousWorkResult::getWeight, 0L);
            }
            IPage<HazardousWorkResult> hazardousWorkResultPage = iHazardousWorkResultService.page(page, hazardousWorkResultLambdaQueryWrapper);
            riskJobItemInputVo.setItemInput(hazardousWorkResultPage);
        }
        return riskJobItemInputVo;
    }


    /**
     * 交底文件
     *
     * @return
     */
    @RequestMapping(value = "/jobFile", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "交底文件", notes = "交底文件")
    public Object jobFile(Long taskId) {
        return iTaskTechDocumentService.list(new LambdaQueryWrapper<TaskTechDocument>().eq(TaskTechDocument::getTaskId, taskId));
    }


    /**
     * 公司结构
     *
     * @return
     */
    @RequestMapping(value = "/businessStructure", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "公司结构", notes = "公司结构")
    public Object businessStructure(Long taskId) {
        setPlatFormAccess();
        Task task = iTaskService.getById(taskId);
        Long createPersonId = task.getCreatePersonId();
        if (createPersonId == null) {
            throw new BaseException("发起人不存在!");
        }
        PersonAscription personAscription =
                iPersonAscriptionService.getOne(new LambdaQueryWrapper<PersonAscription>().eq(PersonAscription::getPersonId
                        , createPersonId));
        String companyName = "";
        String name = "";
        if (personAscription != null) {
            Long companyId = personAscription.getCompanyId();
            Company company = iCompanyService.getById(companyId);
            companyName = company.getName();
            Long departmentId = personAscription.getDepartmentId();
            FeignClientResult<Collection<DepartmentModel>> feignClientResult = Privilege.departmentClient.queryListByChild(departmentId);
            Collection<DepartmentModel> result = feignClientResult.getResult();
            if (StringUtil.isNotEmpty(result)) {
                Collections.reverse((List<?>) result);
                List<String> collect = result.stream().map(r -> r.getDepartmentName()).collect(Collectors.toList());
                name = Joiner.on("-").join(collect);
            }
        }
        Long type = task.getType();
        String taskTypeName = TaskTypeEnum.getLabelByValue(type);

        if (StringUtils.isNotEmpty(companyName) && StringUtils.isNotEmpty(name)) {
            return companyName + ">" + name + ">" + taskTypeName;
        }

        if (StringUtils.isEmpty(companyName) && StringUtils.isNotEmpty(name)) {
            return name + ">" + taskTypeName;
        }

        if (StringUtils.isEmpty(companyName) && StringUtils.isEmpty(name)) {
            return taskTypeName;
        }
        return companyName + ">" + name + ">" + taskTypeName;
    }





}
