package com.yeejoin.precontrol.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.AgencyUserModel;
import com.yeejoin.precontrol.common.annotations.OpsLog;
import com.yeejoin.precontrol.common.entity.Person;
import com.yeejoin.precontrol.common.entity.RiskWork;
import com.yeejoin.precontrol.common.enums.OpsLogEnum;
import com.yeejoin.precontrol.common.param.RiskWorkParam;
import com.yeejoin.precontrol.common.service.IRiskWorkService;
import com.yeejoin.precontrol.common.utils.StringUtil;
import com.yeejoin.precontrol.common.vo.RiskWorkPersonVo;
import com.yeejoin.precontrol.common.vo.RiskWorkVo;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * 风险作业管理表
 *
 * @author duanwei
 * @date 2021-01-28
 */
@Slf4j
@RestController
@Api(tags = "风险作业管理表Api")
@RequestMapping(value = "/risk-work", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class RiskWorkController extends BaseController {

    @Autowired
    IRiskWorkService iRiskWorkService;

    /**
     * 新增风险作业管理表
     *
     * @return
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "新增风险作业管理表", notes = "新增风险作业管理表")
    @OpsLog(value=OpsLogEnum.EDIT_RISKWORK)
    public RiskWorkParam saveRiskWork(@RequestBody @Valid RiskWorkParam riskWorkParam) {
        if(log.isInfoEnabled()){
            log.info("新增风险作业管理表:{}", JSONObject.toJSONString(riskWorkParam));
        }
        Person person = getPerson();
        riskWorkParam.getRiskWork().setOrgCode(person!=null?person.getOrgCode():null);
        return iRiskWorkService.saveWithChild(riskWorkParam, getUserId());
    }

    /**
     * 根据id删除
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "/{ids}", method = RequestMethod.DELETE)
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除,批量刪除", notes = "根据id删除,批量刪除")
    @OpsLog(value=OpsLogEnum.DELETE_RISKWORK)
    public boolean deleteById(@PathVariable String ids) {
        if(log.isInfoEnabled()){
            log.info("根据id删除,批量刪除:{}", JSONObject.toJSONString(ids));
        }
        List<Long> idList = Arrays.stream(ids.split(",")).map(Long::parseLong).collect(Collectors.toList());
        return iRiskWorkService.removeWithChild(idList);
    }


    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
    public RiskWorkParam selectById(@PathVariable Long id) {
        return iRiskWorkService.getWithChildById(id);
    }


    /**
     * 列表分页查询
     *
     * @return  QUALIFICATION_REQUIREMENT
     */
    @RequestMapping(value = "/page/list", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "列表分页查询", notes = "列表分页查询")
    public IPage<RiskWork> listPage(@RequestParam Integer pageNumber,
                                    @RequestParam Integer pageSize,
                                    @RequestParam(required = false) @ApiParam("风险作业名称")  String name,
                                    @RequestParam(required = false) @ApiParam("风险等级id")  Integer level) {
        buildRequestContext();
        Person person = getPerson();
        Page<RiskWork> pageBean = new Page<>(pageNumber, pageSize);
        QueryWrapper<RiskWork> riskWorkQueryWrapper = new QueryWrapper<>();
        if (StringUtil.isNotEmpty(name)) {
            riskWorkQueryWrapper.lambda().like(RiskWork::getName, name);
        }
        if (StringUtil.isNotEmpty(level)) {
            riskWorkQueryWrapper.lambda().eq(RiskWork::getLevel, level);
        }
        String orgCode=person!=null?person.getOrgCode():null;
        if(orgCode!=null) 
        {
        	  riskWorkQueryWrapper.lambda().like(RiskWork::getOrgCode, orgCode);
        }
        riskWorkQueryWrapper.orderByDesc("create_date");
        IPage<RiskWork> page = iRiskWorkService.page(pageBean, riskWorkQueryWrapper);
        Set<String> userIds = page.getRecords().stream().map(RiskWork::getCreateId).collect(Collectors.toSet());
        userIds.remove(null);
        userIds.remove("");
        FeignClientResult<List<AgencyUserModel>> result = CollectionUtils.isEmpty(userIds) ? null : Privilege.agencyUserClient.queryByIds(Joiner.on(",").join(userIds),true);
        if (result != null) {
            List<AgencyUserModel> userModels = result.getResult();
            Map<String, String> userMap = userModels.stream().collect(Collectors.toMap(AgencyUserModel::getUserId, AgencyUserModel::getRealName));
            page.getRecords().forEach(r -> {
                r.setCreateName(userMap.get(r.getCreateId()));
            });
        }
        return page;
    }

    @ApiOperation(httpMethod = "GET", value = "风险作业列表查询,不分页", notes = "风险作业列表查询,不分页")
    @RequestMapping(value = "/list-all", method = RequestMethod.GET)
    public List<RiskWork> listAll(@RequestParam(required = false) String name){
    	 Person person = getPerson();
    	 String orgCode=person!=null?person.getOrgCode():null;
        return iRiskWorkService.listAllWithDangerWork(name,orgCode);
    }

    @ApiOperation(httpMethod = "GET", value = "查询符合条件的人")
    @GetMapping(value = "/person/list")
    public List<RiskWorkPersonVo> matchConditionPerson(
            @ApiParam(required = true,value = "风险作业id") @RequestParam Long riskWorkId,
            @ApiParam(required = true,value = "人员类型") @RequestParam String personType,
            @ApiParam(required = true,value = "公司id") @RequestParam Long companyId,
            @ApiParam(value = "人姓名") @RequestParam(required = false) String name,
            @ApiParam(required = true,value = "项目id") @RequestParam Long projectId){
        buildRequestContext();
        return iRiskWorkService.listPersonOfMatchCondition(riskWorkId,personType,companyId,projectId,name);
    }

    @ApiOperation(httpMethod = "GET", value = "查询关联风险计划的风险作业信息")
    @GetMapping(value = "/detail/{taskRiskControlId}")
    public RiskWorkVo getRiskWorkInfo(@PathVariable Long taskRiskControlId) {
        return iRiskWorkService.getDetailByPlanId(taskRiskControlId);
    }
}


