package com.sw.common.accessory.server.controller;

import com.sw.common.accessory.api.feignCilent.YbFeignClients;
import com.sw.common.accessory.server.dto.DeterminationEchnologyDto;
import com.sw.common.accessory.server.dto.DictionaryItemDto;
import com.sw.common.accessory.server.entity.DeterminationEchnology;
import com.sw.common.accessory.server.service.DeterminationEchnologyService;
import com.sw.common.core.context.BaseContextHandler;
import com.sw.common.core.request.RequestPage;
import com.sw.common.core.response.ResponsePage;
import com.sw.common.core.response.Result;
import com.sw.common.core.response.ResultGenerator;
import com.sw.common.core.utils.StringUtils;
import com.sw.common.mybatisplus.entity.Page;
import com.sw.common.mybatisplus.utils.DynamicSpecifications;
import com.sw.common.mybatisplus.utils.PageUtil;
import com.sw.common.mybatisplus.utils.Specification;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletRequest;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/anomalyDeterminationEchnology")
@Slf4j
@Api(tags = "热场退料异常判断技术评审接口")
public class DeterminationEchnologyController {
    @Autowired
    private DeterminationEchnologyService determinationEchnologyService;
    @Autowired
    private YbFeignClients ybFeignClients;
    @ApiOperation(value = "分页查询热场退料异常判断技术评审列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "状态", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "search_GTE_createTime", value = "开始时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "search_LTE_createTime", value = "结束时间", dataType = "String", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<DeterminationEchnologyDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<DeterminationEchnology> specification = DynamicSpecifications.bySearchFilter(request, DeterminationEchnology.class);
        Page<DeterminationEchnology> page = determinationEchnologyService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<DeterminationEchnologyDto> dtos = page.getContent().stream()
                .map(this::toLazyDto)
                .collect(Collectors.toList());
        ResponsePage<DeterminationEchnologyDto> responsePage = new ResponsePage<>(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

    private Set<Integer> userIdSet(String value) {
        if (StringUtils.isEmpty(value)) {
            return Collections.emptySet();
        }
        return Arrays.stream(value.split(",")).map(Integer::parseInt).collect(Collectors.toSet());
    }
    @ApiOperation(value = "获取热场退料异常判断评审权限")
    @GetMapping("/accessoryAbnormalAuthority")
    public Result<Map<String,Boolean>> accessoryAbnormalAuthority() {
        Map<String,Boolean> map = new HashMap<>();
        Integer userID = BaseContextHandler.getUserID();
        Result<DictionaryItemDto> themeValue1 = ybFeignClients.findByThemeValueAndNameAndValueAndEnable("global_switch",
                "COMMON_SWITCH", "accessoryEchnologyAuthority", true);
        Result<DictionaryItemDto> themeValue2 = ybFeignClients.findByThemeValueAndNameAndValueAndEnable("global_switch",
                "COMMON_SWITCH", "accessoryQualityAuthority", true);
        if(themeValue1.getCode().equals(200) && null != themeValue1.getData()){
            DictionaryItemDto themeValueData = themeValue1.getData();
            if(themeValueData.getEnable() == true && userIdSet(themeValueData.getExtendValue1()).contains(userID)){
                map.put("echnologyAuthority",true);
            }else {
                map.put("echnologyAuthority",false);
            }
        }
        if(themeValue2.getCode().equals(200) && null != themeValue2.getData()){
            DictionaryItemDto themeValueData = themeValue2.getData();
            if(themeValueData.getEnable() == true && userIdSet(themeValueData.getExtendValue1()).contains(userID)){
                map.put("qualityAuthority",true);
            }else {
                map.put("qualityAuthority",false);
            }
        }
        return ResultGenerator.success(map);
    }

    @ApiOperation(value = "获取所有热场退料异常判断技术评审")
    @GetMapping("/listAll")
    public Result<List<DeterminationEchnologyDto>> listAll(ServletRequest request) {
        Specification<DeterminationEchnology> specification = DynamicSpecifications.bySearchFilter(request, DeterminationEchnology.class);
        List<DeterminationEchnology> determinationEchnologies = determinationEchnologyService.findByExampleSort(specification, null);
        List<DeterminationEchnologyDto> applyRecordDtos = determinationEchnologies.stream()
                .map(this::toLazyDto)
                .collect(Collectors.toList());
        return ResultGenerator.success(applyRecordDtos);
    }

    @ApiOperation(value = "辅料热场退料异常判断技术评审")
    @GetMapping("/{id}")
    public Result<DeterminationEchnologyDto> get(@PathVariable @ApiParam(value = "辅料申请记录id") Long id) {
        DeterminationEchnology determinationEchnology = determinationEchnologyService.get(id);
        if (null == determinationEchnology) {
            return ResultGenerator.fail("该辅料申请记录不存在");
        }
        return ResultGenerator.success(toEagerDto(determinationEchnology));
    }

    @ApiOperation(value = "通过id查询辅料热场退料异常判断技术评审详情")
    @GetMapping("/findById")
    public Result<DeterminationEchnologyDto> findById(@RequestParam @ApiParam(value = "辅料申请记录id") Long id) {
        DeterminationEchnologyDto determinationEchnologyDto = determinationEchnologyService.findById(id);
        if (null == determinationEchnologyDto) {
            return ResultGenerator.fail("该辅料申请记录不存在");
        }
        return ResultGenerator.success(determinationEchnologyDto);
    }

    @ApiOperation(value = "创建热场退料异常判断技术评审")
    @PostMapping("/create")
    public Result<String> create(@RequestBody @Valid @ApiParam(value = "辅料申请记录对象") DeterminationEchnologyDto determinationEchnologyDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        DeterminationEchnology applyRecord = fromDto(determinationEchnologyDto);
        determinationEchnologyService.saveOrUpdate(applyRecord);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新热场退料异常判断技术评审")
    @PostMapping("/update")
    public Result<String> update(@RequestBody @Valid @ApiParam(value = "辅料申请记录") DeterminationEchnologyDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (dto.getId() == null) {
            return ResultGenerator.fail("id不能为空");
        }
        DeterminationEchnology entity = determinationEchnologyService.get(dto.getId());
        if (entity == null) {
            return ResultGenerator.fail("原信息不存在");
        }
        try {
            DeterminationEchnology entityfromFto = fromDto(dto);
            determinationEchnologyService.saveOrUpdate(entityfromFto);
            return ResultGenerator.success();
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }
    @ApiOperation(value = "审批通过热场退料异常判断技术评审")
    @PostMapping("/confirmAudit")
    public Result<String> confirmAudit(@RequestBody @Valid @ApiParam(value = "辅料申请记录") DeterminationEchnologyDto dto) {
        if (dto.getId() == null) {
            return ResultGenerator.fail("id不能为空");
        }
        DeterminationEchnology entity = determinationEchnologyService.get(dto.getId());
        if (entity == null) {
            return ResultGenerator.fail("原信息不存在");
        }
        try {
            determinationEchnologyService.confirmAudit(dto,entity);
            return ResultGenerator.success();
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "审批不通过热场退料异常判断技术评审")
    @PostMapping("/unConfirmAudit")
    public Result<String> unConfirmAudit(@RequestBody @Valid @ApiParam(value = "辅料申请记录") DeterminationEchnologyDto dto) {
        if (dto.getId() == null) {
            return ResultGenerator.fail("id不能为空");
        }
        DeterminationEchnology entity = determinationEchnologyService.get(dto.getId());
        if (entity == null) {
            return ResultGenerator.fail("原信息不存在");
        }
        try {
            determinationEchnologyService.unConfirmAudit(dto,entity);
            return ResultGenerator.success();
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }


    @ApiOperation(value = "删除热场退料异常判断技术评审")
    @PostMapping("/delete")
    public Result remove(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Long[] ids) {
        for (Long id : ids) {
            determinationEchnologyService.delete(id);
        }
        return ResultGenerator.success();
    }

    public DeterminationEchnologyDto toLazyDto(DeterminationEchnology entity) {
        DeterminationEchnologyDto determinationEchnologyDto = new DeterminationEchnologyDto();
        BeanUtils.copyProperties(entity, determinationEchnologyDto);
        return determinationEchnologyDto;
    }

    public DeterminationEchnologyDto toEagerDto(DeterminationEchnology entity) {
        DeterminationEchnologyDto determinationEchnologyDto = new DeterminationEchnologyDto();
        BeanUtils.copyProperties(entity, determinationEchnologyDto);
        return determinationEchnologyDto;
    }

    public DeterminationEchnology fromDto(DeterminationEchnologyDto dto) {
        DeterminationEchnology determinationEchnology = new DeterminationEchnology();
        BeanUtils.copyProperties(dto, determinationEchnology);
        return determinationEchnology;
    }
}
