package com.ym.mec.web.controller;

import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.dto.TenantInfoDto;
import com.ym.mec.biz.dal.entity.TenantContractRecord;
import com.ym.mec.biz.dal.entity.TenantInfo;
import com.ym.mec.biz.dal.entity.TenantProductSumm;
import com.ym.mec.biz.service.TenantInfoSendMsgService;
import com.ym.mec.biz.service.TenantInfoService;
import com.ym.mec.biz.service.TenantOrderRecordService;
import com.ym.mec.common.controller.BaseController;
import com.ym.mec.common.entity.HttpResponseResult;
import com.ym.mec.common.page.WrapperUtil;
import com.ym.mec.common.tenant.TenantContextHolder;
import com.ym.mec.util.validator.ValidationKit;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

import static com.ym.mec.biz.service.impl.TenantInfoSendMsgServiceImpl.OPEN;

/**
 * @author hgw
 * Created by 2021-12-07
 */
@RequestMapping("tenantInfo")
@Api(tags = "机构管理")
@RestController
public class TenantInfoController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(TenantInfoController.class);

    @Autowired
    private TenantInfoService tenantInfoService;

    @Autowired
    private SysUserFeignService sysUserFeignService;

    @Autowired
    private TenantInfoSendMsgService tenantInfoSendMsgService;

    @Resource
    private TenantOrderRecordService tenantOrderRecordService;

    @ApiOperation("添加机构信息")
    @PostMapping(value = "/add")
    @PreAuthorize("@pcs.hasPermissions('tenantInfo/add')")
    public Object addTenantInfo(@Valid @RequestBody TenantInfoDto dto) {
        tenantInfoService.addTenantInfo(dto);
        return succeed();
    }

    @ApiOperation("修改机构信息")
    @PostMapping(value = "/update")
    @PreAuthorize("@pcs.hasPermissions('tenantInfo/update')")
    public Object updateTenantInfo(@Valid @RequestBody TenantInfoDto dto, BindingResult bindingResult) {
        ValidationKit.ignoreFields(bindingResult, "productInfo", "config");
        tenantInfoService.updateTenantInfo(dto);
        return succeed();
    }

    @ApiOperation("修改机构启用停用状态")
    @GetMapping(value = "/opsState/{id}")
    @PreAuthorize("@pcs.hasPermissions('tenantInfo/opsState')")
    public Object opsState(@ApiParam(value = "机构ID", required = true) @PathVariable("id") Integer id, Integer state) {
        Map<String, Object> openPar = tenantInfoService.opsTenantState(id, state);
        //有返回密码(第一次开通机构会生成登录密码并返回)就发送邮件及短信提醒
        String pw = WrapperUtil.toStr(openPar, "pw");
        TenantInfo tenantInfo = (TenantInfo) openPar.get("tenantInfo");
        if (StringUtils.isNotBlank(pw) && Objects.nonNull(tenantInfo)) {
            Object[] msg = {tenantInfo.getName(), tenantInfo.getPhone(), pw, "https://online.dayaedu.com"};
            tenantInfoSendMsgService.platformSendToAll(OPEN, tenantInfo.getUserId(), tenantInfo.getEmail(), tenantInfo.getPhone(), msg);
        }
        return succeed();
    }

    @ApiOperation("查询单个机构详情")
    @GetMapping(value = "/info/{id}")
    public Object queryTenantInfo(@ApiParam(value = "机构ID", required = true) @PathVariable("id") Integer id) {
        return succeed(tenantInfoService.queryTenantInfo(id));
    }

    @ApiOperation("查询单个机构详情")
    @GetMapping(value = "/checkInfo/{id}")
    public Object queryTenantInfoCheck(@ApiParam(value = "机构ID", required = true) @PathVariable("id") Integer id) {
        return succeed(tenantInfoService.queryTenantInfoCheck(id));
    }

    @ApiOperation("查询机构产品")
    @GetMapping(value = "/queryTenantInfoSumm")
    public HttpResponseResult<TenantProductSumm> queryTenantInfoProductSumm() {
        Integer tenantId = TenantContextHolder.getTenantId();
        return succeed(tenantInfoService.queryTenantInfoProductSumm(tenantId));
    }

    @ApiOperation("查询用户机构信息")
    @GetMapping(value = "/queryUserTenantInfo")
    public Object queryUserTenantInfo() {
        SysUser user = sysUserFeignService.queryUserInfo();
        if (user == null || user.getId() == null) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        return succeed(tenantInfoService.queryTenantInfo(user.getTenantId()));
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "search", dataType = "String", value = "关键字"),
            @ApiImplicitParam(name = "createdName", dataType = "String", value = "创建人"),
            @ApiImplicitParam(name = "payState", dataType = "Integer", value = "支付状态 缴费状态 0未缴费  1已缴费"),
            @ApiImplicitParam(name = "state", dataType = "Integer", value = "机构状态 1启动 2停用"),
            @ApiImplicitParam(name = "startDate", dataType = "String", value = "开始时间"),
            @ApiImplicitParam(name = "endDate", dataType = "String", value = "结束时间"),
            @ApiImplicitParam(name = "page", dataType = "Integer", value = "页数"),
            @ApiImplicitParam(name = "rows", dataType = "Integer", value = "每页数量"),
    })
    @ApiOperation("分页查询")
    @PostMapping(value = "/queryPage")
    @PreAuthorize("@pcs.hasPermissions('tenantInfo/queryPage')")
    public Object queryPage(@RequestBody Map<String, Object> param) {
        return succeed(tenantInfoService.queryPage(param));
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", dataType = "Integer", value = "机构id"),
            @ApiImplicitParam(name = "type", dataType = "Integer", value = "0开通 1续费"),
            @ApiImplicitParam(name = "renewCount", dataType = "Integer", value = "若是续费，则需要传入续费时长"),
    })
    @ApiOperation("获取机构付款及续费时需要预览的协议")
    @GetMapping(value = "/getContract/{id}")
    public Object getContract(@PathVariable("id") Integer id, Integer type, Integer renewCount) {
        TenantContractRecord.TenantContractRecordEnum en = Optional.ofNullable(type)
                .filter(t -> TenantContractRecord.TenantContractRecordEnum.RENEW.getType().equals(t))
                .map(t -> TenantContractRecord.TenantContractRecordEnum.RENEW)
                .orElse(TenantContractRecord.TenantContractRecordEnum.OPEN);
        return succeed(tenantInfoService.getContract(id, en, renewCount));
    }

    @ApiOperation("机构支付")
    @GetMapping(value = "/pay/{id}")
    public Object pay(@ApiParam(value = "机构ID", required = true) @PathVariable("id") Integer id) throws Exception {
        return succeed(tenantInfoService.tenantOpenPay(id));
    }

    @ApiOperation("机构续费")
    @GetMapping(value = "/renew/{id}")
    public Object tenantRenewPay(@ApiParam(value = "机构ID", required = true) @PathVariable("id") Integer id, Integer val) throws Exception {
        return succeed(tenantInfoService.tenantRenewPay(id, val));
    }

    @ApiOperation(value = "机构充值")
    @GetMapping("/recharge/{amount}")
    @PreAuthorize("@pcs.hasPermissions('tenantInfo/recharge')")
    public HttpResponseResult<Map<String, Object>> recharge(
            @ApiParam(value = "充值金额", required = true) @PathVariable("amount") Double amount
    ) throws Exception {
        Integer tenantId = TenantContextHolder.getTenantId();
        return succeed(tenantInfoService.recharge(tenantId, new BigDecimal(amount)));
    }

    @ApiOperation(value = "轮询查询订单状态")
    @GetMapping("/rechargeCheck/{orderNo}")
    @PreAuthorize("@pcs.hasPermissions('tenantInfo/rechargeCheck')")
    public HttpResponseResult<Boolean> rechargeCheck(
            @ApiParam(value = "订单号", required = true) @PathVariable("orderNo") String orderNo
    ) throws Exception {
        return succeed(tenantInfoService.rechargeCheck(orderNo));
    }

    @ApiOperation(value = "测试临期提醒")
    @GetMapping("/testCheck")
    public Object testCheck() {
        tenantInfoService.checkTenantState();
        return succeed();
    }

    @PostMapping("/callback")
    public String callback(HttpServletRequest request) {
        return tenantOrderRecordService.callback(request);
    }

}
