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


import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import com.tmerclub.cloud.api.platform.constant.OfflineHandleEventType;
import com.tmerclub.cloud.api.platform.dto.OfflineHandleEventDTO;
import com.tmerclub.cloud.api.platform.feign.OfflineHandleEventFeignClient;
import com.tmerclub.cloud.api.platform.vo.OfflineHandleEventVO;
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.exception.LuckException;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.security.AuthUserContext;
import com.tmerclub.cloud.supplier.dto.SupplierDetailDTO;
import com.tmerclub.cloud.supplier.service.SupplierAllinpayService;
import com.tmerclub.cloud.supplier.service.SupplierDetailService;
import com.tmerclub.cloud.supplier.vo.SupplierStatusInfoVO;
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.web.bind.annotation.*;

import java.util.Objects;

/**
 * @author lth
 */
@RestController("supplierSupplierDetailController")
@RequestMapping("/s/apply_supplier/supplier_detail")
@Tag(name = "supplier-供应商信息")
public class SupplierDetailController {

    @Autowired
    private SupplierDetailService supplierDetailService;
    @DubboReference
    private OfflineHandleEventFeignClient offlineHandleEventFeignClient;
    @Autowired
    private SupplierAllinpayService supplierAllinpayService;

    @PostMapping
    @Operation(summary = "创建供应商", description = "创建供应商")
    public ServerResponseEntity<Void> createSupplier(@RequestBody @Valid SupplierDetailDTO supplierDetailDTO) {
        if (!Objects.equals(AuthUserContext.get().getTenantId(), Constant.DEFAULT_SUPPLIER_ID)) {
            throw new LuckException("供应商已存在,不能重复创建");
        }
        this.dealWithUpdateOrCreateInfo(supplierDetailDTO);
        supplierDetailService.createSupplier(supplierDetailDTO);
        return ServerResponseEntity.success();
    }

    @PutMapping
    @Operation(summary = "更新供应商基本信息", description = "更新供应商基本信息")
    public ServerResponseEntity<Void> update(@RequestBody @Valid SupplierDetailDTO supplierDetailDTO) {
        Long supplierId = AuthUserContext.get().getTenantId();
        if (Objects.equals(supplierId, Constant.DEFAULT_SUPPLIER_ID)) {
            throw new LuckException("供应商不存在,无法更新");
        }
        supplierDetailDTO.setSupplierId(supplierId);
        this.dealWithUpdateOrCreateInfo(supplierDetailDTO);
        supplierDetailService.update(supplierDetailDTO);
        return ServerResponseEntity.success();
    }

    @PostMapping("/storage")
    @Operation(summary = "存储供应商基本信息", description = "存储供应商基本信息,不存在则新增，已存在则更新")
    public ServerResponseEntity<Void> storage(@RequestBody @Valid SupplierDetailDTO supplierDetailDTO) {
        Long supplierId = AuthUserContext.get().getTenantId();
        this.dealWithUpdateOrCreateInfo(supplierDetailDTO);
        if (Objects.equals(supplierId, Constant.DEFAULT_SUPPLIER_ID)) {
            // 供应商不存在，新增
            supplierDetailService.createSupplier(supplierDetailDTO);
        } else {
            // 供应商已存在，更新
            supplierDetailDTO.setSupplierId(supplierId);
            supplierDetailService.update(supplierDetailDTO);
        }
        return ServerResponseEntity.success();
    }

    @GetMapping
    @Operation(summary = "获取供应商基本信息", description = "获取供应商基本信息")
    public ServerResponseEntity<SupplierApiDetailVO> get() {
        Long supplierId = AuthUserContext.get().getTenantId();
        if (Objects.equals(supplierId, Constant.DEFAULT_SUPPLIER_ID)) {
            // 供应商未创建
            return ServerResponseEntity.success(null);
        }
        SupplierApiDetailVO supplierApiDetailVO = supplierDetailService.getBySupplierId(supplierId);
        if (Objects.nonNull(supplierApiDetailVO) && StrUtil.isNotBlank(supplierApiDetailVO.getContactPhone())) {
            supplierApiDetailVO.setContactPhone(PhoneUtil.hideBetween(supplierApiDetailVO.getContactPhone()).toString());
        }
        return ServerResponseEntity.success(supplierApiDetailVO);
    }

