package com.yonge.cooleshow.admin.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.microsvc.toolkit.common.response.paging.PageInfo;
import com.microsvc.toolkit.common.response.paging.QueryInfo;
import com.microsvc.toolkit.common.response.template.R;
import com.microsvc.toolkit.middleware.payment.common.api.BasePaymentService;
import com.microsvc.toolkit.middleware.payment.common.api.PaymentServiceContext;
import com.microsvc.toolkit.middleware.payment.common.api.entity.PaymentMerchant;
import com.yonge.cooleshow.biz.dal.entity.TenantMember;
import com.yonge.cooleshow.biz.dal.service.TenantMemberService;
import com.yonge.cooleshow.biz.dal.wrapper.TenantMemberWrapper;
import com.yonge.cooleshow.common.controller.BaseController;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.cooleshow.common.enums.EPayerType;
import com.yonge.toolset.base.exception.BizException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;


/**
 * @Author：haonan
 * @Date：2023/8/10 13:40
 * @Filename：TenantMemberController
 */
@Slf4j
@Validated
@RestController
@RequestMapping("${app-config.url.admin:}/tenantMember")
@Api(tags = "机构子账户表")
public class TenantMemberController extends BaseController {

    @Autowired
    private TenantMemberService tenantMemberService;

    @Autowired
    private PaymentServiceContext paymentServiceContext;
    @ApiOperation(value = "详情", notes = "机构子账户表-根据详情ID查询单条, 传入id")
    @PreAuthorize("@pcs.hasPermissions('tenantMember/detail', {'BACKEND'})")
    @PostMapping("/detail/{id}")
    public R<TenantMember> detail(@PathVariable("id") Long id) {

        TenantMember wrapper = tenantMemberService.detail(id);

        return R.from(wrapper);
    }

    @ApiOperation(value = "查询分页", notes = "机构子账户表- 传入 TenantMemberWrapper.TenantMemberQuery")
    @PreAuthorize("@pcs.hasPermissions('tenantMember/page', {'BACKEND'})")
    @PostMapping("/page")
    public HttpResponseResult<PageInfo<TenantMemberWrapper.TenantMember>> page(@RequestBody TenantMemberWrapper.TenantMemberQuery query) {

        IPage<TenantMemberWrapper.TenantMember> pages = tenantMemberService.selectPage(QueryInfo.getPage(query), query);

        return succeed(QueryInfo.pageInfo(pages));
    }

    @ApiOperation(value = "新增", notes = "机构子账户表- 传入 TenantMemberWrapper.InsertTenantMember")
    @PreAuthorize("@pcs.hasPermissions('tenantMember/add', {'BACKEND'})")
    @PostMapping("/add")
    public HttpResponseResult add(@Valid  TenantMemberWrapper.InsertOrUpdateTenantMember tenantMember) throws IOException {

        if (tenantMember.getMultipartFile() != null) {
            File file = new File("/var/tmp/" + tenantMember.getMultipartFile().getOriginalFilename());
            tenantMember.setFile(file);
            InputStream inputStream = tenantMember.getMultipartFile().getInputStream();

            try {
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                FileOutputStream fos = new FileOutputStream(file);
                IOUtils.copy(inputStream, fos);
                // 新增数据
                return HttpResponseResult.succeed(tenantMemberService.add(tenantMember));
            } catch (Exception e) {
                return failed(e.getMessage());
            } finally {
                IOUtils.closeQuietly(inputStream);
                FileUtils.deleteQuietly(file);
            }
        }

        // 新增数据
        return HttpResponseResult.succeed(tenantMemberService.add(tenantMember));
    }

    @ApiOperation(value = "修改", notes = "机构子账户表- 传入 TenantMemberWrapper.InsertTenantMember")
    @PreAuthorize("@pcs.hasPermissions('tenantMember/update', {'BACKEND'})")
    @PostMapping("/update")
    public HttpResponseResult update( TenantMemberWrapper.InsertOrUpdateTenantMember tenantMember) throws IOException {
        if (tenantMember.getMultipartFile() != null) {
            File file = new File("/var/tmp/" + tenantMember.getMultipartFile().getOriginalFilename());
            tenantMember.setFile(file);
            InputStream inputStream = tenantMember.getMultipartFile().getInputStream();

            try {
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                FileOutputStream fos = new FileOutputStream(file);
                IOUtils.copy(inputStream, fos);
                // 新增数据
                return HttpResponseResult.succeed(tenantMemberService.update(tenantMember));
            } catch (Exception e) {
                return failed(e.getMessage());
            } finally {
                IOUtils.closeQuietly(inputStream);
                FileUtils.deleteQuietly(file);
            }
        }

        // 新增数据
        return HttpResponseResult.succeed(tenantMemberService.update(tenantMember));
    }


    @ApiOperation(value = "修改结算账户", notes = "机构子账户表- 传入 TenantMemberWrapper.UpdateCount")
    @PreAuthorize("@pcs.hasPermissions('tenantMember/updateCount', {'BACKEND'})")
    @PostMapping("/updateCount")
    public HttpResponseResult updateCount(@RequestBody TenantMemberWrapper.UpdateCount tenantMember) {

        // 更新数据
        return HttpResponseResult.succeed(tenantMemberService.updateCount(tenantMember));
    }


    @ApiOperation(value = "删除", notes = "机构子账户表- 传入id")
    @PreAuthorize("@pcs.hasPermissions('tenantMember/remove', {'BACKEND'})")
    @PostMapping("/remove")
    public R<Boolean> remove(@RequestParam Long id) {

        return R.from(tenantMemberService.removeById(id));
    }


    @ApiOperation(value = "查询三方企业账户", notes = "机构子账户表-根据详情ID查询单条, 传入id")
    @PreAuthorize("@pcs.hasPermissions('tenantMember/detail', {'BACKEND'})")
    @PostMapping("/remoteDetail/{id}")
    public R<PaymentMerchant.MerchantMember> remoteDetail(@PathVariable("id") Long id) {

        PaymentMerchant.MerchantMember merchantMember = tenantMemberService.remoteDetail(id);

        return R.from(merchantMember);
    }


    @ApiOperation("修改企业用户(状态是failed才能修改)")
    @PostMapping(value = "upload")
    @PreAuthorize("@pcs.hasPermissions('tenantMember/upload')")
    public HttpResponseResult<String> upload(MultipartFile multipartFile) throws Exception {


        File file = new File("/var/tmp/" + multipartFile.getOriginalFilename());
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        FileOutputStream fos = new FileOutputStream(file);
        InputStream inputStream = multipartFile.getInputStream();

        try {
            IOUtils.copy(inputStream, fos);
            inputStream.close();
            fos.close();


            PaymentMerchant.MerchantConfig merchantConfig = tenantMemberService.getMerchantConfig(EPayerType.YEEPAY.getDesc());

            // 创建账户
            BasePaymentService paymentService = paymentServiceContext.getPaymentService(EPayerType.YEEPAY.getDesc());
            if (paymentService == null) {
                throw new BizException("支付渠道不存在");
            }

            return succeed(paymentService.upload(merchantConfig, file));
        } catch (Exception e) {
            return failed(e.getMessage());
        } finally {
            IOUtils.closeQuietly(fos);
            IOUtils.closeQuietly(inputStream);
            FileUtils.deleteQuietly(file);
        }

    }
}