package com.kingtom.shengtai.api.controller;

import java.util.*;
import java.util.stream.Collectors;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaCheckRole;
import com.kingtom.kirin.api.security.SaSecurityUtils;
import com.kingtom.kirin.api.system.mapper.SystemMapper;
import com.kingtom.kirin.api.system.model.SystemUserDTO;
import com.kingtom.kirin.app.security.base.SessionData;
import com.kingtom.kirin.app.system.SystemConst;
import com.kingtom.kirin.app.system.model.SystemUser;
import com.kingtom.kirin.core.common.CommonConst;
import com.kingtom.kirin.core.common.base.PageInfo;
import com.kingtom.kirin.core.common.base.Result;
import com.kingtom.kirin.core.common.utils.CollectionUtils;
import com.kingtom.kirin.core.common.utils.JsonUtils;
import com.kingtom.shengtai.api.mapper.SrmMapper;
import com.kingtom.shengtai.api.model.SrmSupplierDTO;
import com.kingtom.shengtai.app.srm.model.ProductDir;
import com.kingtom.shengtai.app.srm.service.IProductDirService;
import com.kingtom.shengtai.app.srm.model.SrmSupplier;
import com.kingtom.shengtai.app.srm.model.SrmSupplierDO;
import com.kingtom.shengtai.app.srm.service.ISrmSupplierService;
import com.mybatisflex.core.paginate.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 供应商信息表 控制层。
 *
 * @author wany
 * @since 2023-12-21
 */
@Tag(name = "SrmSupplierController", description = "供应商信息表 控制层。")
@RestController
@RequestMapping("/srmSuppliers")
public class SrmSupplierController{

    @Autowired
    private ISrmSupplierService iSrmSupplierService;

    @Autowired
    private IProductDirService productDirService;

    /**
     * 添加供应商信息表。
     *
     * @param dto
     *         供应商信息表
     * @return {@code true} 添加成功，{@code false} 添加失败
     */
    @Operation(summary = "添加供应商信息表。", description = "添加供应商信息表。")
    @PostMapping("/")
    @SaCheckPermission(value = {"AuthMenu:srm_supplier:Execute"})
    public Result<SrmSupplierDTO> save(@RequestBody SrmSupplierDTO dto){
        SrmSupplier convert = SrmMapper.INSTANCE.convert(dto);
        SrmSupplierDO supplierDO = iSrmSupplierService.create(convert);
        return Result.ok(SrmSupplierDTO.convert(supplierDO));
    }

    /**
     * 根据主键删除供应商信息表。
     *
     * @param id
     *         主键
     * @return {@code true} 删除成功，{@code false} 删除失败
     */
    @Parameter(name = "id", description = "主键", in = ParameterIn.PATH, required = true)
    @Operation(summary = "根据主键删除供应商信息表。", description = "根据主键删除供应商信息表。")
    @PostMapping("/{id}/")
    @SaCheckPermission(value = {"AuthMenu:srm_supplier:Execute"})
    public Result<String> remove(@PathVariable String id){
        iSrmSupplierService.deleteById(id);
        return Result.ok(null);
    }

    /**
     * 根据主键删除供应商信息表。
     *
     * @param ids
     *         主键
     * @return {@code true} 删除成功，{@code false} 删除失败
     */
    @Operation(summary = "根据主键批量删除供应商信息表。", description = "根据主键批量删除供应商信息表。")
    @PostMapping("/remove_batch")
    @SaCheckPermission(value = {"AuthMenu:srm_supplier:Execute"})
    public Result<String> remove(@RequestBody List<String> ids){
        iSrmSupplierService.deleteByIds(ids);
        return Result.ok(null);
    }

    /**
     * 根据主键更新供应商信息表。
     *
     * @param dto
     *         供应商信息表
     * @return {@code true} 更新成功，{@code false} 更新失败
     */
    @Parameter(name = "id", description = "", in = ParameterIn.PATH, required = true)
    @Operation(summary = "根据主键更新供应商信息表。", description = "根据主键更新供应商信息表。")
    @PostMapping("/{id}/info")
    @SaCheckPermission(value = {"AuthMenu:srm_supplier:Execute"})
    public Result<SrmSupplierDTO> update(@RequestBody SrmSupplierDTO dto, @PathVariable String id){
        //只能更新评分、类型、产品目录
        SrmSupplier update = new SrmSupplier();
        update.setId(id);
        update.setMark(dto.getMark());
        update.setType(dto.getType());
        List<String> list = dto.getProduct();
        if(list == null){
            list = new ArrayList<>();
        }
        update.setProduct(JsonUtils.toJson(list));
        SrmSupplierDO supplierDO = iSrmSupplierService.update(update);
        return Result.ok(SrmSupplierDTO.convert(supplierDO));
    }

    /**
     * 根据供应商信息表主键获取详细信息。
     *
     * @param id
     *         供应商信息表主键
     * @return 供应商信息表详情
     */
    @Parameter(name = "id", description = "供应商信息表主键", in = ParameterIn.PATH, required = true)
    @Operation(summary = "根据供应商信息表主键获取详细信息。", description = "根据供应商信息表主键获取详细信息。")
    @GetMapping("/{id}/info")
    @SaCheckPermission(value = {"AuthMenu:srm_supplier:Execute"})
    public Result<SrmSupplierDTO> getInfo(@PathVariable String id){
        SrmSupplierDO supplierDO = iSrmSupplierService.findById(id);
        return Result.ok(SrmSupplierDTO.convert(supplierDO));
    }