    @GetMapping("/get_status_info")
    @Operation(summary = "获取供应商状态信息", description = "获取供应商状态信息")
    public ServerResponseEntity<SupplierStatusInfoVO> getSupplierStatusInfo() {
        Long supplierId = AuthUserContext.get().getTenantId();
        Integer sysType = AuthUserContext.get().getSysType();
        SupplierApiDetailVO supplierApiDetailVO = supplierDetailService.getBySupplierId(supplierId);
        if (Objects.isNull(supplierApiDetailVO)) {
            throw new LuckException("供应商不存在");
        }
        SupplierStatusInfoVO supplierStatusInfoVO = new SupplierStatusInfoVO();
        supplierStatusInfoVO.setSupplierStatus(supplierApiDetailVO.getSupplierStatus());
        supplierStatusInfoVO.setContractStartTime(supplierApiDetailVO.getContractStartTime());
        supplierStatusInfoVO.setContractEndTime(supplierApiDetailVO.getContractEndTime());
        if (Objects.equals(supplierApiDetailVO.getSupplierStatus(), SupplierStatus.OFFLINE.value())) {
            ServerResponseEntity<OfflineHandleEventVO> offlineHandleEventRes = offlineHandleEventFeignClient.getProcessingEventByHandleTypeAndHandleId(OfflineHandleEventType.SHOP.getValue(), supplierId, sysType);
            if (!offlineHandleEventRes.isSuccess()) {
                throw new LuckException(offlineHandleEventRes.getMsg());
            }
            OfflineHandleEventVO offlineHandleEventVO = offlineHandleEventRes.getData();
            if (Objects.nonNull(offlineHandleEventVO)) {
                supplierStatusInfoVO.setOfflineStatus(offlineHandleEventVO.getStatus());
                supplierStatusInfoVO.setOfflineReason(offlineHandleEventVO.getOfflineReason());
            } else if (supplierAllinpayService.getIsAllinpay()) {
                supplierStatusInfoVO.setOfflineReason("平台开启通联支付，请重新提交工商信息与财务信息");
            }
        }
        return ServerResponseEntity.success(supplierStatusInfoVO);
    }

    @PostMapping("/create_allinpay_member")
    @Operation(summary = "给还没有创建通联账户的供应商创建一个", description = "给还没有创建通联账户的供应商创建一个")
    public ServerResponseEntity<Void> createAllinpayMemberBySupplierId() {
        supplierDetailService.createAllinpayMemberBySupplierId(AuthUserContext.get().getTenantId());
        supplierDetailService.removeCacheBySupplierId(AuthUserContext.get().getTenantId());
        return ServerResponseEntity.success();
    }

    @PostMapping("/auditApply")
    @Operation(summary = "供应商重新申请上线", description = "供应商重新申请上线")
    public ServerResponseEntity<Void> auditApply(@RequestBody OfflineHandleEventDTO offlineHandleEventDTO) {
        Long supplierId = AuthUserContext.get().getTenantId();
        offlineHandleEventDTO.setHandleId(supplierId);
        supplierDetailService.auditApply(offlineHandleEventDTO);
        return ServerResponseEntity.success();
    }

    /**
     * 处理供应商信息，这些信息供应商无法直接修改
     *
     * @param supplierDetailDTO
     */
    private void dealWithUpdateOrCreateInfo(SupplierDetailDTO supplierDetailDTO) {
        if (Objects.isNull(supplierDetailDTO)) {
            return;
        }
        supplierDetailDTO.setContractEndTime(null);
        supplierDetailDTO.setContractStartTime(null);
        supplierDetailDTO.setSupplierStatus(null);
    }
}
