package com.sw.mes.fb.turnstore.controller;

import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.response.ResponsePage;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.core.utils.DynamicSpecifications;
import com.sw.mes.core.utils.PageUtil;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.fb.checkout.entity.FbJoin;
import com.sw.mes.fb.checkout.service.FbJoinService;
import com.sw.mes.fb.turnstore.dto.TurnStoreSendDto;
import com.sw.mes.fb.turnstore.dto.vo.TurnStoreSenVo;
import com.sw.mes.fb.turnstore.entity.TurnStoreAccept;
import com.sw.mes.fb.turnstore.entity.TurnStoreSend;
import com.sw.mes.fb.turnstore.service.TurnStoreAcceptService;
import com.sw.mes.fb.turnstore.service.TurnStoreSendService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

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


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@RestController
@RequestMapping("/turnStoreSend")
@Slf4j
@Api(description = "方棒送验发送方记录表接口")
public class TurnStoreSendController {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private TurnStoreSendService turnStoreSendService;

    @Autowired
    private TurnStoreAcceptService turnStoreAcceptService;

    @Autowired
    private FbJoinService fbJoinService;

    @ApiOperation(value = "分页查询方棒送验发送方记录表列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_sendNo", value = "送验单号", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_state", value = "状态(1:待确认，2:已确认，3:拒收)", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "search_EQ_sendType", value = "送验类型", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "search_GTE_createTime", value = "操作时间(开始时间)", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LT_createTime", value = "操作时间(结束时间)", dataType = "string", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<TurnStoreSendDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<TurnStoreSend> specification = DynamicSpecifications.bySearchFilter(request, TurnStoreSend.class);
        Page<TurnStoreSend> page = turnStoreSendService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<TurnStoreSendDto> list = page.getContent().stream()
                .map(this::toLazyDto)
                .collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(list, page.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "获取所有方棒送验发送方记录表")
    @GetMapping("/listAll")
    public Result<List<TurnStoreSendDto>> listAll(ServletRequest request) {
        Specification<TurnStoreSend> specification = DynamicSpecifications.bySearchFilter(request, TurnStoreSend.class);
        List<TurnStoreSend> turnStoreSends = turnStoreSendService.findByExampleSort(specification, null);
        List<TurnStoreSendDto> turnStoreSendList = turnStoreSends.stream()
                .map(this::toLazyDto)
                .collect(Collectors.toList());
        return ResultGenerator.success(turnStoreSendList);
    }

    @ApiOperation(value = "方棒送验发送方记录表详细信息")
    @GetMapping("/{id}")
    public Result<TurnStoreSenVo> get(@PathVariable @ApiParam(value = "方棒送验发送方记录表id") Long id) {
        TurnStoreSenVo turnStoreSendDto = turnStoreSendService.getTurnStoreSendDtoById(id);
        if (null == turnStoreSendDto) {
            return ResultGenerator.fail("该方棒送验发送方记录表不存在");
        }
        return ResultGenerator.success(turnStoreSendDto);
    }

    @ApiOperation(value = "更新方棒送验发送方记录表")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "方棒送验发送方记录表,添加是id不用赋值，修改需要，" +
            "fid的值为方棒拼棒id集合，用逗号拼接") TurnStoreSendDto dto) {
        try {
            TurnStoreSend obj = fromDto(dto);
            if (obj.getFid() == null || obj.getFid().equals("")) {
                return ResultGenerator.fail("晶段信息不能为空");
            }

            if (obj.getId() <= 0) {
                obj.setSendNo("SY-" + System.currentTimeMillis());
                obj.setUserId(BaseContextHandler.getUserID());
                obj.setUserName(BaseContextHandler.getUsername());
                obj.setCreateTime(new Date());
            }
            String[] ids = obj.getFid().split(",");
            List<FbJoin> list = fbJoinService.getFbJoinDaoList(ids);
            for (FbJoin fbJoin : list) {
                if (fbJoin.getIsSend() > 0) {
                    return ResultGenerator.fail(fbJoin.getSectionNoFb() + "已存在未确认的单号");
                }
                fbJoinService.updateIsSend(fbJoin.getId(), 1);
            }
            if (obj.getId() == 0) {
                obj.setId(null);
                obj = turnStoreSendService.save(obj);
            } else {
                obj.setState(1);
                obj.setUpdateUserId(null);
                obj.setUpdateUserName(null);
                obj.setUpdateTime(null);
                turnStoreSendService.saveOrUpdate(obj);
            }
            TurnStoreAccept turnStoreAccept = new TurnStoreAccept();
            turnStoreAccept.setStickCount(obj.getStickCount());
            turnStoreAccept.setSource("粘方棒站");
            turnStoreAccept.setStoreCode(obj.getSendNo());
            turnStoreAccept.setAcceptType(obj.getSendType());
            turnStoreAccept.setRemark(obj.getRemark());
            turnStoreAccept.setFid(obj.getFid());
            turnStoreAccept.setSendId(obj.getId());
            turnStoreAccept.setUserId(BaseContextHandler.getUserID());
            turnStoreAccept.setUserName(BaseContextHandler.getUsername());
            turnStoreAccept.setCreateTime(new Date());
            turnStoreAcceptService.saveOrUpdate(turnStoreAccept);
            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) {
            TurnStoreSenVo turnStoreSendDto = turnStoreSendService.getTurnStoreSendDtoById(id);
            List<FbJoin> list = fbJoinService.getFbJoinDaoList(turnStoreSendDto.getFid().split(","));
            for (FbJoin fbJoin : list) {
                fbJoinService.updateIsSend(fbJoin.getId(), 0);
            }
            turnStoreAcceptService.deleteBySendId(turnStoreSendDto.getId());
            turnStoreSendService.delete(id);
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "取消")
    @PostMapping("/cancel")
    public Result affirm(@ApiParam(value = "记录id", type = "query") @RequestParam Long id) {
        TurnStoreSenVo turnStoreSendDto = turnStoreSendService.getTurnStoreSendDtoById(id);
        if (null == turnStoreSendDto) {
            return ResultGenerator.fail("该方棒送验记录不存在");
        }
        List<FbJoin> list = fbJoinService.getFbJoinDaoList(turnStoreSendDto.getFid().split(","));
        for (FbJoin fbJoin : list) {
            fbJoinService.updateIsSend(fbJoin.getId(), 0);
        }
        //更新发送记录
        TurnStoreSend turnStoreSend = turnStoreSendService.get(id);
        turnStoreSend.setState(4);
        turnStoreSend.setUpdateUserId(BaseContextHandler.getUserID());
        turnStoreSend.setUpdateUserName(BaseContextHandler.getUsername());
        turnStoreSend.setUpdateTime(new Date());
        turnStoreSendService.saveOrUpdate(turnStoreSend);
        //同步接收记录
        TurnStoreAccept turnStoreAccept = turnStoreAcceptService.findBySendId(id);
        turnStoreAccept.setUpdateUserId(BaseContextHandler.getUserID());
        turnStoreAccept.setUpdateUserName(BaseContextHandler.getUsername());
        turnStoreAccept.setUpdateTime(new Date());
        turnStoreAccept.setState(4);
        turnStoreAcceptService.saveOrUpdate(turnStoreAccept);
        return ResultGenerator.success();
    }

    public TurnStoreSendDto toLazyDto(TurnStoreSend entity) {
        return modelMapper.map(entity, TurnStoreSendDto.class);
    }

    public TurnStoreSendDto toEagerDto(TurnStoreSend entity) {
        return modelMapper.map(entity, TurnStoreSendDto.class);
    }

    public TurnStoreSend fromDto(TurnStoreSendDto dto) {
        return modelMapper.map(dto, TurnStoreSend.class);
    }


}
