/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.youchain.businessdata.rest;

import com.youchain.DuplicateSubmission.DuplicateSubmission;
import com.youchain.annotation.AnonymousAccess;
import com.youchain.annotation.Log;
import com.youchain.basicdata.domain.BillType;
import com.youchain.basicdata.service.dto.BillTypeQueryCriteria;
import com.youchain.businessdata.domain.Asn;
import com.youchain.businessdata.repository.AsnRepository;
import com.youchain.businessdata.service.AsnService;
import com.youchain.businessdata.service.dto.AsnQueryCriteria;
import com.youchain.exception.BadRequestException;
import com.youchain.exception.handler.ApiResult;
import com.youchain.utils.BizStatus;
import com.youchain.utils.CodeUtils;
import com.youchain.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import javax.servlet.http.HttpServletResponse;

/**
 * @author JiangKun
 * @website https://eladmin.vip
 * @date 2024-01-09
 **/
@Slf4j
@RestController
@RequiredArgsConstructor
@Api(tags = "asn管理")
@RequestMapping("/api/asn")
public class AsnController {

    private final AsnService asnService;
    private final AsnRepository asnRepository;
    private final CodeUtils codeUtils;


    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @AnonymousAccess
    public void exportAsn(HttpServletResponse response, AsnQueryCriteria criteria) throws Exception {
        asnService.download(asnService.queryAll(criteria), response);
    }

    @GetMapping(value = "/maxNo")
    @Log("查询最大的单号")
    @ApiOperation("查询最大单号")
    @AnonymousAccess
    public ResponseEntity<Object> maxNo(@RequestParam("code") String code) {
        return new ResponseEntity<>(codeUtils.getCode_yyMMdd(code, 3), HttpStatus.OK);
    }


    @GetMapping
    @Log("查询asn")
    @ApiOperation("查询asn")
    @AnonymousAccess
    public ResponseEntity<Object> queryAsn(AsnQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity<>(asnService.queryAll(criteria, pageable), HttpStatus.OK);
    }


    @GetMapping("/getIdByAsn")
    @Log("查询asn")
    @ApiOperation("查询asn")
    @AnonymousAccess
    public ResponseEntity<Object> getIdByAsn(@RequestParam("id") Long id) {
        return new ResponseEntity<>(asnService.findById(id), HttpStatus.OK);
    }

    @GetMapping("/queryAsnAll")
    @Log("查询asn")
    @ApiOperation("查询asn")
    @AnonymousAccess
    public ResponseEntity<Object> queryAsnAll(AsnQueryCriteria criteria) {
        return new ResponseEntity<>(asnService.queryAll(criteria), HttpStatus.OK);
    }

