package com.srs.web.controller.stureg;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.srs.common.annotation.Anonymous;
import com.srs.common.enums.HttpMethod;
import com.srs.common.utils.DateUtils;
import com.srs.common.utils.http.HttpHelper;
import com.srs.common.utils.sign.Base64;
import com.srs.common.utils.sign.Md5Utils;
import com.srs.comprehensive.domain.CphTeacher;
import com.srs.comprehensive.domain.SrsClass;
import com.srs.comprehensive.mapper.CphTeacherMapper;
import com.srs.comprehensive.mapper.SrsClassMapper;
import com.srs.dormitory.service.ISrsDormitoryStudentService;
import com.srs.stureg.domain.SrsStuReg;
import com.srs.stureg.domain.SrsStuTodo;
import com.srs.stureg.service.ISrsStuRegService;
import com.srs.stureg.service.ISrsStuTodoService;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.srs.common.annotation.Log;
import com.srs.common.core.controller.BaseController;
import com.srs.common.core.domain.AjaxResult;
import com.srs.common.enums.BusinessType;
import com.srs.comprehensive.domain.SrsOrder;
import com.srs.comprehensive.service.ISrsOrderService;
import com.srs.common.utils.poi.ExcelUtil;
import com.srs.common.core.page.TableDataInfo;

/**
 * 支付订单Controller
 *
 * @author srs
 * @date 2023-07-24
 */
@RestController
@RequestMapping("/system/order")
public class SrsOrderController extends BaseController
{
    @Autowired
    private ISrsOrderService srsOrderService;

    @Autowired
    private ISrsStuRegService _stuRegService;

    @Autowired
    private ISrsStuTodoService srsStuTodoService;



    @PostMapping("/validToken")
    public AjaxResult validToken(){
        String username = getUsername();
        return AjaxResult.success(username);
    }

    @Anonymous
    @PostMapping("/toPay")
    public AjaxResult toPay(){
        //String sno = getUsername();
        //SrsStuReg stu = _stuRegService.selectSrsStuRegByStuNo(sno);

        String username = getUsername();//"202301001"; //getUsername();
        String strKey = "GLJP";
        String strSysDatetime = DateUtils.getTime();
        String jsName = "student";

        String ext = Md5Utils.hash(username + strKey + strSysDatetime + jsName);

        String url = "http://xsjf.gxsdxy.cn:8560/Home/login?userName=" +username+"&strSysDatetime="+strSysDatetime
                +"&jsName=student&verify="+ext+"&npage=djxf";

        Map<String,String> map= new HashMap<>();

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        QrCodeUtil.generate(url, 500, 500, ImgUtil.IMAGE_TYPE_PNG, outputStream);
        // encode 就是前端img标签可解析的base编码
        String encode = Base64.encode(outputStream.toByteArray());
        //如果二维码要在前端显示需要转成Base64
        String base64 = "data:image/png;base64,";
        encode = base64 + encode;
        map.put("src",encode);
        map.put("url",url);
        return AjaxResult.success(map);
    }


    @Autowired
    private SrsClassMapper srcClassMapper;
    @Autowired
    private CphTeacherMapper cphTeacherMapper;
    @Autowired
    private ISrsDormitoryStudentService srsDormitoryStudentService;