    /**
     * 分页查询供应商信息表。
     *
     * @param query
     *         查询条件
     * @param pageNum
     *         当前页码
     * @param pageSize
     *         每页数量
     * @return 分页对象
     */
    @Operation(summary = "分页查询供应商信息表。", description = "分页查询供应商信息表。")
    @GetMapping("/page")
    @SaCheckPermission(value = {"AuthMenu:srm_supplier:Execute"})
    public Result<PageInfo<SrmSupplierDTO>> page(String query, Integer pageNum, Integer pageSize){
        Map<String, Object> object = JsonUtils.toObject(query, Map.class);
        String name = object.get("name") instanceof String ? object.get("name").toString() : null;
        String type = object.get("type") instanceof String ? object.get("type").toString() : null;
        String state = object.get("state") instanceof String ? object.get("state").toString() : null;
        List<String> products = object.get("products") instanceof Collection<?> ?
                ((Collection<?>)object.get("products")).stream().map(e -> e instanceof String ? ((String)e) : null)
                                                       .collect(Collectors.toList()) : null;
        Page<SrmSupplierDO> page = iSrmSupplierService.page(name, type, state, products, pageNum, pageSize);
        return Result.ok(CollectionUtils.convertPage(page, SrmSupplierDTO::convert));
    }

    /**
     * 我的供应商。
     *
     * @return 供应商信息表详情
     */
    @Operation(description = "我的供应商")
    @GetMapping("/self")
    @SaCheckRole(value = {"supplier"})
    public Result<SrmSupplierDTO> getSelf(){
        SessionData sessionData = SaSecurityUtils.findSessionData();
        String userId = sessionData.getUserId();
        SrmSupplier supplier = iSrmSupplierService.findByPerson(userId);
        SystemUserDTO dto = sessionData.getAttr(SystemConst.SESSION_ATTR_SYSTEM_USER);
        SystemUser user = SystemMapper.INSTANCT.convert(dto);
        SrmSupplierDO supplierDO = SrmSupplierDO.builder().supplier(supplier).user(user).build();
        return Result.ok(SrmSupplierDTO.convert(supplierDO));
    }

    @Operation(description = "供应商评分申诉")
    @PostMapping("/appeal")
    @SaCheckRole(value = {"supplier"})
    public Result<String> appeal(@RequestBody String content){
        SessionData sessionData = SaSecurityUtils.findSessionData();
        String userId = sessionData.getUserId();
        iSrmSupplierService.appeal(userId, content);
        return Result.ok(null);
    }

    @Operation(description = "供应商修改自己的供应商信息")
    @PostMapping("/self/info")
    @SaCheckRole(value = {"supplier"})
    public Result<SrmSupplierDTO> updateSelf(@RequestBody SrmSupplierDTO dto){
        SessionData sessionData = SaSecurityUtils.findSessionData();
        String userId = sessionData.getUserId();
        SrmSupplier supplier = iSrmSupplierService.findByPerson(userId);
        if(supplier == null){
            return Result.fail("没有找到供应商信息");
        }
        SrmSupplier convert = SrmMapper.INSTANCE.convert(dto);
        convert.setId(supplier.getId());
        //不能更新评分和类型
        convert.setMark(null);
        convert.setType(null);
        //兼容移动端不能发送字符串数组问题
        if(StringUtils.isNotEmpty(dto.getImageStr())){
            List<String> images = Arrays.asList(dto.getImageStr().split(CommonConst.COMMA_STRING));
            convert.setImage(JsonUtils.toJson(images));
        }
        if(StringUtils.isNotEmpty(dto.getCertificatesStr())){
            List<String> certificates = Arrays.asList(dto.getCertificatesStr().split(CommonConst.COMMA_STRING));
            convert.setCertificates(JsonUtils.toJson(certificates));
        }
        SrmSupplierDO update = iSrmSupplierService.update(convert);
        return Result.ok(SrmMapper.INSTANCE.convert(update.getSupplier()));
    }

    @Operation(description = "供应商移动端首页，获取自己的优势产品")
    @GetMapping("/self/product/info")
    @SaCheckRole(value = {"supplier"})
    public Result<LinkedHashMap<String, String>> getSelfProducts(){
        SessionData sessionData = SaSecurityUtils.findSessionData();
        String userId = sessionData.getUserId();
        SrmSupplier supplier = iSrmSupplierService.findByPerson(userId);
        if(supplier == null){
            return Result.fail("没有找到供应商信息");
        }
        List<String> productIds = JsonUtils.toObjectList(supplier.getProduct(), String.class);
        List<ProductDir> dirs = productDirService.findByIds(productIds);
        LinkedHashMap<String,String> map = new LinkedHashMap<>(dirs.size());
        dirs.forEach(e-> map.put(e.getCode(),e.getName()));
        return Result.ok(map);
    }

}
