package com.bohuikeji.delivery.backstage.controller.api.courier;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bohuikeji.delivery.backstage.entity.TCourier;
import com.bohuikeji.delivery.backstage.entity.TCourierCard;
import com.bohuikeji.delivery.backstage.service.ITCourierCardService;
import com.bohuikeji.delivery.backstage.service.ITCourierService;
import com.bohuikeji.frame.module.admin.base.ApiController;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.utils.BaiDuAiUtils;
import com.bohuikeji.frame.module.admin.utils.ImageUtil;
import com.bohuikeji.frame.module.admin.utils.JsonUtil;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jodd.http.HttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 绑定银行卡接口
 */
@Api(tags = {"派送员绑定银行卡接口"})
@RestController
@RequestMapping("/api/courier/card")
public class TCourierCardApi extends ApiController {
    @Autowired
    ITCourierCardService ITCourierCardService;
    @Autowired
    ITCourierService courierService;
    @PostMapping("save")
    @ApiOperation("保存或更新银行卡信息")
    public APIEntity save(@RequestBody TCourierCard tCourierCard){
        if(tCourierCard.getCourierId()==null){
            return APIEntity.fail("无法识别派送员信息！").setStatus(411);
        }
        if(StringUtils.isBlank(tCourierCard.getCardNum())||StringUtils.isBlank(tCourierCard.getCardBank())){
            return APIEntity.fail("请先拍照识别您的银行卡！");
        }
        if(!"中国银行".equals(tCourierCard.getCardBank())){
            return APIEntity.fail("抱歉，目前仅支持绑定中国银行银行卡！");
        }
        //近三十天内绑卡次数
        int times=tCourierCard.sql()
                .selectCount("select count(*)  from t_courier_card  where courier_id={0} and DATE_FORMAT(create_date, '%Y%m' )= DATE_FORMAT( CURDATE( ) , '%Y%m' )",tCourierCard.getCourierId());
        if(times>=3){
            return APIEntity.fail("您本月更改次数已满3次，下个月再来吧！");
        }
        tCourierCard.setCreateDate(LocalDateTime.now());
        tCourierCard.setBankType("商业银行");
        if(ITCourierCardService.save(tCourierCard)){
            if(courierService.update(new UpdateWrapper<TCourier>().set("courier_bank_account",tCourierCard.getCardId()).eq("courier_id",tCourierCard.getCourierId()))){
                return APIEntity.success();
            }
        }

        return APIEntity.fail("系统繁忙，请稍后再试！");
    }

    @GetMapping("getBank")
    @ApiOperation("根据派送员id获得绑定银行卡信息")
    public APIEntity getBankCard(Integer courierId){
        List<TCourierCard> tCourierCards = ITCourierCardService.list(new QueryWrapper<TCourierCard>().eq("courier_id",courierId).eq("bank_type","商业银行").orderByDesc("card_id"));
        if (tCourierCards == null||tCourierCards.size()<1){
            return APIEntity.fail("该派送员未绑定银行卡");
        }
        return APIEntity.success(tCourierCards.get(0));
    }

    @PostMapping("/upload/image")
    @ApiOperation("上传银行卡图片识别返回银行卡信息")
    public APIEntity imageRead(@ApiIgnore @RequestAttribute("JwtUserId") Integer id, @RequestParam("file") MultipartFile file, HttpServletResponse response) throws IOException {
        TCourier courier=courierService.getById(id);
        if(courier==null){
            return APIEntity.fail("无法找到派送员信息，请重新登陆！");
        }
        if(!ImageUtil.isImage(file)){
            return APIEntity.fail("无法识别的图片格式，请上传jpg或png格式！");
        }
        //压缩图像后上传
        org.json.JSONObject cardJson=BaiDuAiUtils.bankCard(ImageUtil.imageToBytes(ImageUtil.compress(ImageIO.read(file.getInputStream())),"jpg"));
        try{
            cardJson=cardJson.getJSONObject("result");
        }catch (Exception e){
            return APIEntity.fail("无法识别银行卡！");
        }
        if(!"中国银行".equals(cardJson.getString("bank_name"))){
            return APIEntity.fail("抱歉，目前仅支持绑定中国银行银行卡！");
        }
        TCourierCard card=new TCourierCard();
        card.setCreateDate(LocalDateTime.now());
        card.setCardName(courier.getCourierName());
        card.setCourierId(id);
        card.setIdNumber(courier.getCourierCard());
        card.setCardBank(cardJson.getString("bank_name"));
        card.setCardNum(cardJson.getString("bank_card_number").replace(" ",""));
        return APIEntity.success(card);
    }
    @GetMapping("/back/get")
    @ApiOperation("校验银行卡号返回银行卡信息")
    public APIEntity getBankByCord(@ApiIgnore @RequestAttribute("JwtUserId") Integer id,String cardNum){
        TCourier courier=courierService.getById(id);
        if(courier==null){
            return APIEntity.fail("无法找到派送员信息，请重新登陆！");
        }
        String result=HttpRequest.get("https://ccdcapi.alipay.com/validateAndCacheCardInfo.json")
                .query("_input_charset","utf-8")
                .query("cardNo",cardNum.replace(" ",""))
                .query("cardBinCheck","true").send().bodyText();
        JSONObject cardJson=JSON.parseObject(result);
        if(!cardJson.getBoolean("validated")){
            return APIEntity.fail("银行卡号填写错误！");
        }
        cardJson.put("bankName", JsonUtil.bankJson.getString(cardJson.getString("bank")));
        TCourierCard card=new TCourierCard();
        card.setCreateDate(LocalDateTime.now());
        card.setCardName(courier.getCourierName());
        card.setIdNumber(courier.getCourierCard());
        card.setCourierId(id);
        card.setCardBank(cardJson.getString("bankName"));
        card.setCardNum(cardJson.getString("key").replace(" ",""));
        return APIEntity.success(card);
    }

}