    @Anonymous
    @PostMapping("/getOrderList")
    public AjaxResult getOrder() {
        try{
            SrsStuReg stuReg = _stuRegService.getOwnInfoByKsh(getUsername());
            if(stuReg.getRegStatus()=="5") {
                return AjaxResult.success("确定申请助学贷款");
            }
            SrsStuReg stu= _stuRegService.getOwnInfoByKsh(getUsername());
            String username = stu.getKSH();//"202301001";//stu.getKSH();
            String strKey = "GLJP";
            String strSysDatetime = DateUtils.getTime();
            String ext = Md5Utils.hash(username + strKey + strSysDatetime );

            String url = "http://xsjf.gxsdxy.cn:8560/Interface/GetStudentChargeItems?verify="
                    +ext+"&strSysDatetime="+strSysDatetime
                    +"&SID="+username+"&IDCode="+stu.getSFZH();
            url = url.replace(" ","%20");
            HttpClient client= HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse res = client.execute(httpGet);
            JSONObject jsonObject = JSONObject.parseObject(EntityUtils.toString(res.getEntity()));
            String data= jsonObject.get("data").toString();
            String code=jsonObject.get("code").toString();
            if(code.equals("0")){
                return AjaxResult.error(data);
            }else{
                Gson gson = new Gson();
                Type type = new com.google.gson.reflect.TypeToken<Map<String, Object>>() {}.getType();
                // 将 JSON 字符串转换为 Map
                Map<String, Object> map = gson.fromJson(data, type);
                BigDecimal totalReceivableMoney = new BigDecimal(map.get("TotalReceivableMoney").toString());//应收
                BigDecimal totalPayMoney = new BigDecimal(map.get("TotalPayMoney").toString());//已交

                BigDecimal result = totalReceivableMoney.subtract(totalPayMoney);
                //System.out.println(result);
                boolean isPay = result.compareTo(BigDecimal.ZERO) == 0 || result.compareTo(BigDecimal.ZERO) < 0;
                if (isPay){
                    stuReg.setRegStatus("1");
                    _stuRegService.updateSrsStuReg(stuReg);
                    srsStuTodoService.confirmTask(getUsername(),"ZXJF");
                    // 分配宿舍逻辑
//                    String classCode = stuReg.getBJDM();
//                    QueryWrapper<SrsClass> queryWrapper = new QueryWrapper<>();
//                    queryWrapper.eq("class_code",classCode);
//                    SrsClass srsClass = srcClassMapper.selectOne(queryWrapper);
//                    Long teacherId = srsClass.getTeacherId();
//                    CphTeacher cphTeacher = cphTeacherMapper.selectCphTeacherByTeacherId(teacherId);
//                    String employeeId = cphTeacher.getEmployeeId();
//                    // 自动分配宿舍
//                    srsDormitoryStudentService.assignDormitoryByTeacher(employeeId);

                    return AjaxResult.success("已缴费");
                }else {
                    return AjaxResult.error("未缴费");
                }
            }
        }catch(Exception ex){
            return AjaxResult.error(ex.getMessage());
        }
    }

    /**
     * 查询支付订单列表
     */
//    @PreAuthorize("@ss.hasPermi('system:order:list')")
    @GetMapping("/list")
    public TableDataInfo list(SrsOrder srsOrder)
    {
        startPage();
        List<SrsOrder> list = srsOrderService.selectSrsOrderList(srsOrder);
        return getDataTable(list);
    }
    /**
     * 根据用户id查询支付订单
     */
    @GetMapping("/list/user")
    public TableDataInfo listByUserId()
    {
        SrsOrder srsOrder = new SrsOrder();
        srsOrder.setUserId(getUserId());
        startPage();
        List<SrsOrder> list = srsOrderService.selectSrsOrderList(srsOrder);
        return getDataTable(list);
    }

    /**
     * 导出支付订单列表
     */
//    @PreAuthorize("@ss.hasPermi('system:order:export')")
    @Log(title = "支付订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SrsOrder srsOrder)
    {
        List<SrsOrder> list = srsOrderService.selectSrsOrderList(srsOrder);
        ExcelUtil<SrsOrder> util = new ExcelUtil<SrsOrder>(SrsOrder.class);
        util.exportExcel(response, list, "支付订单数据");
    }

    /**
     * 获取支付订单详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:order:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(srsOrderService.selectSrsOrderById(id));
    }

    /**
     * 新增支付订单
     */
//    @PreAuthorize("@ss.hasPermi('system:order:add')")
    @Log(title = "支付订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SrsOrder srsOrder)
    {
        return toAjax(srsOrderService.insertSrsOrder(srsOrder));
    }

    /**
     * 修改支付订单
     */
//    @PreAuthorize("@ss.hasPermi('system:order:edit')")
    @Log(title = "支付订单", businessType = BusinessType.UPDATE)
    @PostMapping("/update")
    public AjaxResult edit(@RequestBody SrsOrder srsOrder)
    {
        return toAjax(srsOrderService.updateSrsOrder(srsOrder));
    }

    /**
     * 删除支付订单
     */
//    @PreAuthorize("@ss.hasPermi('system:order:remove')")
    @Log(title = "支付订单", businessType = BusinessType.DELETE)
    @PostMapping("/delete/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(srsOrderService.deleteSrsOrderByIds(ids));
    }
}
