package com.yeejoin.amos.boot.module.hygf.biz.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.module.hygf.api.config.UserLimits;
import com.yeejoin.amos.boot.module.hygf.api.dto.*;
import com.yeejoin.amos.boot.module.hygf.api.entity.*;
import com.yeejoin.amos.boot.module.hygf.api.mapper.*;
import com.yeejoin.amos.boot.module.hygf.biz.service.impl.WorkOrderServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 施工派工工单
 *
 * @author system_generator
 * @date 2024-01-02
 */
@RestController
@Api(tags = "派工工单Api")
@RequestMapping(value = "/work-order")
public class WorkOrderController extends BaseController {

    @Autowired
    WorkOrderServiceImpl workOrderServiceImpl;
    @Autowired
    WorkOrderPowerStationMapper workOrderPowerStationMapper;
    @Autowired
    WorkOrderMapper workOrderMapper;
    @Autowired
    HouseholdContractMapper householdContractMapper;
    @Autowired
    PowerStationEngineeringInfoMapper powerStationEngineeringInfoMapper;

    @Autowired
    PersonnelBusinessMapper personnelBusinessMapper;
    @Autowired
    PowerStationConstructionDataMapper powerStationConstructionDataMapper;
    @Value("${admin.engineering.roleId}")
    Long engineeringId;
    @Value("${admin.area.roleId}")
    Long areaId;
    @Value("${admin.design.roleId}")
    Long designId;
    @Value("${admin.delerAdmin.roleId}")
    Long delerAdminId;
    /**
     * 新增施工派工工单
     *
     * @return
     * @throws Exception 
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/save")
	@ApiOperation(httpMethod = "POST", value = "新增施工派工工单", notes = "新增施工派工工单")
	public ResponseModel<WorkOrder> save(@RequestBody WorkOrder model) throws Exception {
        UserUnitInformationDto userUnitInformationDto=personnelBusinessMapper.getUserUnitInformationDto( getUserInfo().getUserId());
	    model = workOrderServiceImpl.saveWorkOrder(model,userUnitInformationDto);
	    return ResponseHelper.buildResponse(model);
	}

	/**
     * 根据sequenceNbr更新
     *
     * @param sequenceNbr 主键
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PutMapping(value = "/{sequenceNbr}")
	@ApiOperation(httpMethod = "PUT", value = "根据sequenceNbr更新施工派工工单", notes = "根据sequenceNbr更新施工派工工单")
	public ResponseModel<WorkOrder> updateBySequenceNbrWorkOrder(@RequestBody WorkOrder model,@ApiParam(name = "sequenceNbr",value = "主键", example = "158888889425888")@PathVariable(value = "sequenceNbr") Long sequenceNbr) {
	    model.setSequenceNbr(sequenceNbr);
        UserUnitInformationDto userUnitInformationDto=personnelBusinessMapper.getUserUnitInformationDto( getUserInfo().getUserId());
	    return ResponseHelper.buildResponse(workOrderServiceImpl.updateWorkOrder(model,userUnitInformationDto));
	}

	/**
     * 根据sequenceNbr删除
     *
     * @param sequenceNbr 主键
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @DeleteMapping(value = "/{sequenceNbr}")
    @ApiOperation(httpMethod = "DELETE", value = "根据sequenceNbr删除施工派工工单", notes = "根据sequenceNbr删除施工派工工单")
    public ResponseModel<Boolean> deleteBySequenceNbr(HttpServletRequest request, @ApiParam(name = "sequenceNbr",value = "主键", example = "158888889425888")@PathVariable(value = "sequenceNbr") Long sequenceNbr){
        return ResponseHelper.buildResponse(workOrderServiceImpl.removeById(sequenceNbr));
    }

    /**
     * 根据sequenceNbr查询
     *
	 * @param sequenceNbr  主键
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/{sequenceNbr}")
	@ApiOperation(httpMethod = "GET",value = "根据sequenceNbr查询单个施工派工工单",  notes = "根据sequenceNbr查询单个施工派工工单")
	public ResponseModel<WorkOrder> selectOne(@ApiParam(name = "sequenceNbr",value = "主键", example = "158888889425888")@PathVariable Long sequenceNbr) {
        WorkOrder workOrder = workOrderServiceImpl.selectOne(sequenceNbr);
        return ResponseHelper.buildResponse(workOrder);
	}

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/selectOneall")
    @ApiOperation(httpMethod = "GET",value = "根据sequenceNbr查询单个施工派工工单",  notes = "根据sequenceNbr查询单个施工派工工单")
    public ResponseModel<Map<String,Object>> selectOneall(@ApiParam(name = "sequenceNbr",value = "主键", example = "158888889425888")@RequestParam(value = "sequenceNbr") Long sequenceNbr) {
        return ResponseHelper.buildResponse(workOrderServiceImpl.selectOneall(sequenceNbr));
    }



	/**
     * 列表分页查询
     *
     * @param current 当前页
     * @param current 每页大小
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping   (value = "/page")
	@ApiOperation(httpMethod = "GET",value = "施工派工工单分页查询",  notes = "施工派工工单分页查询")
    @UserLimits
	public ResponseModel<Page<WorkOrder>> queryForPage(@RequestBody WorkOrder  workOrder
    ) {

//        UserUnitInformationDto userUnitInformationDto=personnelBusinessMapper.getUserUnitInformationDto( getUserInfo().getUserId());
//
//        workOrder.setRegionCompanyId(userUnitInformationDto.getRegionalCompaniesSeq());
//        workOrder.setAmosDealerId(userUnitInformationDto.getAmosDealerId());

        return ResponseHelper.buildResponse(workOrderServiceImpl.selectPage(workOrder.getCurrent(),workOrder.getSize(), workOrder));
	}

	/**
	 * 列表全部数据查询
     *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET",value = "施工派工工单列表全部数据查询",   notes = "施工派工工单列表全部数据查询")
	@GetMapping(value = "/list")
	public ResponseModel<List<WorkOrderDto>> selectForList() {
	    return ResponseHelper.buildResponse(workOrderServiceImpl.queryForWorkOrderList());
	}



    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET",value = "列表全部数据查询",   notes = "列表全部数据查询")
    @GetMapping(value = "/getWorkOrderHousehold")
    public ResponseModel<  Page<PeasantHousehold>  > getPeasantHouseholdData(
            @ApiParam(name = "sequenceNbr",value = "主键", example = "158888889425888")  @RequestParam(required=false) Long sequenceNbr,
            @ApiParam(name="current",value = "页码",example = "1")  @RequestParam(required=false) Integer current,
            @ApiParam(name="size",value = "大小",example = "20")  @RequestParam(required=false) Integer size,
            @ApiParam(name="ownersName",value = "电站名称",example = "admin")  @RequestParam(required=false) String ownersName
    ) {
        Page<PeasantHousehold> page = new Page<>();
        PageHelper.startPage(current,size);
        List<PeasantHousehold> list=workOrderPowerStationMapper.selectPeasantHousehold(sequenceNbr,ownersName);

        if(list != null && list.size() > 0) {
            list.forEach(e -> {
                if(e.getPeasantHouseholdNo() != null) {
                    e.setScale(householdContractMapper.getHygfCommercialScale(e.getPeasantHouseholdNo()));
                    e.setRealScale(powerStationEngineeringInfoMapper.getRealScaleByPeasantHouseholdNo(e.getPeasantHouseholdNo()));
                }
            });
        }

        PageInfo<PeasantHousehold> pageInfo = new PageInfo<>(list);
        page.setSize(pageInfo.getSize());
        page.setCurrent(pageInfo.getPageNum());
        page.setTotal(pageInfo.getTotal());
        page.setRecords(list);
        return ResponseHelper.buildResponse(page);
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping (value = "/wgpage")
    @ApiOperation(httpMethod = "GET",value = "施工派工工单分页查询",  notes = "施工派工工单分页查询")
    @UserLimits
    public ResponseModel<Page<WorkOrderPage>> queryForwgpage(@RequestBody WorkOrderPage  workOrder
    ) {

        //当前登录人所属场站
//        UserUnitInformationDto userUnitInformationDto=personnelBusinessMapper.getUserUnitInformationDto( getUserInfo().getUserId());
//
//        workOrder.setRegionCompanyId(userUnitInformationDto.getRegionalCompaniesSeq());
//        workOrder.setAmosDealerId(userUnitInformationDto.getAmosDealerId());
        ReginParams reginParams = getSelectedOrgInfo();
        List<String> workOrderPowerStationNodes = new ArrayList<>();

        List<Long> roleIds = new ArrayList<>();
        for (Long aLong : reginParams.getUserModel().getOrgRoleSeqs().keySet()) {
            List<Long> longs = reginParams.getUserModel().getOrgRoleSeqs().get(aLong);

            if (longs.contains(areaId)) {
                workOrderPowerStationNodes.add("area");
            }
            if (longs.contains(engineeringId)) {
                workOrderPowerStationNodes.add("engineering");
            }
            if (longs.contains(designId)) {
                workOrderPowerStationNodes.add("design");
            }
            if (longs.contains(delerAdminId)) {
                workOrderPowerStationNodes.add("design");
                workOrderPowerStationNodes.add("engineering");
                workOrderPowerStationNodes.add("area");
            }
            roleIds.addAll(longs);
        }
        if (workOrder.getType().equals("3") && workOrderPowerStationNodes != null){
            workOrder.setWorkOrderPowerStationNodes(workOrderPowerStationNodes);
        }
        Page<WorkOrderPage> workOrderPagePage = workOrderServiceImpl.queryForwgpage(workOrder.getCurrent(), workOrder.getSize(), workOrder);
        if (workOrder.getType().equals("3") && workOrderPowerStationNodes != null){
            workOrderPagePage.getRecords().forEach(e->{
                if (workOrderPowerStationNodes.contains(e.getWorkOrderPowerStationNode()) && (roleIds.contains(areaId) ||roleIds.contains(designId) ||  roleIds.contains(engineeringId)) ){
                    e.setIsAudit("0");
                }
                else {
                    e.setIsAudit("1");
                }
                if(e.getPeasantHouseholdNo() != null) {
                    e.setScale(householdContractMapper.getHygfCommercialScale(e.getPeasantHouseholdNo()));
                    e.setRealScale(powerStationEngineeringInfoMapper.getRealScaleByPeasantHouseholdNo(e.getPeasantHouseholdNo()));
                }

            });
        }

        return ResponseHelper.buildResponse(workOrderPagePage);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping (value = "/wgpageList")
    @ApiOperation(httpMethod = "GET",value = "无分页查询",  notes = "无分页查询")
    public ResponseModel<List<WorkOrderPage>> wgpageList(
            @RequestBody WorkOrderPage  workOrder
    ) {

        //当前登录人所属场站
        UserUnitInformationDto userUnitInformationDto=personnelBusinessMapper.getUserUnitInformationDto( getUserInfo().getUserId());
        workOrder.setRegionCompanyId(userUnitInformationDto.getRegionalCompaniesSeq());
        workOrder.setAmosDealerId(userUnitInformationDto.getAmosDealerId());
        List<WorkOrderPage>  list=workOrderMapper.queryForwgpage(workOrder);

        if(list != null && list.size() > 0) {
            list.forEach(e -> {
                if(e.getPeasantHouseholdNo() != null) {
                    e.setScale(householdContractMapper.getHygfCommercialScale(e.getPeasantHouseholdNo()));
                    e.setRealScale(powerStationEngineeringInfoMapper.getRealScaleByPeasantHouseholdNo(e.getPeasantHouseholdNo()));
                }
            });

        }

        return ResponseHelper.buildResponse(list);
    }


    //获取施工资料详情
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping (value = "/getPowerStationConstructionData")
    @ApiOperation(httpMethod = "GET",value = "无分页查询",  notes = "无分页查询")
    public ResponseModel<PowerStationConstructionData> getPowerStationConstructionData(
            @RequestBody PowerStationConstructionData  powerStationConstructionData
    ) {
	    //查询施工信息
        LambdaQueryWrapper<PowerStationConstructionData> up=new LambdaQueryWrapper<>();
        up.eq(PowerStationConstructionData::getWorkOrderId,powerStationConstructionData.getWorkOrderId());
        up.eq(PowerStationConstructionData::getWorkOrderPowerStationId,powerStationConstructionData.getWorkOrderPowerStationId());
        PowerStationConstructionData da=  powerStationConstructionDataMapper.selectOne(up);
        return ResponseHelper.buildResponse(da!=null?da:new PowerStationConstructionData());
    }


    //施工信息添加

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping (value = "/addOrUpdate")
    @ApiOperation(httpMethod = "POST",value = "施工信息添加或者修改",  notes = "施工信息添加或者修改")
    public ResponseModel<PowerStationConstructionData> addOrUpdate(
            @RequestBody PowerStationConstructionData  powerStationConstructionData
    ) {
        return ResponseHelper.buildResponse( workOrderServiceImpl.addOrUpdate(powerStationConstructionData));
    }



    /**
     * 勘察信息编辑
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET",value = "电站详情",   notes = "勘察信息编辑")
    @GetMapping(value = "/getsurveyQueryxq")
    public ResponseModel<SurveyInfoAllDto> getsurveyQueryxq(@ApiParam(name = "sequenceNbr",value = "主键", example = "158888889425888") @RequestParam(value = "peasantHouseholdId" ) Long peasantHouseholdId,
                                                            @ApiParam(name = "workOrderId",value = "派工单ID",example = "1716344754242850818") @RequestParam(value = "workOrderId") Long workOrderId,
                                                            @ApiParam(name = "workOrderPowerStationId",value = "施工派工单Id",example = "1712383951215005697")  @RequestParam(value = "workOrderPowerStationId")Long workOrderPowerStationId) {

        SurveyInfoAllDto returnDto = workOrderServiceImpl.getsurveyQueryxq(peasantHouseholdId,workOrderId,workOrderPowerStationId);
        return ResponseHelper.buildResponse(returnDto);
    }




    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET",value = "完工登记详情",   notes = "完工登记详情")
    @GetMapping(value = "/getPowerStationEngineeringInfo")
    public ResponseModel<PowerStationEngineeringInfoAllDto> getPowerStationEngineeringInfo( @ApiParam(name = "workOrderPowerStationId",value = "施工派工单Id",example = "1712383951215005697") @RequestParam(value = "workOrderPowerStationId")Long workOrderPowerStationId) {

        PowerStationEngineeringInfoAllDto returnDto = workOrderServiceImpl.getPowerStationEngineeringInfo(workOrderPowerStationId);
        return ResponseHelper.buildResponse(returnDto);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET",value = "完工登记详情",   notes = "完工登记详情")
    @GetMapping(value = "/getPowerStationEngineeringInfoHistory")
    public ResponseModel<PowerStationEngineeringInfoAllDto> getPowerStationEngineeringInfoHistory( @ApiParam(name = "peasantHouseholdId",value = "农户ID",example = "1712383951215005697") @RequestParam(value = "peasantHouseholdId")Long peasantHouseholdId ,
                                                                                                   @ApiParam(value = "流程实例Id",example = "f2d8aa89-7594-11ef-b7e1-02420a1c0012")   @RequestParam(value = "processInstanceId",required = false)String  processInstanceId) {

        PowerStationEngineeringInfoAllDto returnDto = workOrderServiceImpl.getPowerStationEngineeringInfoHistory(peasantHouseholdId,processInstanceId);
        return ResponseHelper.buildResponse(returnDto);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET",value = "完工登记",   notes = "完工登记")
    @PostMapping (value = "/addPowerStationEngineeringInfo")
    public ResponseModel<PowerStationEngineeringInfoAllDto> addPowerStationEngineeringInfo(
            @RequestBody  PowerStationEngineeringInfoAllDto powerStationEngineeringInfoAllDto
    ) {

        workOrderServiceImpl.addPowerStationEngineeringInfo(powerStationEngineeringInfoAllDto);
        return ResponseHelper.buildResponse(powerStationEngineeringInfoAllDto);
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET",value = "完工登记审核详情",   notes = "完工登记审核详情")
    @GetMapping(value = "/getConstructionRecords")
    public ResponseModel<PowerStationEngineeringInfoAllDto> getConstructionRecords(@ApiParam(name = "workOrderPowerStationId",value = "施工派工单ID",example = "1712383951215005697")@RequestParam(value = "workOrderPowerStationId")Long workOrderPowerStationId) {

        PowerStationEngineeringInfoAllDto returnDto = workOrderServiceImpl.getConstructionRecords(workOrderPowerStationId,getUserInfo().getRealName());
        return ResponseHelper.buildResponse(returnDto);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST",value = "更新详情信息",   notes = "更新详情信息")
    @PostMapping(value = "/updateDetail")
    public ResponseModel updateDetail(@RequestBody PowerStationEngineeringInfoAllDto powerStationEngineeringInfoAllDto) {
        String realName = getSelectedOrgInfo().getUserModel().getRealName();

        workOrderServiceImpl.updateDetail(powerStationEngineeringInfoAllDto,realName);
        return ResponseHelper.buildResponse(null);
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET",value = "完工登记审核",   notes = "完工登记审核")
    @PostMapping(value = "/addConstructionRecords")
    public ResponseModel<ConstructionRecords> addConstructionRecords( @RequestBody  PowerStationEngineeringInfoAllDto constructionRecords) {
        ConstructionRecords da= constructionRecords.getConstructionRecords();
        da.setWorkOrderPowerStationId(constructionRecords.getWorkOrderPowerStationId());
        ConstructionRecords returnDto = workOrderServiceImpl.addConstructionRecords(da);
        return ResponseHelper.buildResponse(returnDto);
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST",value = "完工自审管理审核",   notes = "完工自审管理审核")
    @PostMapping(value = "/completeAudit")
    public ResponseModel completeAudit( @RequestBody  Map<String,String> kv) {
        workOrderServiceImpl.completeAudit(kv);
        return ResponseHelper.buildResponse(null);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET",value = "完工整改单下发",   notes = "完工整改单下发")
    @PostMapping(value = "/addRectification")
    public ResponseModel addRectification( @RequestBody HygfRectificationOrder hygfReplenishment) {


        return ResponseHelper.buildResponse( workOrderServiceImpl.addRectification(hygfReplenishment));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST",value = "完工整改单添加信息",   notes = "完工整改单添加信息")
    @PostMapping(value = "/nextTaskExcute")
    public ResponseModel nextTaskExcute( @RequestBody HygfRectificationOrder hygfReplenishment) {

        workOrderServiceImpl.nextTaskExcute(hygfReplenishment);
        return ResponseHelper.buildResponse(null);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST",value = "完工整改单审核",   notes = "完工整改单审核")
    @PostMapping(value = "/nextTaskAduit")
    public ResponseModel nextTaskAduit( @RequestBody HygfRectificationOrder hygfReplenishment) {

        workOrderServiceImpl.nextTaskAduit(hygfReplenishment);
        return ResponseHelper.buildResponse(null);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "PUT",value = "完工整改单作废",   notes = "完工整改单作废")
    @PutMapping(value = "/rollback")
    public ResponseModel rollback( @ApiParam(name = "sequenceNbr",value = "主键", example = "158888889425888")@RequestParam(value = "sequenceNbr") Long sequenceNbr) {

        workOrderServiceImpl.rollback(sequenceNbr);
        return ResponseHelper.buildResponse(null);
    }

}