    @PostMapping
    @Log("新增asn")
    @ApiOperation("新增asn")
    @PreAuthorize("@el.check('super:man')")
    public ResponseEntity<Object> createAsn(@Validated @RequestBody Asn resources) {
        return new ResponseEntity<>(asnService.create(resources), HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改asn")
    @ApiOperation("修改asn")
    @PreAuthorize("@el.check('super:man')")
    public ResponseEntity<Object> updateAsn(@Validated @RequestBody Asn resources) {
        asnService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除asn")
    @ApiOperation("删除asn")
    @PreAuthorize("@el.check('super:man')")
    public ResponseEntity<Object> deleteAsn(@RequestBody Long[] ids) {
        asnService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @DeleteMapping(value = "/deleteAsnAndDetail")
    @Log("删除入库单和入库明细")
    @ApiOperation("删除入库单和入库明细")
    @PreAuthorize("@el.check('super:man')")
    public ResponseEntity<Object> deleteAsnAndDetail(@RequestBody Long[] ids) {
        try {
            for (Long id : ids) {
                asnService.deleteAsnAndDetail(id);
            }
            return new ResponseEntity<>(ApiResult.success("删除成功", null), HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(ApiResult.fail(HttpStatus.BAD_REQUEST.value(), e.getMessage(), null), HttpStatus.BAD_REQUEST);
        }

    }

    @PostMapping("/zlRegister")
    @Log("入库整理登记")
    @ApiOperation("入库整理登记")
    @PreAuthorize("@el.check('super:man')")
    @Transactional
    @DuplicateSubmission(5)
    public ResponseEntity<Object> zlRegister(@RequestBody Long[] ids) {
        for (Long id : ids) {
            Asn asn = asnService.getEntity(id);
            BillType bt = asn.getBillType();
            if (bt.getBezl()) {
                if (!asn.getStatus().equals(BizStatus.OPEN)) {
                    throw new BadRequestException(asn.getCode() + "状态不正确，打开状态才能操作");
                }
                asn.setZlBy(SecurityUtils.getCurrentUsername());
                asn.setZlDate(new Timestamp(new Date().getTime()));
                asn.setStatus(BizStatus.ZL);
                asnService.update(asn);
            } else {
                throw new BadRequestException(asn.getCode() + "不需要整理");
            }
        }
        return new ResponseEntity<>("操作成功", HttpStatus.OK);
    }

    @PostMapping("/cyRegister")
    @Log("入库抽样登记")
    @ApiOperation("入库抽样登记")
    @PreAuthorize("@el.check('super:man')")
    @Transactional
    @DuplicateSubmission(5)
    public ResponseEntity<Object> cyRegister(@RequestBody Long[] ids) {
        for (Long id : ids) {
            Asn asn = asnService.getEntity(id);
            BillType bt = asn.getBillType();
            if (bt.getBezl() && asn.getZlBy() == null) {
                throw new BadRequestException(asn.getCode() + "该单子还未整理，请先整理");
            }
            if (bt.getBecy()) {
                if (!asn.getStatus().equals(BizStatus.OPEN) && !asn.getStatus().equals(BizStatus.ZL)) {
                    throw new BadRequestException(asn.getCode() + "状态不正确，打开或整理状态才能操作");
                }
                asn.setCyBy(SecurityUtils.getCurrentUsername());
                asn.setCyDate(new Timestamp(new Date().getTime()));
                asn.setStatus(BizStatus.CY);
                asnService.update(asn);
            } else {
                throw new BadRequestException(asn.getCode() + "不需要抽样");
            }
        }
        return new ResponseEntity<>("操作成功", HttpStatus.OK);
    }

    @PostMapping("/zjRegister")
    @Log("入库质检登记")
    @ApiOperation("入库质检登记")
    @PreAuthorize("@el.check('super:man')")
    @Transactional
    @DuplicateSubmission(5)
    public ResponseEntity<Object> zjRegister(@RequestBody Long[] ids) {
        for (Long id : ids) {
            Asn asn = asnService.getEntity(id);
            BillType bt = asn.getBillType();
            if (bt.getBezl() && asn.getZlBy() == null) {
                throw new BadRequestException(asn.getCode() + "该单子还未整理，请先整理");
            }
            if (bt.getBecy() && asn.getCyBy() == null) {
                throw new BadRequestException(asn.getCode() + "该单子还未抽样，请先抽样");
            }
            if (bt.getBezj()) {
                if (!asn.getStatus().equals(BizStatus.OPEN) && !asn.getStatus().equals(BizStatus.ZL) && !asn.getStatus().equals(BizStatus.CY)) {
                    throw new BadRequestException(asn.getCode() + "状态不正确，打开或整理或抽样状态才能操作");
                }
                asn.setZjBy(SecurityUtils.getCurrentUsername());
                asn.setZjDate(new Timestamp(new Date().getTime()));
                asn.setStatus(BizStatus.ZJ);
                asnService.update(asn);
            } else {
                throw new BadRequestException(asn.getCode() + "不需要质检");
            }
        }
        return new ResponseEntity<>("操作成功", HttpStatus.OK);
    }
}
