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.EasyExcelUtils;
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.dao.TurnStoreAcceptDao;
import com.sw.mes.fb.turnstore.dto.TurnStoreAcceptDto;
import com.sw.mes.fb.turnstore.dto.vo.TurnStoreAcceptVo;
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.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


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

    @Autowired
    private TurnStoreAcceptService turnStoreAcceptService;

    @Autowired
    private TurnStoreSendService turnStoreSendService;

    @Autowired
    private TurnStoreAcceptDao turnStoreAcceptDao;

    @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_state", value = "状态(1:待确认，2:已确认，3:拒收)", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_storeCode", value = "出库单号", dataType = "string", 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<TurnStoreAcceptDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<TurnStoreAccept> specification = DynamicSpecifications.bySearchFilter(request, TurnStoreAccept.class);
        Page<TurnStoreAccept> page = turnStoreAcceptService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<TurnStoreAcceptDto> list = page.getContent().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(list, page.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "记录导出")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "search_EQ_state", value = "状态(1:待确认，2:已确认，3:拒收)", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_storeCode", value = "出库单号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_GTE_createTime", value = "操作时间(开始时间)", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LT_createTime", value = "操作时间(结束时间)", dataType = "string", paramType = "query"),
    })
    @GetMapping("/export")
    public void export(ServletRequest request, @ApiIgnore RequestPage requestPage, HttpServletResponse response) {
        try {
            Specification<TurnStoreAccept> specification = DynamicSpecifications.bySearchFilter(request, TurnStoreAccept.class);
            Page<TurnStoreAccept> page = turnStoreAcceptService.findByExample(specification, PageUtil.createPageable(requestPage));
            List<TurnStoreAcceptDto> list = page.getContent().stream()
                    .map(this::toLazyDto)
                    .collect(Collectors.toList());
            EasyExcelUtils.write(response, TurnStoreAcceptDto.class, "导出打包接收记录", "导出打包接收记录", list);
        } catch (IOException e) {
            throw new RuntimeException("打包接收记录导出失败，错误信息：" + e.getMessage());
        }
    }

    @ApiOperation(value = "获取所有方棒送验接收方记录表")
    @GetMapping("/listAll")
    public Result<List<TurnStoreAcceptDto>> listAll(ServletRequest request) {
        Specification<TurnStoreAccept> specification = DynamicSpecifications.bySearchFilter(request, TurnStoreAccept.class);
        List<TurnStoreAccept> turnStoreAccepts = turnStoreAcceptService.findByExampleSort(specification, null);
        List<TurnStoreAcceptDto> turnStoreAcceptList = turnStoreAccepts.stream()
                .map(turnStoreAccept -> toLazyDto(turnStoreAccept))
                .collect(Collectors.toList());
        return ResultGenerator.success(turnStoreAcceptList);
    }

    @ApiOperation(value = "方棒送验接收方记录表详细信息")
    @GetMapping("/{id}")
    public Result<TurnStoreAcceptVo> get(@PathVariable @ApiParam(value = "方棒送验接收方记录表id") Long id) {
        TurnStoreAcceptVo turnStoreAcceptDto = turnStoreAcceptService.getTurnStoreAcceptById(id);
        if (null == turnStoreAcceptDto)
            return ResultGenerator.fail("该方棒送验接收方记录表不存在");
        return ResultGenerator.success(turnStoreAcceptDto);
    }


    @ApiOperation(value = "更新方棒送验接收方记录表")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "方棒送验接收方记录表,添加是id不用赋值，修改需要，fid的值为" +
            "方棒拼棒id集合，用逗号拼接") TurnStoreAcceptDto dto) {
        try {
            TurnStoreAccept obj = fromDto(dto);
            if (obj.getId() > 0) {
                obj.setUpdateUserId(BaseContextHandler.getUserID());
                obj.setUpdateUserName(BaseContextHandler.getUsername());
                obj.setUpdateTime(new Date());
            } else {
                obj.setUserId(BaseContextHandler.getUserID());
                obj.setUserName(BaseContextHandler.getUsername());
                obj.setCreateTime(new Date());
            }
            turnStoreAcceptService.saveOrUpdate(obj);
            return ResultGenerator.success();
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "拒收")
    @PostMapping("/delete")
    public Result remove(@ApiParam(value = "记录id", type = "query") @RequestParam Long id, @RequestParam String remark) {
        TurnStoreAcceptVo turnStoreAcceptDto = turnStoreAcceptService.getTurnStoreAcceptById(id);
        turnStoreAcceptService.deleteById(id, turnStoreAcceptDto.getFid());
        TurnStoreSend turnStoreSend = turnStoreSendService.get(turnStoreAcceptDto.getSendId());
        if (null == turnStoreSend) {
            return ResultGenerator.fail("该方棒送验记录不存在");
        }
        turnStoreSend.setState(3);
        turnStoreSend.setRemark(remark);
        turnStoreSend.setUpdateUserId(BaseContextHandler.getUserID());
        turnStoreSend.setUpdateUserName(BaseContextHandler.getUsername());
        turnStoreSend.setUpdateTime(new Date());
        turnStoreSendService.saveOrUpdate(turnStoreSend);
        //同步接收记录
        TurnStoreAccept turnStoreAccept = turnStoreAcceptService.get(id);
        turnStoreAccept.setUpdateUserId(BaseContextHandler.getUserID());
        turnStoreAccept.setUpdateUserName(BaseContextHandler.getUsername());
        turnStoreAccept.setUpdateTime(new Date());
        turnStoreAccept.setState(3);
        turnStoreAccept.setRemark(remark);
        turnStoreAcceptService.saveOrUpdate(turnStoreAccept);
        List<FbJoin> list = fbJoinService.getFbJoinDaoList(turnStoreAcceptDto.getFid().split(","));
        for (FbJoin fbJoin : list) {
            fbJoinService.updateIsSend(fbJoin.getId(), 0);
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "确认接收")
    @PostMapping("/affirm")
    public Result affirm(@ApiParam(value = "记录id", type = "query") @RequestParam Long id, @RequestParam String remark) {
        turnStoreAcceptService.affirmById(id, 2, BaseContextHandler.getUserID(), BaseContextHandler.getUsername(), remark);
        TurnStoreAcceptVo obj = turnStoreAcceptService.getTurnStoreAcceptById(id);
        turnStoreSendService.affirmById(obj.getSendId(), 2, BaseContextHandler.getUserID(), BaseContextHandler.getUsername(), remark);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "取消")
    @PostMapping("/cancel")
    public Result affirm(@ApiParam(value = "记录id", type = "query") @RequestParam Long id) {
        TurnStoreAcceptVo obj = turnStoreAcceptService.getTurnStoreAcceptById(id);
        turnStoreAcceptDao.affirmById(id, 4, BaseContextHandler.getUserID(), BaseContextHandler.getUsername(), "", new Date());
        TurnStoreSend turnStoreSend = turnStoreSendService.get(obj.getSendId());
        turnStoreSend.setState(4);
        turnStoreSend.setUpdateUserId(BaseContextHandler.getUserID());
        turnStoreSend.setUpdateUserName(BaseContextHandler.getUsername());
        turnStoreSend.setUpdateTime(new Date());
        turnStoreSendService.saveOrUpdate(turnStoreSend);
        List<FbJoin> list = fbJoinService.getFbJoinDaoList(obj.getFid().split(","));
        for (FbJoin fbJoin : list) {
            fbJoinService.updateIsSend(fbJoin.getId(), 0);
        }
        return ResultGenerator.success();
    }

    public TurnStoreAcceptDto toLazyDto(TurnStoreAccept entity) {
        return modelMapper.map(entity, TurnStoreAcceptDto.class);
    }

    public TurnStoreAcceptDto toEagerDto(TurnStoreAccept entity) {
        return modelMapper.map(entity, TurnStoreAcceptDto.class);
    }

    public TurnStoreAccept fromDto(TurnStoreAcceptDto dto) {
        return modelMapper.map(dto, TurnStoreAccept.class);
    }


}
