package com.jeequan.jeepay.mgr.ctrl.qrcode;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.zxing.WriterException;
import com.jeequan.jeepay.bizcommons.manage.qrshell.AbstractGenerator;
import com.jeequan.jeepay.bizcommons.manage.qrshell.ShellQRGenerator;
import com.jeequan.jeepay.components.oss.ctrl.OssFileController;
import com.jeequan.jeepay.components.oss.model.MockMultipartFile;
import com.jeequan.jeepay.components.oss.model.OssFileConfig;
import com.jeequan.jeepay.core.aop.MethodLog;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.core.model.QRCodeParams;
import com.jeequan.jeepay.core.utils.SpringBeansUtil;
import com.jeequan.jeepay.db.entity.MchApplyment;
import com.jeequan.jeepay.db.entity.MchQrcShell;
import com.jeequan.jeepay.db.entity.MchQrcodeCard;
import com.jeequan.jeepay.db.entity.MchStore;
import com.jeequan.jeepay.mgr.ctrl.CommonCtrl;
import com.jeequan.jeepay.service.impl.MchApplymentService;
import com.jeequan.jeepay.service.impl.MchQrcShellService;
import com.jeequan.jeepay.service.impl.MchQrcodeCardService;
import com.jeequan.jeepay.service.impl.SysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;


/**
 * 二维码模板管理
 *
 * @author terrfly
 *
 * @date 2022/1/17 14:22
 */
@RestController
@RequestMapping("/api/mchQrcShells")
public class MchQrcShellController extends CommonCtrl {

    @Autowired private MchQrcodeCardService mchQrcodeCardService;
    @Autowired private MchQrcShellService mchQrcShellService;
    @Autowired private SysConfigService sysConfigService;
    @Autowired private OssFileController ossFileController;
    @Autowired private MchApplymentService mchApplymentService;

    @GetMapping
    public ApiRes list() {

        // 构造查询条件
        MchQrcShell mchQrCode = getObject(MchQrcShell.class);
        mchQrCode.setSysType(CS.SYS_ROLE_TYPE.PLATFORM);

        LambdaQueryWrapper<MchQrcShell> lambdaQueryWrapper = MchQrcShell.gw();
        lambdaQueryWrapper.eq(MchQrcShell::getSysType, CS.SYS_ROLE_TYPE.PLATFORM);

        IPage<MchQrcShell> records = mchQrcShellService.page(getIPage(true), lambdaQueryWrapper);
        return ApiRes.ok(records);
    }

    @MethodLog(remark = "新建模板")
    @PostMapping
    public ApiRes add() throws IOException, WriterException {

        MchQrcShell record = getObject(MchQrcShell.class);
        record.setSysType(CS.SYS_ROLE_TYPE.PLATFORM);
        record.setBelongInfoId("0");
        MchQrcShell qrcShell = mchQrcShellService.getDefaultTemplate(CS.SYS_ROLE_TYPE.PLATFORM);
        qrcShell.setIsDefault(qrcShell == null ? CS.YES : CS.NO);
        // 示例图片
        InputStream inputStreamByView = AbstractGenerator.convertInputStream(getAbstractGenerator(record.getStyleCode()).genQrImgBuffer(record.getConfigInfo(), "示例",  18888L, "示例门店名称", true));
        String viewUrl = ossFileController.singleFileUpload(new MockMultipartFile(UUID.fastUUID() + ".png", 1L, inputStreamByView), OssFileConfig.BIZ_TYPE.QRC);
        record.setShellImgViewUrl(viewUrl); //预览图
        mchQrcShellService.save(record);
        return ApiRes.ok();
    }

    @GetMapping("/{recordId}")
    public ApiRes detail(@PathVariable("recordId") Long recordId) {
        return ApiRes.ok(mchQrcShellService.getById(recordId));
    }

