package com.winsun.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.winsun.auth.core.common.model.ResponseData;
import com.winsun.bean.OrderView;
import com.winsun.bean.Product;
import com.winsun.bean.School;
import com.winsun.bean.UniversityInfo;
import com.winsun.constant.Constant;
import com.winsun.constant.OrderStatus;
import com.winsun.mapper.*;
import com.winsun.utils.IDCardUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 单宽办理接口
 *
 * @Author xuede
 * @Date 2020/3/9 16:52
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/dankuan")
public class DankuanController {

    private static ProductMapper productMapper;

    private static SchoolMapper schoolMapper;

    private static AppMapper appMapper;

    private static UniversityInfoMapper universityInfoMapper;

    private static OrderViewMapper orderViewMapper;


    @Autowired
    public DankuanController(ProductMapper productMapper, SchoolMapper schoolMapper, AppMapper appMapper,
                             UniversityInfoMapper universityInfoMapper, OrderViewMapper orderViewMapper) {
        DankuanController.productMapper = productMapper;
        DankuanController.schoolMapper = schoolMapper;
        DankuanController.appMapper = appMapper;
        DankuanController.universityInfoMapper = universityInfoMapper;
        DankuanController.orderViewMapper = orderViewMapper;
    }

    /**
     * 查询单宽办理接口
     *
     * @return
     */
    @RequestMapping("/data")
    public ResponseData<Product> getdankuanData(@RequestParam("id") Integer id) {
        //空，直接返回
        if (id == null) {
            return ResponseData.error("请输入合伙人id");
        }
        String schoolId = appMapper.selectSchoolId(id.toString());
        School school = schoolMapper.selectById(schoolId);
        String bandproductId = school.getBandproductId();
        if (StringUtils.isBlank(bandproductId)) {
            return ResponseData.error("敬请期待");
        }
        Product product = productMapper.selectById(bandproductId);
        return ResponseData.success(product);
    }

    @RequestMapping("/selectUniversity")
    public ResponseData<UniversityInfo> selectUniversity(@RequestParam("universityId") String universityId) {
        UniversityInfo universityInfo = universityInfoMapper.selectById(universityId);
        return ResponseData.success(universityInfo);
    }

    @RequestMapping("/createProductOrder")
    public ResponseData<OrderView> createProductOrder(@RequestParam("orderName") String orderName, @RequestParam("orderPhone") String orderPhone,
                                                   @RequestParam("orderNumber") String orderNumber, @RequestParam("orderCustomerStudentId") String orderCustomerStudentId,
                                                   @RequestParam("orderCustomerAccount") String orderCustomerAccount, @RequestParam("orderCustomerPwd") String orderCustomerPwd,
                                                   @RequestParam("orderSetMeal") String orderSetMeal, @RequestParam("productId") String productId,
                                                   @RequestParam("webOrderAmount") String webOrderAmount) {
        if(!IDCardUtil.IDCardValidate(orderNumber)){
            return ResponseData.error("您的身份证输入有误，请重新输入！");
        }
        if (orderPhone.length() != 11) {
            return ResponseData.error("联系号码有误，请重新输入");
        }
        Wrapper<OrderView> wrapper = new EntityWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(orderNumber), "orderNumber", orderNumber);
        wrapper.ne( "status", OrderStatus.INVALID.getId());
        List<OrderView> orderViews = orderViewMapper.selectList(wrapper);
        OrderView orderV = new OrderView();
        if(orderViews.size()!= 0){
            orderV.setOrderId(orderViews.get(0).getOrderId());
            orderV.setOrderseq(orderViews.get(0).getOrderseq());
            return ResponseData.error(orderV,"当前身份证号已有订单存在！");
        }
        SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date();
        String format = yyyyMMdd.format(date);
        String s = String.valueOf((int) ((Math.random() * 9 + 1) * 1000));
        String orderSeq = "YRYM" + format + s;
        Product product = productMapper.selectById(productId);
        OrderView orderView = new OrderView();
        orderView.setOrdername(orderName);
        orderView.setOrderphone(orderPhone);
        orderView.setOrdernumber(orderNumber);
        orderView.setOrderCustomerStudentId(orderCustomerStudentId);
        orderView.setOrderCustomerAccount(orderCustomerAccount);
        orderView.setOrderCustomerPwd(orderCustomerPwd);
        orderView.setOrderSetMeal(orderSetMeal);
        orderView.setOrderseq(orderSeq);
        orderView.setProductname(product.getProductTitle());
        orderView.setOrderdate(new Date());
        orderView.setOrderUniversityName(product.getProductUniversity());
        orderView.setStatus(OrderStatus.NOTPAID.getId());
        orderView.setOrderRegion(product.getProductRegion());
        orderView.setPaytype("1");
        orderView.setWeborderamount(webOrderAmount);
        if(webOrderAmount.equals("0")){
            orderView.setIpay("0");
        }else {
            orderView.setIpay("1");
        }
        orderView.setOrderreqtranseq("xyzxyql");
        orderView.setOrderCustomerType("学生");
        Integer insert = orderViewMapper.insert(orderView);
        if(insert == 1){
            orderV.setOrderId(orderView.getOrderId());
            orderV.setOrderseq(orderView.getOrderseq());
            return ResponseData.success(orderV,"订单提交完成！");
        }
        return ResponseData.error("提交失败！");
    }

