package com.izouma.nineth.web;


import com.izouma.nineth.domain.ActivityPriorityDocument;
import com.izouma.nineth.domain.Asset;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.enums.ItemType;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.ActivityPriorityDocumentRepo;
import com.izouma.nineth.repo.AssetRepo;
import com.izouma.nineth.service.ActivityPriorityDocumentService;
import com.izouma.nineth.utils.JpaUtils;
import com.izouma.nineth.utils.ObjUtils;
import com.izouma.nineth.utils.excel.ExcelUtils;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 优先购设置
 */
@RestController
@RequestMapping("/activityPriorityDocument")
@AllArgsConstructor
public class ActivityPriorityDocumentController extends BaseController {

    private ActivityPriorityDocumentRepo activityPriorityDocumentRepo;
    private AssetRepo assetRepo;
    private ActivityPriorityDocumentService activityPriorityDocumentService;

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public ActivityPriorityDocument save(@RequestBody ActivityPriorityDocument record) {
        //这里只查询出asset.id ,asset.userId ,asset.projectId
        List<Asset> assets = assetRepo.findAssetHeldId(record.getCollectionId(), record.getProjectId());
        if (record.getId() != null) {
            ActivityPriorityDocument orig = activityPriorityDocumentRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
            if (orig.getCollectionId()!=null && !orig.getCollectionId().equals(record.getCollectionId())){
                throw new BusinessException("持有藏品不可更改");
            }
            if (orig.getAdvancePurchaseCount()!=record.getAdvancePurchaseCount()){
                throw new BusinessException("优先购次数不可修改");
            }
            ObjUtils.merge(orig, record);
            orig.setItemName(ItemType.getValue(record.ItemId));
            activityPriorityDocumentService.resetAllUserWareHouseLsit(assets, orig, false);//修改,编辑
            return activityPriorityDocumentRepo.save(orig);
        }
        record.setItemName(ItemType.getValue(record.ItemId));
        //先保存配置在给用户添加优先购
        activityPriorityDocumentRepo.save(record);
        activityPriorityDocumentService.saveAllUserWareHouseLsit(assets, record);
        return record;
    }
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/reset")
    public ActivityPriorityDocument reset(@RequestBody ActivityPriorityDocument record) {
        List<Asset> assets = assetRepo.findAssetHeldId(record.getCollectionId(), record.getProjectId());
        if (record.getId() != null) {
            ActivityPriorityDocument orig = activityPriorityDocumentRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
            activityPriorityDocumentService.resetAllUserWareHouseLsit(assets, record, true);//重置
            return orig;
        }
        throw new BusinessException("没有修改的目标ID");
    }


    //@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/all")
    public Page<ActivityPriorityDocument> all(@RequestBody PageQuery pageQuery) {
        return activityPriorityDocumentRepo.findAll(JpaUtils.toSpecification(pageQuery, ActivityPriorityDocument.class), JpaUtils.toPageRequest(pageQuery));
    }

    @GetMapping("/get/{id}")
    public ActivityPriorityDocument get(@PathVariable Long id) {
            return activityPriorityDocumentRepo.findById(id).orElseThrow(new BusinessException("优先凭证无记录"));
    }


    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/del/{id}")
    public void del(@PathVariable Long id) {
        ActivityPriorityDocument record = activityPriorityDocumentRepo.findById(id).orElseThrow(new BusinessException("优先凭证无记录"));
        List<Asset> assets = assetRepo.findAssetHeldId(record.getCollectionId(), record.getProjectId());
        activityPriorityDocumentService.delAllUserWareHouseLsit( assets, id);
        activityPriorityDocumentRepo.softDelete(id);
    }

    @PostMapping("/excel")
    @ResponseBody
    public void excel(HttpServletResponse response, @RequestBody PageQuery pageQuery) throws IOException {
        List<ActivityPriorityDocument> data = all(pageQuery).getContent();
        ExcelUtils.export(response, data);
    }
}
