package io.renren.modules.admin.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.math.BigDecimal;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.renren.modules.admin.entity.ExcelEntity;
import io.renren.modules.admin.entity.PaymentEntity;
import io.renren.modules.admin.service.AttendersService;
import io.renren.modules.admin.service.PaymentService;
import io.renren.common.utils.ExcelUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;

/**
 * 
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2020-02-14 14:51:30
 */
@RestController
@RequestMapping("admin/payment")
public class PaymentController {
    @Autowired
    private PaymentService paymentService;
    @Autowired
    private AttendersService attendersService;

    /**
     * 列表
     */
    @GetMapping("/list")
    @RequiresPermissions("admin:payment:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = paymentService.myQueryPage(params);

        Long meetingId = Long.valueOf(params.get("meetingId").toString());
        int total = paymentService.getTotal(meetingId);
        String where = "";
        BigDecimal totalMoney = paymentService.getTotalMoney(meetingId, where);
        // 现场缴费
        where = " and p.pay_type=2";
        BigDecimal totalMoney2 = paymentService.getTotalMoney(meetingId, where);
        // 线上缴费(汇款)
        where = " and p.pay_type=1";
        BigDecimal totalMoney1 = paymentService.getTotalMoney(meetingId, where);

        Map<String, Object> gatherMap = new HashMap<String, Object>();
        gatherMap.put("total", total);
        gatherMap.put("totalMoney", totalMoney);
        gatherMap.put("totalMoney1", totalMoney1);
        gatherMap.put("totalMoney2", totalMoney2);

        return R.ok().put("page", page).put("gather", gatherMap);
    }

    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    @RequiresPermissions("admin:payment:info")
    public R info(@PathVariable("id") Long id){
		PaymentEntity payment = paymentService.getById(id);

        Long aid = payment.getAttendersId();
        Map<String, Object> attenders = attendersService.getMapById(aid);

        return R.ok().put("payment", payment).put("attenders", attenders);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    @RequiresPermissions("admin:payment:save")
    public R save(@RequestBody PaymentEntity payment){
		paymentService.savePayment(payment);

        return R.ok();
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    @RequiresPermissions("admin:payment:update")
    public R update(@RequestBody PaymentEntity payment){
		paymentService.updateById(payment);

        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    @RequiresPermissions("admin:payment:delete")
    public R delete(@RequestBody Long[] ids){
		paymentService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    @GetMapping("/downloadxls")
    @RequiresPermissions("admin:payment:list")
    public void makeExcel(HttpServletResponse response, @RequestParam Map<String, Object> params) throws Exception {
        if (!params.containsKey("meetingId")) {
            throw new Exception("会议id不可为空");
        }
        String meetingName = params.containsKey("meetingName") ? params.get("meetingName").toString() : "";
       
        ExcelEntity data = new ExcelEntity();
        data.setName(meetingName + "签到数据");
        //添加表头
        List<String> titles = new ArrayList<String>();
        titles.add("id");
        titles.add("订单编号");
        titles.add("姓名");
        titles.add("所属机构");
        titles.add("缴费方式");
        titles.add("联系电话");
        titles.add("联系邮箱");
        titles.add("是否已缴费");
        titles.add("缴费时间");
        data.setTitles(titles);
        //添加列
        List<List<Object>> rows = new ArrayList<List<Object>>();
        List<Object> row = null;

        List<Map<String, Object>> list = paymentService.getMapList(params);
        SimpleDateFormat lastdate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (Map<String, Object> pmap : list) {
            row = new ArrayList<Object>();
            row.add(pmap.get("id"));
            row.add(pmap.get("orderId"));
            row.add(pmap.get("truename"));
            row.add(pmap.get("organization"));
            Integer payType = Integer.valueOf(pmap.get("payType").toString());
            if (payType == 1) {
                row.add("线上缴费");
            } else if (payType == 2) {
                row.add("现场缴费");
            } else {
                row.add("");
            }
            row.add(pmap.get("phone"));
            row.add(pmap.get("email"));
            Integer isPay = Integer.valueOf(pmap.get("isPay").toString());
            if (isPay == 1) {
                row.add("已缴费");
            } else {
                row.add("未缴费");
            }
            if (pmap.get("payTime") == null) {
                row.add("");
            } else {
                String payTime = lastdate.format((Date) pmap.get("payTime"));
                row.add(payTime);
            }
            rows.add(row);
            row = null;
        }
        data.setRows(rows);
        SimpleDateFormat fdate=new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName=fdate.format(new Date())+".xlsx";

        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(fileName, "utf-8"));
        // response.setHeader("Content-Disposition", "attachment;filename="+fileName);

        ExcelUtils.exportExcel(data, response.getOutputStream());
    }
}