    @MethodLog(remark = "更新模板信息")
    @PutMapping("/{recordId}")
    public ApiRes update(@PathVariable("recordId") Long recordId) throws IOException, WriterException {

        MchQrcShell record = getObject(MchQrcShell.class);

        MchQrcShell dbRecord = mchQrcShellService.getById(recordId);

        // 发生了变化
        if(!dbRecord.getConfigInfo().equals(record.getConfigInfo())){

            // 示例图片
            InputStream inputStreamByBiew = AbstractGenerator.convertInputStream(getAbstractGenerator(dbRecord.getStyleCode()).genQrImgBuffer(record.getConfigInfo(), "示例", 188L, "示例门店名称",true));
            String viewUrl = ossFileController.singleFileUpload(new MockMultipartFile(UUID.fastUUID() + ".png", 1L, inputStreamByBiew), OssFileConfig.BIZ_TYPE.QRC);

            record.setShellImgViewUrl(viewUrl); //预览图
        }

        record.setSid(recordId);
        record.setStyleCode(null); //类型不允许修改
        mchQrcShellService.updateById(record);
        return ApiRes.ok();
    }

    @MethodLog(remark = "删除二维码")
    @DeleteMapping("/{recordId}")
    public ApiRes delete(@PathVariable("recordId") Long recordId) {

        mchQrcShellService.removeById(recordId);
        return ApiRes.ok();
    }




    /** 预览二维码 **/
    @PostMapping("/view")
    public ApiRes view() throws Exception {

        String configModelStr = getValStringRequired("configModelStr");
        AbstractGenerator generator = getAbstractGenerator(getValStringRequired("styleCode"));

        Long viewQrId = 220101000001L;
        BufferedImage bufferedImage = generator.genQrImgBuffer(configModelStr, "示例", viewQrId, "示例门店名称",true);

        //给前端拼接上 【 data:image/jpg;base64 】
        return ApiRes.ok("data:image/jpg;base64,"+ AbstractGenerator.convertImgBase64(bufferedImage));
    }


    /** 根据qrcId获取图片base64 **/
    @GetMapping("/viewByQrc/{qrcId}")
    public ApiRes viewByQrc(@PathVariable("qrcId") Long qrcId) throws Exception {

        MchQrcodeCard dbRecord = mchQrcodeCardService.getById(qrcId);

        String mchStoreName = "";
        if(dbRecord.getBindState() == CS.YES && dbRecord.getStoreId() != null && !"-1".equals(dbRecord.getStoreId())){
            MchStore mchStore = mchStoreService.getById(dbRecord.getStoreId());
            mchStoreName = mchStore != null ? mchStore.getStoreName() : "";
        }
        MchApplyment applyment = mchApplymentService.getById(dbRecord.getMchApplyId());

        // 封装URL
        String qrUrlContent = sysConfigService.getDBApplicationConfig().genUniJsapiPayUrl(QRCodeParams.TYPE_QRC, dbRecord.getEntryPage(), qrcId + "", applyment.getIsvNo());

        if(dbRecord.getQrcShellId() == null || dbRecord.getQrcShellId() <= 0){
            //给前端拼接上 【 data:image/jpg;base64 】
            AbstractGenerator shellQRGenerator = SpringBeansUtil.getBean(ShellQRGenerator.class);
            return ApiRes.ok("data:image/jpg;base64,"+ AbstractGenerator.convertImgBase64(shellQRGenerator.genQrImgBuffer(null, qrUrlContent, qrcId, mchStoreName, false)));
        }

        MchQrcShell mchQrcShell = mchQrcShellService.getById(dbRecord.getQrcShellId());

        AbstractGenerator generator = getAbstractGenerator(mchQrcShell.getStyleCode());
        BufferedImage bufferedImage = generator.genQrImgBuffer(mchQrcShell.getConfigInfo(), qrUrlContent, qrcId, mchStoreName, false);

        //给前端拼接上 【 data:image/jpg;base64 】
        return ApiRes.ok("data:image/jpg;base64,"+ AbstractGenerator.convertImgBase64(bufferedImage));
    }


    private AbstractGenerator getAbstractGenerator(String code){

        AbstractGenerator generator = SpringBeansUtil.getBean(code + "Generator", AbstractGenerator.class);
        if(generator == null){
            throw new BizException("选择模板[" + code + "]不存在！");
        }
        return generator;
    }


}
