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

import com.tmerclub.cloud.api.payment.feign.AllinpayFeignClient;
import com.tmerclub.cloud.api.supplier.vo.SupplierApiDetailVO;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.constant.IdCardCollectProcessStatus;
import com.tmerclub.cloud.common.constant.StatusEnum;
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.common.util.BeanUtil;
import com.tmerclub.cloud.supplier.constant.AuditStatus;
import com.tmerclub.cloud.supplier.dto.SupplierCompanyDTO;
import com.tmerclub.cloud.supplier.mapper.SupplierDetailMapper;
import com.tmerclub.cloud.supplier.model.SupplierCompany;
import com.tmerclub.cloud.supplier.service.SupplierAllinpayService;
import com.tmerclub.cloud.supplier.service.SupplierCompanyService;
import com.tmerclub.cloud.supplier.service.SupplierDetailService;
import com.tmerclub.cloud.supplier.vo.SupplierCompanyVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
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
 * @Date 2021/4/25 16:31
 */
@RestController
@RequestMapping("/s/apply_supplier/supplier_company")
@Tag(name = "supplier-供应商工商信息")
public class SupplierCompanyController {

    @Autowired
    private SupplierCompanyService supplierCompanyService;
    @Autowired
    private SupplierAllinpayService supplierAllinpayService;
    @Autowired
    private SupplierDetailService supplierDetailService;
    @Autowired
    private SupplierDetailMapper supplierDetailMapper;
    @DubboReference
    private AllinpayFeignClient allinpayFeignClient;

    @PostMapping
    @Operation(summary = "新增供应商工商信息", description = "新增供应商工商信息")
    public ServerResponseEntity<Void> save(@Valid @RequestBody SupplierCompanyDTO supplierCompanyDTO) {
        Long supplierId = this.getSupplierId();
        checkAllinpay(supplierCompanyDTO);
        SupplierCompany supplierCompany = BeanUtil.map(supplierCompanyDTO, SupplierCompany.class);
        supplierCompany.setSupplierId(supplierId);
        supplierCompany.setStatus(AuditStatus.WAITAUDIT.value());
        supplierCompanyService.save(supplierCompany, true);
        return ServerResponseEntity.success();
    }

    @PutMapping
    @Operation(summary = "供应商更新工商信息,仅在申请开店时调用", description = "供应商更新工商信息")
    public ServerResponseEntity<Void> update(@Valid @RequestBody SupplierCompanyDTO supplierCompanyDTO) {
        checkAllinpay(supplierCompanyDTO);
        SupplierCompany supplierCompany = BeanUtil.map(supplierCompanyDTO, SupplierCompany.class);
        supplierCompany.setStatus(AuditStatus.WAITAUDIT.value());
        supplierCompanyService.checkInfo(supplierCompany, false, null);
        supplierCompanyService.update(supplierCompany);
        return ServerResponseEntity.success();
    }

    @PostMapping("/storage")
    @Operation(summary = "存储供应商工商信息", description = "存储供应商工商信息,已存在则更新，不存在则新增")
    public ServerResponseEntity<Void> storage(@Valid @RequestBody SupplierCompanyDTO supplierCompanyDTO) {
        Long supplierId = this.getSupplierId();
        checkAllinpay(supplierCompanyDTO);
        SupplierCompanyVO supplierCompanyVO = supplierCompanyService.getSupplierCompanyBySupplierIdAndStatus(supplierId, AuditStatus.WAITAUDIT.value());
        SupplierCompany supplierCompany = BeanUtil.map(supplierCompanyDTO, SupplierCompany.class);
        supplierCompany.setSupplierId(supplierId);
        supplierCompany.setStatus(AuditStatus.WAITAUDIT.value());
        if (Objects.isNull(supplierCompanyVO)) {
            // 不存在，新增
            supplierCompanyService.save(supplierCompany, true);
        } else {
            // 已存在，更新
            supplierCompany.setSupplierCompanyId(supplierCompanyVO.getSupplierCompanyId());
            supplierCompanyService.checkInfo(supplierCompany, false, null);
            supplierCompanyService.update(supplierCompany);
        }
        return ServerResponseEntity.success();
    }

    @GetMapping
    @Operation(summary = "获取供应商工商信息")
    @Parameter(name = "status", description = "审核状态：1：已通过 0待审核 -1未通过")
    public ServerResponseEntity<SupplierCompanyVO> getSupplierCompanyBySupplierId(@RequestParam(value = "status", required = false, defaultValue = "1") Integer status) {
        Long supplierId = this.getSupplierId();
        Integer isPassShop = AuthUserContext.get().getIsPassShop();
        if (Objects.equals(isPassShop, StatusEnum.DISABLE.value())) {
            status = AuditStatus.WAITAUDIT.value();
        }
        if (supplierAllinpayService.getIsAllinpay()) {
            // 影印件还没通过审核
            SupplierApiDetailVO supplierApiDetailVO = supplierDetailService.getBySupplierId(supplierId);
            if (!Objects.equals(supplierApiDetailVO.getIdCardCollectProcessStatus(), IdCardCollectProcessStatus.ALL.value())) {
                status = AuditStatus.WAITAUDIT.value();
            }
        }
        return ServerResponseEntity.success(supplierCompanyService.getSupplierCompanyBySupplierIdAndStatus(supplierId, status));
    }

    @PutMapping("/updateAcctProtocolNo")
    @Operation(summary = "更新供应商账户协议编号")
    @Parameters({
            @Parameter(name = "signAcctType", description = "签约类型 1.个人 2.法人 3.企业"),
            @Parameter(name = "acctProtocolNo", description = "账户提现协议编号")
    })
    public ServerResponseEntity<Void> updateAcctProtocolNo(@RequestParam("signAcctType") Integer signAcctType,
                                                           @RequestParam("acctProtocolNo") String acctProtocolNo) {
        Long supplier = this.getSupplierId();
        // 企业会员-“企业名称”“法人姓名”变更后，需重新签约。
        supplierDetailMapper.updateAcctProtocolNoByType(supplier, signAcctType, acctProtocolNo);
        supplierDetailService.removeCacheBySupplierId(supplier);
        return ServerResponseEntity.success();
    }


    private Long getSupplierId() {
        Long supplierId = AuthUserContext.get().getTenantId();
        if (Objects.equals(supplierId, Constant.DEFAULT_SUPPLIER_ID)) {
            throw new LuckException("供应商不存在");
        }
        return supplierId;
    }

    private void checkAllinpay(SupplierCompanyDTO supplierCompanyDTO) {
        boolean needInfo = Objects.isNull(supplierCompanyDTO.getLegalIds()) || Objects.isNull(supplierCompanyDTO.getLegalPhone());
        if (supplierAllinpayService.getIsAllinpay() && needInfo) {
            throw new LuckException("开店所需要提交的信息有所变更，请重新填写");
        }
    }

}
