package com.aegis.web.controller.resource.supplier;

import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.aegis.common.annotation.Log;
import com.aegis.common.core.controller.BaseController;
import com.aegis.common.core.domain.AjaxResult;
import com.aegis.common.core.page.TableDataInfo;
import com.aegis.common.enums.BusinessType;
import com.aegis.resource.supplier.assembler.SupplierAssembler;
import com.aegis.resource.supplier.domain.Supplier;
import com.aegis.resource.supplier.domain.SupplierLicense;
import com.aegis.resource.supplier.dto.SupplierDTO;
import com.aegis.resource.supplier.service.IResourceSupplierService;

/**
 * 供应商Controller
 * 
 * @author aegis
 */
@RestController
@RequestMapping("/resources/suppliers")
public class ResourceSupplierController extends BaseController {

    @Autowired
    private IResourceSupplierService supplierService;

    /**
     * 查询供应商列表
     */
    @PreAuthorize("@ss.hasPermi('resource:supplier:list')")
    @GetMapping("/list")
    public TableDataInfo list(Supplier supplier) {
        startPage();
        List<Supplier> list = supplierService.listSuppliers(supplier);
        return getDataTable(list);
    }

    /**
     * 根据ID获取供应商详情
     */
    @PreAuthorize("@ss.hasPermi('resource:supplier:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        return success(supplierService.getSupplierById(id));
    }

    /**
     * 新增供应商
     */
    @PreAuthorize("@ss.hasPermi('resource:supplier:add')")
    @Log(title = "供应商管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SupplierDTO supplierDTO) {
        Supplier supplier = SupplierAssembler.toDomain(supplierDTO);
        // 唯一性检查和恢复逻辑由 Service 层统一处理
        return toAjax(supplierService.createSupplier(supplier));
    }

    /**
     * 修改供应商
     */
    @PreAuthorize("@ss.hasPermi('resource:supplier:edit')")
    @Log(title = "供应商管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SupplierDTO supplierDTO) {
        Supplier supplier = SupplierAssembler.toDomain(supplierDTO);
        // 唯一性检查和恢复逻辑由 Service 层统一处理
        return toAjax(supplierService.modifySupplier(supplier));
    }

    /**
     * 删除供应商
     */
    @PreAuthorize("@ss.hasPermi('resource:supplier:remove')")
    @Log(title = "供应商管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String ids) {
        // 支持单个ID和多个ID（逗号分隔）
        Long[] idArray = null;
        if (ids.contains(",")) {
            String[] idStrings = ids.split(",");
            idArray = new Long[idStrings.length];
            for (int i = 0; i < idStrings.length; i++) {
                idArray[i] = Long.parseLong(idStrings[i].trim());
            }
        } else {
            idArray = new Long[]{Long.parseLong(ids.trim())};
        }
        return toAjax(supplierService.removeSuppliers(idArray));
    }

    /**
     * 启用供应商
     */
    @PreAuthorize("@ss.hasPermi('resource:supplier:edit')")
    @Log(title = "供应商管理", businessType = BusinessType.UPDATE)
    @PostMapping("/{id}/activate")
    public AjaxResult activate(@PathVariable Long id) {
        return toAjax(supplierService.activateSupplier(id));
    }

    /**
     * 停用供应商
     */
    @PreAuthorize("@ss.hasPermi('resource:supplier:edit')")
    @Log(title = "供应商管理", businessType = BusinessType.UPDATE)
    @PostMapping("/{id}/deactivate")
    public AjaxResult deactivate(@PathVariable Long id) {
        return toAjax(supplierService.deactivateSupplier(id));
    }

    /**
     * 加入黑名单
     */
    @PreAuthorize("@ss.hasPermi('resource:supplier:edit')")
    @Log(title = "供应商管理", businessType = BusinessType.UPDATE)
    @PostMapping("/{id}/blacklist")
    public AjaxResult blacklist(@PathVariable Long id) {
        return toAjax(supplierService.blacklistSupplier(id));
    }

    /**
     * 评分（1-5星）
     */
    @PreAuthorize("@ss.hasPermi('resource:supplier:edit')")
    @Log(title = "供应商管理", businessType = BusinessType.UPDATE)
    @PostMapping("/{id}/rate")
    public AjaxResult rate(@PathVariable Long id, @RequestBody Map<String, Object> params) {
        Integer rating = params.get("rating") != null ? Integer.valueOf(params.get("rating").toString()) : null;
        if (rating == null || rating < 1 || rating > 5) {
            return error("评分必须在1-5之间");
        }
        return toAjax(supplierService.updateSupplierRating(id, rating));
    }

    /**
     * 查询资质列表
     */
    @PreAuthorize("@ss.hasPermi('resource:supplier:query')")
    @GetMapping("/{id}/licenses")
    public TableDataInfo listLicenses(@PathVariable Long id, SupplierLicense license) {
        license.setSupplierId(id);
        startPage();
        List<SupplierLicense> list = supplierService.listLicenses(license);
        return getDataTable(list);
    }

    /**
     * 根据ID获取资质详情
     */
    @PreAuthorize("@ss.hasPermi('resource:supplier:query')")
    @GetMapping("/licenses/{licenseId}")
    public AjaxResult getLicenseInfo(@PathVariable Long licenseId) {
        return success(supplierService.getLicenseById(licenseId));
    }

    /**
     * 新增资质
     */
    @PreAuthorize("@ss.hasPermi('resource:supplier:edit')")
    @Log(title = "供应商资质管理", businessType = BusinessType.INSERT)
    @PostMapping("/{id}/licenses")
    public AjaxResult addLicense(@PathVariable Long id, @Validated @RequestBody SupplierLicense license) {
        license.setSupplierId(id);
        return toAjax(supplierService.createLicense(license));
    }

    /**
     * 修改资质
     */
    @PreAuthorize("@ss.hasPermi('resource:supplier:edit')")
    @Log(title = "供应商资质管理", businessType = BusinessType.UPDATE)
    @PutMapping("/{id}/licenses/{licenseId}")
    public AjaxResult editLicense(@PathVariable Long id, @PathVariable Long licenseId, @Validated @RequestBody SupplierLicense license) {
        license.setId(licenseId);
        license.setSupplierId(id);
        return toAjax(supplierService.modifyLicense(license));
    }

    /**
     * 删除资质
     */
    @PreAuthorize("@ss.hasPermi('resource:supplier:edit')")
    @Log(title = "供应商资质管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}/licenses/{licenseId}")
    public AjaxResult removeLicense(@PathVariable Long id, @PathVariable Long licenseId) {
        return toAjax(supplierService.removeLicense(licenseId));
    }
}