package cn.pluss.platform.controller;

import cn.pluss.platform.annotation.OpLog;
import cn.pluss.platform.api.PageInfo;
import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.baidu.BaiduFaceDetectService;
import cn.pluss.platform.constants.ProjectConstant;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.merchant.MerchantBaseInfoService;
import cn.pluss.platform.merchantBankCard.MerchantBankCardService;
import cn.pluss.platform.systemConfig.SystemConfigService;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.util.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequiredArgsConstructor
@RequestMapping("/systemConfig")
@Transactional
@Slf4j
@Api(value = "SystemConfig控制类", tags = {"系统参数接口"})
public class SystemConfigController {

    private final SystemConfigService systemConfigService;
    private final UserAppService userAppService;
    private final MerchantBaseInfoService merchantBaseInfoService;
    private final MerchantBankCardService merchantBankCardService;

    @Autowired
    private BaiduFaceDetectService baiduFaceDetectService;

    @GetMapping
    @ApiOperation(value = "获取全部", notes = "返回分页过后的数据", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "查询页码", paramType = "query", dataType = "Integer", defaultValue = "0"),
            @ApiImplicitParam(name = "size", value = "每页数据量", paramType = "query", dataType = "Integer", defaultValue = "0")
    })
    public Result<PageInfo<SystemConfig>> list(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "1") Integer size) {
        if (size == null || size == 0) {
            size = ProjectConstant.PAGE_SIZE;
        }
        if (page == null || page == 0) {
            page = 1;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("pageSize", size);
        map.put("offset", (page - 1) * size);
        List<SystemConfig> systemconfigList = systemConfigService.querySystemConfigPage(map);
        Integer count = systemConfigService.querySystemConfigPageCount(map);
        //返回参数
        PageInfo pager = new PageInfo<>(count.longValue(), (long) StringUtil.getPageCount(count, size), page.longValue(), size.longValue(), systemconfigList);
        return ResultGenerator.genSuccessResult(pager);
    }

    /**
     * 版本跟新接口
     *
     * @param platformCode 0： android; 1 :  iOS
     * @return
     */
    @PostMapping("/updateSystemVersion")
    @ApiOperation(value = "版本更新", notes = "传来版本返回下载地址和系统版本", httpMethod = "POST")
    public Result<Object> updateSystemVersion(@RequestParam(defaultValue = "-1") int platformCode) {
        Object result = systemConfigService.updateSystemVersion(platformCode);
        return ResultGenerator.genSuccessResult(result);
    }

    @PostMapping("/queryMerchantFeeImgUrl")
    public Result queryMerchantFeeImgUrl() {
        Map<String, Object> result = new HashMap<String, Object>(16);
        boolean flag = false;
        try {
            String merchantType = "1";
            String accountType = "1";
            UserApp userApp = userAppService.queryUserAppByToken();
            String myLimit = "";
            String brushBank = "";
            String merchantCode = userApp.getMerchantCode();
            if (StringUtil.isNotEmpty(merchantCode)) {
                MerchantBaseInfo merchantBaseInfo = new MerchantBaseInfo();
                merchantBaseInfo.setMerchantCode(merchantCode);
                merchantBaseInfo = merchantBaseInfoService.queryMerchantBaseInfo(merchantBaseInfo);
                if (null != merchantBaseInfo) {
                    merchantType = merchantBaseInfo.getMerchantType() == null ? "1" : merchantBaseInfo.getMerchantType();
                }
                MerchantBankCard merchantBankCard;
                merchantBankCard = merchantBankCardService.queryMerchantBankCard(userApp.getUserId() + "");
                if (null != merchantBankCard) {
                    accountType = merchantBankCard.getAccountType() == null ? "1" : merchantBankCard.getAccountType();
                }
            }

            String levelImg = systemConfigService.querySystemConfigValue("levelImg");

            flag = true;
            result.put("flag", flag);
            result.put("myLimit", levelImg);
            result.put("brushBank", levelImg);
            result.put("levelImg", levelImg);

            return ResultGenerator.genSuccessResult(result);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("flag", flag);
            return ResultGenerator.genFailResult(result);
        }

    }

    @PostMapping("/isLogin")
    @ApiOperation(value = "当前版本是否已经上架到appStore", notes = "1, 没有；2，已经上架", httpMethod = "POST", consumes = "application/json", produces = "application/json")
    @ApiOperationSupport(params = @DynamicParameters(properties = {
            @DynamicParameter(name = "version", value = "当前app版本号", example = "1.0.9.beta", required = true, dataTypeClass = String.class)
    }))
    public Result isLogin(HttpServletRequest request) throws IOException {
        InputStream is = request.getInputStream();
        StringBuilder responseStrBuilder = new StringBuilder();
        BufferedReader streamReader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
        String inputStr;
        while ((inputStr = streamReader.readLine()) != null) {
            responseStrBuilder.append(inputStr);
        }

        if (responseStrBuilder.length() == 0) {
            return ResultGenerator.genSuccessResult("1");
        }

        Object o = systemConfigService.updateSystemVersion(1);

        if(o instanceof AppVersionInfo) {
            JSONObject json = JSON.parseObject(responseStrBuilder.toString());
            String version = json.getString("version");

            String versionName = ((AppVersionInfo) o).getVersionName();

            if (StringUtil.isEmpty(version) || StringUtil.isEmpty(versionName) || versionName.compareTo(version) < 0) {
                return ResultGenerator.genSuccessResult("1");
            } else {
                return ResultGenerator.genSuccessResult("2");
            }
        } else {
            return ResultGenerator.genSuccessResult("1");
        }
    }

    @GetMapping("/getLeshuaUploadParam")
    public Result<Map<String, Object>> getLeshuaUploadUrl(String fileMD5) {
//        Map<String, Object> result = new HashMap<>();
//        result.put("url", ParametersUtil.LESHUA_API + "/picture/upload");
//        result.put("agentId", "7389852");
//        result.put("version", "2.0");
//
//        JSONObject object = new JSONObject();
//        object.put("data")
//
//        getSign()
//
//        return ResultGenerator.genSuccessResult(ParametersUtil.LESHUA_API + "/picture/upload");

        return ResultGenerator.genFailResult("非法接口");
    }

    /**
     * 进件获取签名值
     *
     * @param data
     * @return
     */
    private String getSign(JSONObject data) {
        String sign = "";
        String jsonData = data.toJSONString();
        StringBuffer sb = new StringBuffer("lepos");
        sb.append("60E3F31EDEC8061C33721737B36FA86D").append(jsonData);// key每个渠道商不一样
        String md5 = DigestUtils.md5Hex(sb.toString().getBytes(StandardCharsets.UTF_8));
        sign = Base64.encodeBase64String(md5.getBytes(StandardCharsets.UTF_8));
        log.info("待签参数:{}" + sb);
        log.info("签名值:{}" + sign);
        return sign;
    }


    @OpLog(opCode = "BAIDU_ACCESS_TOKEN", opDetail = "获取百度访问token", opName = "获取百度访问token")
    @GetMapping("/baiduAccessToken")
    public Result<?> getBaiduAccessToken() {
        final String auth = baiduFaceDetectService.apiGetAuth();
        return ResultGenerator.genSuccessResult(auth);
    }
}
