package net.ferrum.web.controller.business;

import cn.dev33.satoken.annotation.SaCheckPermission;
import lombok.RequiredArgsConstructor;
import net.ferrum.business.domain.bo.QsSupplierBo;
import net.ferrum.business.domain.bo.QsUserSupplierBo;
import net.ferrum.business.domain.vo.QsSupplierVo;
import net.ferrum.business.service.IQsSupplierService;
import net.ferrum.business.service.IQsUserSupplierService;
import net.ferrum.common.annotation.Log;
import net.ferrum.common.annotation.RepeatSubmit;
import net.ferrum.common.core.controller.BaseController;
import net.ferrum.common.core.domain.PageQuery;
import net.ferrum.common.core.domain.R;
import net.ferrum.common.core.page.TableDataInfo;
import net.ferrum.common.core.validate.AddGroup;
import net.ferrum.common.core.validate.EditGroup;
import net.ferrum.common.enums.BusinessType;
import net.ferrum.common.utils.poi.ExcelUtil;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 供应商信息
 *
 * @author ferrum
 * @version 1.0.0
 * @since 2025-03-05
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/business/supplier")
public class QsSupplierController extends BaseController {

    private final IQsSupplierService iQsSupplierService;

    private final IQsUserSupplierService iQsUserSupplierService;

    /**
     * 查询供应商信息列表
     */
    @SaCheckPermission("business:supplier:list")
    @GetMapping("/list")
    public TableDataInfo<QsSupplierVo> list(QsSupplierBo bo, PageQuery pageQuery) {

        return iQsUserSupplierService.selectSuppliersByUsersPages(bo, pageQuery);

        //return iQsSupplierService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出供应商信息列表
     */
    @SaCheckPermission("business:supplier:export")
    @Log(title = "供应商信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(QsSupplierBo bo, HttpServletResponse response) {
        List<QsSupplierVo> list = iQsSupplierService.queryList(bo);
        ExcelUtil.exportExcel(list, "供应商信息", QsSupplierVo.class, response);
    }

    /**
     * 获取供应商信息详细信息
     *
     * @param supplierId 主键
     */
    @SaCheckPermission("business:supplier:query")
    @GetMapping("/{supplierId}")
    public R<QsSupplierVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable String supplierId) {
        return R.ok(iQsSupplierService.queryById(Long.parseLong(supplierId)));
    }

    /**
     * 新增供应商信息
     */
    @SaCheckPermission("business:supplier:add")
    @Log(title = "供应商信息", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody QsSupplierBo bo) {
        boolean ret = iQsSupplierService.insertByBo(bo);
        if (ret == true){
            bo.getDockerUsers().forEach(dockerUser -> {
                if(dockerUser.getDel()==null){ //=null是新增加的，=2是增加后，又删除了的
                    QsUserSupplierBo qsUserSupplierBo = new QsUserSupplierBo();
                    qsUserSupplierBo.setSupplierId(bo.getSupplierId());
                    qsUserSupplierBo.setUserId(dockerUser.getUserId());
                    if (dockerUser.getId() == null){
                        iQsUserSupplierService.insertByBo(qsUserSupplierBo);
                    }
                    else{
                        qsUserSupplierBo.setId(dockerUser.getId());
                        iQsUserSupplierService.updateByBo(qsUserSupplierBo);
                    }
                }
            });
        }


        return toAjax(ret);
    }

    /**
     * 修改供应商信息
     */
    @SaCheckPermission("business:supplier:edit")
    @Log(title = "供应商信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody QsSupplierBo bo) {
        List<Long> ids = new ArrayList<>();
        bo.getDockerUsers().forEach(dockerUser -> {

            if(dockerUser.getDel()!=null){//=null是原来有的，!=null 是后增加的
                ids.add(dockerUser.getId());
            }
            else{
                QsUserSupplierBo qsUserSupplierBo = new QsUserSupplierBo();
                qsUserSupplierBo.setSupplierId(bo.getSupplierId());
                qsUserSupplierBo.setUserId(dockerUser.getUserId());
                if (dockerUser.getId() == null){
                    iQsUserSupplierService.insertByBo(qsUserSupplierBo);
                }
                else{
                    qsUserSupplierBo.setId(dockerUser.getId());
                    iQsUserSupplierService.updateByBo(qsUserSupplierBo);
                }
            }

        });
        if ( !(ids == null || ids.isEmpty()) ){
            iQsUserSupplierService.deleteWithValidByIds(ids,true);
        }
        return toAjax(iQsSupplierService.updateByBo(bo));
    }

    /**
     * 删除供应商信息
     *
     * @param supplierIds 主键串
     */
    @SaCheckPermission("business:supplier:remove")
    @Log(title = "供应商信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{supplierIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] supplierIds) {
        return toAjax(iQsSupplierService.deleteWithValidByIds(Arrays.asList(supplierIds), true));
    }

}