/*    *//**
     * @author ljh
     * @Description:支付请求
     *//*
    private void JsoupMethodZhifu(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // TODO Auto-generated method stub
        log.info("----------首先发送支付请求接口----------");
        Map<String, String> map = new HashMap<String, String>();
        //查询订单信息


        //给MAP数组添加数据
        map.put("CLIENTNUMBER", Constant.CLIENTNUMBER);
        map.put("ORDERSEQ", orderMap.get("orderSeq"));

        log.info("----------宽带价格prices：" + prices);
        if (Constant.PRODUCTSKU479Str.indexOf(prices) != -1) {
            map.put("PRODUCTSKU", Constant.PRODUCTSKU479);
        } else {
            map.put("PRODUCTSKU", Constant.PRODUCTSKU481);
        }


        map.put("ORDERDATE", orderMap.get("orderDate"));
        String pricesStr = orderMap.get("prices").replace("元", "");
//		pricesStr = "0.01";
        map.put("ORDERAMOUNT", pricesStr);


        map.put("ORDERNAME", orderMap.get("orderName"));
        map.put("ORDERPHONE", orderMap.get("orderPhone"));
        map.put("ORDERNUMBER", orderMap.get("orderNumber"));

        if (Constant.Payment1.equals(radioValue)) {
            String MERCHANTURL = Constant.TOMCATURL + "/gdtel-xyzx-hhr/vPageJump/toPaymentSuccessPage.do?orderSeq=" + orderMap.get("orderSeq");
            map.put("MERCHANTURL", MERCHANTURL);
        }
        if (orderMap.get("upStatus") != null && orderMap.get("upStatus").equals("1")) {
            //支付成功后融合回调
            map.put("BACKDROPURL", Constant.TOMCATURL + "/gdtel-xyzx-hhr/paymentCon/toSubmisOrderPreserRH.do");
        } else {
            //单宽回调地址
            map.put("BACKDROPURL", Constant.TOMCATURL + "/gdtel-xyzx-hhr/paymentCon/toSubmisOrderPreser.do");
        }
        String str = "ORDERSEQ=" + orderMap.get("orderSeq") + "&ORDERDATE=" + orderMap.get("orderDate") + "&ORDERAMOUNT=" + pricesStr + "&KEY=" + Constant.KEY;
        *//*	将值转换为大写	*//*
        map.put("MAC", SignUtil.exChange(SignUtil.md5EncodeSignature(str)));
        int PAYTYPE = 1;        // 支付类型
        int IPAY = 1;    // 支付平台
        log.info("----------支付渠道（0翼支付网厅，1支付宝，3微信）：" + radioValue);
        if (Constant.Payment3.equals(radioValue)) {
            PAYTYPE = 5;
            IPAY = 3;
        }
        map.put("PAYTYPE", String.valueOf(PAYTYPE));
        map.put("IPAY", String.valueOf(IPAY));
        log.info("----------支付请求参数：" + map);
        //定义Document对象
        Document doc = null;
        String result = "";
        String qrcode = "";
        //Jsoup用post提交,超时6秒钟，
        doc = Jsoup.connect("https://gzdxpay.mini189.cn/web/order-pay.action").data(map).timeout(20000).ignoreContentType(true).post();
        //获取回调信息
        String i = doc.text().trim();
        System.out.println(i);
        //解析json格式
        JSONObject json = JSONObject.fromObject(i);
        //获取jsonp格式中的result（短链接，返回到前端）
        log.info("----------调用穗易付接口返回的结果：" + json);
        result = (String) json.get("result");
        qrcode = (String) json.get("qrcode");
        String ORDERSEQ = (String) json.get("ORDERSEQ");
        String msg = (String) json.get("msg");
        if (StringUtils.isNotBlank(msg) && msg.equals("success")) {
            //获取的短链接地址，使用redirect方式返回前端。（流程图中的步骤8,301跳转）
            orderMap.put("payType", PAYTYPE + "");
            log.info("====默认受理未付费，之后可通过提交订单到智能平台后再更新状态====");
            orderMap.put("Status", "100");
            log.info("====保存到本地数据库 ====");
            if (StringUtils.isNotBlank(ORDERSEQ)) {
                Map<String, Object> queOrderMaps = orderService.queryorderSeq(ORDERSEQ);    // 保存前查询订单号是否存在，存在即为更新
                if (BeanUtil.isNotBlank(queOrderMaps)) {
                    saveOrderInfo(request, orderMap, ORDERSEQ);
                } else {
                    saveOrderInfo(request, orderMap, "");
                }
            }

            response.sendRedirect(result);
        }
    }*/
}
