
package com.tmerclub.cloud.supplier.controller.platform;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import com.tmerclub.cloud.api.auth.constant.SysTypeEnum;
import com.tmerclub.cloud.api.auth.dto.AuthAccountDTO;
import com.tmerclub.cloud.api.auth.feign.AccountFeignClient;
import com.tmerclub.cloud.api.auth.vo.AuthAccountVO;
import com.tmerclub.cloud.api.platform.constant.OfflineHandleEventStatus;
import com.tmerclub.cloud.api.platform.dto.OfflineHandleEventDTO;
import com.tmerclub.cloud.api.supplier.constant.SupplierStatus;
import com.tmerclub.cloud.api.supplier.vo.SupplierApiDetailVO;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.database.dto.PageDTO;
import com.tmerclub.cloud.common.database.vo.PageVO;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.response.ResponseEnum;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.security.AuthUserContext;
import com.tmerclub.cloud.common.util.BeanUtil;
import com.tmerclub.cloud.supplier.constant.IsPreferred;
import com.tmerclub.cloud.supplier.dto.SupplierAccountDTO;
import com.tmerclub.cloud.supplier.dto.SupplierCreateInfoDTO;
import com.tmerclub.cloud.supplier.dto.SupplierDetailDTO;
import com.tmerclub.cloud.supplier.dto.SupplierSigningInfoDTO;
import com.tmerclub.cloud.supplier.service.SupplierDetailService;
import com.tmerclub.cloud.supplier.vo.SupplierDetailVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * 供应商详情
 *
 * @author tmerclub
 * @date 2020-12-05 15:50:25
 */
@RestController("platformSupplierDetailController")
@RequestMapping("/p/supplier_detail")
@Tag(name = "platform-供应商信息")
public class SupplierDetailController {

    @Value("${tmerclub.expose.permission:}")
    private Boolean permission;

    @Autowired
    private SupplierDetailService supplierDetailService;
    @DubboReference
    private AccountFeignClient accountFeignClient;

    @GetMapping("/page")
    @Operation(summary = "分页查询", description = "分页查询")
    public ServerResponseEntity<PageVO<SupplierApiDetailVO>> getSupplierAuditingPage(PageDTO pageDTO, SupplierDetailDTO supplierDetailDTO) {
        if (!Objects.equals(Constant.PLATFORM_SHOP_ID, AuthUserContext.get().getTenantId())) {
            throw new LuckException(ResponseEnum.UNAUTHORIZED);
        }
        return ServerResponseEntity.success(supplierDetailService.page(pageDTO, supplierDetailDTO));
    }

    @GetMapping("/info")
    @Operation(summary = "获取供应商基本信息", description = "获取供应商基本信息")
    public ServerResponseEntity<SupplierApiDetailVO> getInfo(@RequestParam Long supplierId) {
        SupplierApiDetailVO supplierApiDetailVO = supplierDetailService.getBySupplierId(supplierId);
        if (StrUtil.isNotBlank(supplierApiDetailVO.getContactPhone())) {
            supplierApiDetailVO.setContactPhone(PhoneUtil.hideBetween(supplierApiDetailVO.getContactPhone()).toString());
        }
        ServerResponseEntity<AuthAccountVO> responseEntity = accountFeignClient.getAccountInfoByTenantId(supplierId, SysTypeEnum.SUPPLIER.value());
        if (responseEntity.isSuccess() && Objects.nonNull(responseEntity.getData())) {
            AuthAccountVO authAccountVO = responseEntity.getData();
            supplierApiDetailVO.setSupplierAccount(PhoneUtil.hideBetween(authAccountVO.getPhone()).toString());
            supplierApiDetailVO.setAccountStatus(authAccountVO.getStatus());
        }
        return ServerResponseEntity.success(supplierApiDetailVO);
    }

    /**
     * 新建供应商
     */
    @PostMapping("/create_supplier")
    @Operation(summary = "新建供应商", description = "新建供应商")
    public ServerResponseEntity<Void> createSupplier(@RequestBody SupplierCreateInfoDTO supplierCreateInfoDTO) {
        supplierDetailService.platformCreateSupplier(supplierCreateInfoDTO);
        return ServerResponseEntity.success();
    }

    @PutMapping
    @Operation(summary = "编辑供应商基本信息", description = "编辑供应商基本信息")
    public ServerResponseEntity<Void> editSupplier(@RequestBody SupplierDetailDTO supplierDetailDTO) {
        if (Objects.isNull(supplierDetailDTO.getSupplierId())) {
            throw new LuckException("供应商id不能为空");
        }
        supplierDetailService.update(supplierDetailDTO);
        return ServerResponseEntity.success();
    }

    @PutMapping("/update_signing_info")
    @Operation(summary = "更新供应商签约信息", description = "更新供应商签约信息")
    public ServerResponseEntity<Void> updateSigningInfo(@RequestBody @Valid SupplierSigningInfoDTO supplierSigningInfoDTO) {
        if (Objects.isNull(supplierSigningInfoDTO.getSupplierId())) {
            throw new LuckException("供应商id不能为空");
        }
        supplierDetailService.updateSigningInfo(supplierSigningInfoDTO);
        return ServerResponseEntity.success();
    }

