package com.huiju.estateagents.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huiju.estateagents.base.BaseController;
import com.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.common.StringUtils;
import com.huiju.estateagents.common.WxUtils;
import com.huiju.estateagents.entity.TaMiniapp;
import com.huiju.estateagents.service.IMiniAppService;
import com.huiju.estateagents.service.ITaMiniappService;
import io.swagger.annotations.ApiOperation;
import org.apache.tomcat.jni.Mmap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * <p>
    * 小程序表  前端控制器
    * </p>
 *
 * @author jobob
 * @since 2019-09-11
 */
@RestController
@RequestMapping("/api")
public class TaMiniappController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(TaMiniappController.class);

    @Autowired
    public ITaMiniappService iTaMiniappService;

    @Autowired
    private IMiniAppService miniAppService;

    @Autowired
    WxUtils wxUtils;

    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value="/center/taMiniapp",method= RequestMethod.GET)
    public ResponseBean taMiniappList(@RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
									 @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize){
        ResponseBean responseBean = new ResponseBean();
        try {
            //使用分页插件
		    IPage<TaMiniapp> pg = new Page<>(pageNum, pageSize);
            QueryWrapper<TaMiniapp> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByDesc("create_date");

            IPage<TaMiniapp> result = iTaMiniappService.page(pg, queryWrapper);
            responseBean.addSuccess(result);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taMiniappList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 保存对象
     * @param taMiniapp 实体对象
     * @return
     */
    @RequestMapping(value="/center/taMiniapp",method= RequestMethod.POST)
    public ResponseBean taMiniappAdd(@RequestBody TaMiniapp taMiniapp, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        Integer channelId = getChannelId(request);
        try {
            iTaMiniappService.saveInfoWithTpls(taMiniapp, channelId);
            responseBean.addSuccess(taMiniapp);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taMiniappAdd -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     */
    @ResponseBody
    @RequestMapping(value="/taMiniapp/{id}", method= RequestMethod.DELETE)
    public ResponseBean taMiniappDelete(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            if(iTaMiniappService.removeById(id)){
                responseBean.addSuccess("success");
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taMiniappDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 修改对象
     * @param id  实体ID
     * @param taMiniapp 实体对象
     * @return
     */
    @RequestMapping(value="/center/taMiniapp/{id}",method= RequestMethod.PUT)
    public ResponseBean taMiniappUpdate(@PathVariable String id,
                                        @RequestBody TaMiniapp taMiniapp){
        ResponseBean responseBean = new ResponseBean();
        try {
            taMiniapp.setMiniappId(id);
            if (iTaMiniappService.updateById(taMiniapp)){
                responseBean.addSuccess(taMiniapp);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taMiniappUpdate -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     * @param id  实体ID
     */
    @RequestMapping(value="/center/taMiniapp/{id}",method= RequestMethod.GET)
    public ResponseBean taMiniappGet(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean.addSuccess(iTaMiniappService.getById(id));
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taMiniappDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    @PostMapping(value = "center/check/taMiniapp")
    public ResponseBean createQRCode(@RequestBody String paramStr) {
        if (StringUtils.isEmpty(paramStr)) {
            return ResponseBean.error("参数不能为空", ResponseBean.ERROR_MISSING_PARAMS);
        }

        JSONObject params = JSONObject.parseObject(paramStr);
        if (null == params) {
            return ResponseBean.error("非法参数", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        String appid = params.getString("miniappId");
        String secret = params.getString("secret");
        String path = params.getString("path");

        if (StringUtils.isEmpty(appid) || StringUtils.isEmpty(secret) || StringUtils.isEmpty(path)) {
            return ResponseBean.error("缺失参数", ResponseBean.ERROR_MISSING_PARAMS);
        }

        TaMiniapp taMiniapp = null;
        WxMaService service = wxUtils.getMiniApp(appid);
        if (null != service) {
            taMiniapp = iTaMiniappService.getById(appid);
            if (null == taMiniapp) {
                return ResponseBean.error("异常, 请联系技术人员", ResponseBean.ERROR_UNAVAILABLE);
            }
        }

        if (null == service || !secret.equals(taMiniapp.getSecret())){
            service = wxUtils.newService(new TaMiniapp(){{
                setMiniappId(appid);
                setSecret(secret);
                setToken(params.getString("token"));
            }});
        }

        try {
            String qrCode = miniAppService.createQrCode(service, path);
            return ResponseBean.success(new HashMap<String, Object>(){{
                put("qrCode", qrCode);
            }});
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseBean.error("校验不通过", ResponseBean.ERROR_UNAVAILABLE);
        }
    }

    @ApiOperation(value = "获取小程序名称", notes = "获取小程序名称")
    @GetMapping(value = "/admin/getMiniappName")
    public ResponseBean getMiniappName(HttpServletRequest request){
        Integer orgId = getOrgId(request);
        QueryWrapper<TaMiniapp> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("org_id", orgId);
        TaMiniapp one = iTaMiniappService.getOne(queryWrapper);

        ResponseBean responseBean = new ResponseBean();
        responseBean.addSuccess((Object) one.getName());

        return responseBean;
    }
}