    @PutMapping("/update_supplier_preferred")
    @Operation(summary = "当前供应商为优选，则取消优选;不是优选，则设置为优选", description = "当前供应商为优选，则取消优选;不是优选，则设置为优选")
    public ServerResponseEntity<Void> updateSupplierPreferred(@RequestParam("supplierId") Long supplierId) {
        SupplierApiDetailVO supplierApiDetailVO = supplierDetailService.getBySupplierId(supplierId);
        supplierApiDetailVO.setIsPreferred(Objects.equals(supplierApiDetailVO.getIsPreferred(), IsPreferred.YES.value()) ? IsPreferred.NO.value() : IsPreferred.YES.value());
        supplierDetailService.update(BeanUtil.map(supplierApiDetailVO, SupplierDetailDTO.class));
        return ServerResponseEntity.success();
    }

    @PutMapping("/updatePassword")
    @Operation(summary = "更新供应商账户的登录密码", description = "更新供应商账户的登录密码")
    public ServerResponseEntity<Void> updatePassword(@RequestBody SupplierAccountDTO supplierAccountDTO) {
        if (Objects.equals(supplierAccountDTO.getSupplierId(), Constant.ON_LINE_SUPPLIER_ID) && BooleanUtil.isFalse(permission)) {
            throw new LuckException("没有权限进行操作");
        }
        ServerResponseEntity<AuthAccountVO> merchantInfoByTenantId = accountFeignClient.getAccountInfoByTenantId(supplierAccountDTO.getSupplierId(), SysTypeEnum.SUPPLIER.value());
        if (!merchantInfoByTenantId.isSuccess()) {
            throw new LuckException("服务异常");
        }
        AuthAccountVO authAccountVO = merchantInfoByTenantId.getData();
        authAccountVO.setPassword(supplierAccountDTO.getPassword());
        accountFeignClient.update(BeanUtil.map(authAccountVO, AuthAccountDTO.class));
        return ServerResponseEntity.success();
    }

    @PutMapping("/offline")
    @Operation(summary = "下线供应商", description = "下线供应商")
    public ServerResponseEntity<Void> offline(@RequestBody OfflineHandleEventDTO offlineHandleEventDTO) {
        Long sysUserId = AuthUserContext.get().getUserId();
        SupplierApiDetailVO supplierApiDetailVO = supplierDetailService.getBySupplierId(offlineHandleEventDTO.getHandleId());
        if (Objects.isNull(supplierApiDetailVO)) {
            throw new LuckException("未找到该供应商信息");
        }
        if (!Objects.equals(supplierApiDetailVO.getSupplierStatus(), SupplierStatus.OPEN.value()) && !Objects.equals(supplierApiDetailVO.getSupplierStatus(), SupplierStatus.STOP.value())) {
            throw new LuckException("供应商不处于营业或者停业状态,不能进行下线");
        }
        supplierDetailService.offline(supplierApiDetailVO, offlineHandleEventDTO.getOfflineReason(), sysUserId);
        return ServerResponseEntity.success();
    }

    @GetMapping("/count_by_supplier_status")
    @Operation(summary = "根据供应商状态查询供应商数量", description = "根据供应商状态查询供应商数量")
    public ServerResponseEntity<Long> countBySupplierStatus(@RequestParam(value = "supplierStatus", required = false, defaultValue = "3") Long supplierStatus) {
        Long countBySupplierStatus = supplierDetailService.countBySupplierStatus(supplierStatus);
        return ServerResponseEntity.success(countBySupplierStatus);
    }

    @PostMapping("/online_audit")
    @Operation(summary = "供应商违规下线，重新申请上线审核", description = "供应商违规下线，重新申请上线审核")
    public ServerResponseEntity<Void> onlineAudit(@RequestBody OfflineHandleEventDTO offlineHandleEventDTO) {
        supplierDetailService.onlineAudit(offlineHandleEventDTO);
        return ServerResponseEntity.success();
    }

    @PostMapping("/online_open_shop")
    @Operation(summary = "供应商违规下线，平台直接上线供应商", description = "开通通联支付可用")
    public ServerResponseEntity<Void> onlineOpenSupplier(@RequestBody OfflineHandleEventDTO offlineHandleEventDTO) {
        offlineHandleEventDTO.setStatus(OfflineHandleEventStatus.AGREE_BY_PLATFORM.getValue());
        supplierDetailService.onlineOpenSupplier(offlineHandleEventDTO);
        return ServerResponseEntity.success();
    }

    @GetMapping("/page_supplier")
    @Operation(summary = "供应商列表", description = "供应商列表")
    public ServerResponseEntity<PageVO<SupplierDetailVO>> pageSupplier(@Valid PageDTO pageDTO, SupplierDetailDTO supplierDetailDTO) {
        supplierDetailDTO.setSysType(SysTypeEnum.PLATFORM.value());
        return ServerResponseEntity.success(supplierDetailService.pageSupplier(pageDTO, supplierDetailDTO, null));
    }

}
