package io.renren.modules.admin.controller;

import io.renren.common.utils.ExcelUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.modules.admin.entity.AttendersEntity;
import io.renren.modules.admin.entity.ExcelEntity;
import io.renren.modules.admin.entity.MemberEntity;
import io.renren.modules.admin.entity.PaymentEntity;
import io.renren.modules.admin.entity.SignEntity;
import io.renren.modules.admin.entity.SignInfoEntity;
import io.renren.modules.admin.service.AttendersService;
import io.renren.modules.admin.service.MemberService;
import io.renren.modules.admin.service.PaymentService;
import io.renren.modules.admin.service.SignInfoService;
import io.renren.modules.admin.service.SignService;
import io.renren.modules.sys.controller.AbstractController;
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 javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * VIEW
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2020-03-23 16:28:38
 */
@RestController
@RequestMapping("admin/signinfo")
public class SignInfoController extends AbstractController {
    @Autowired
    private SignInfoService signInfoService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private AttendersService attendersService;
    @Autowired
    private SignService signService;
    @Autowired
    private PaymentService paymentService;

    /**
     * 列表
     */
    @GetMapping("/list")
    @RequiresPermissions("admin:signinfo:list")
    public R list(@RequestParam Map<String, Object> params){
        if (!params.containsKey("meetingId")) {
            return R.error("会议id不可为空");
        }
        PageUtils page = signInfoService.queryPage(params);

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

    @GetMapping("/listreg")
    @RequiresPermissions("admin:signinfo:list")
    public R listReg(@RequestParam Map<String, Object> params){
        params.put("regflag", 2);      // 现场注册
        return list(params);
    }

    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    @RequiresPermissions("admin:signinfo:info")
    public R info(@PathVariable("id") Long id){
		SignInfoEntity signInfo = signInfoService.getById(id);

        return R.ok().put("signInfo", signInfo);
    }

    public String setStringBoolen(Integer value) {
        return (value != null) && (value == 1) ? "是" : "否";
    }

    @GetMapping("/downloadxls")
    @RequiresPermissions("admin:signinfo: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("序号");
        titles.add("姓名");
        titles.add("所属机构");
        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;
        int i = 0;

        List<SignInfoEntity> sEntities = signInfoService.getList(params);
        SimpleDateFormat lastdate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (SignInfoEntity signInfoEntity : sEntities) {
            row = new ArrayList<Object>();
            row.add(i + 1);
            row.add(signInfoEntity.getTruename());
            row.add(signInfoEntity.getOrganization());
            row.add(signInfoEntity.getPosition());
            row.add(signInfoEntity.getPhone());
            row.add(signInfoEntity.getTypeAttenders());
            row.add(setStringBoolen(signInfoEntity.getIsPay()));
            row.add(setStringBoolen(signInfoEntity.getStatus()));
            row.add(setStringBoolen(signInfoEntity.getBadge()));
            row.add(signInfoEntity.getServername());
            String lastTime = lastdate.format(signInfoEntity.getLastTime());
            row.add(lastTime);
            rows.add(row);
            row = null;
            i++;
        }
        data.setRows(rows);
        SimpleDateFormat fdate=new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        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());
    }

    @GetMapping("/downloadxlsreg")
    @RequiresPermissions("admin:signinfo:list")
    public void downloadRgeData(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("序号");
        titles.add("姓名");
        titles.add("所属机构");
        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;
        int i = 0;

        params.put("regflag", 2);      // 现场注册
        List<SignInfoEntity> sEntities = signInfoService.getList(params);
        SimpleDateFormat date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (SignInfoEntity signInfoEntity : sEntities) {
            row = new ArrayList<Object>();
            row.add(i + 1);
            row.add(signInfoEntity.getTruename());
            row.add(signInfoEntity.getOrganization());
            row.add(signInfoEntity.getPhone());
            row.add(setStringBoolen(signInfoEntity.getIsPay()));
            row.add(signInfoEntity.getMoney());
            row.add(setStringBoolen(signInfoEntity.getStatus()));
            row.add(setStringBoolen(signInfoEntity.getBadge()));
            row.add(signInfoEntity.getServername());
            String regtime = date.format(signInfoEntity.getCreateTime());
            row.add(regtime);
            String lastTime = date.format(signInfoEntity.getLastTime());
            row.add(lastTime);
            rows.add(row);
            row = null;
            i++;
        }
        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());
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("admin:signinfo:save")
    public R save(@RequestBody SignInfoEntity signInfo){
        Date nowTime = new Date();
        MemberEntity member = new MemberEntity();
        member.setUsername(signInfo.getPhone());
        member.setPassword("123456");         // 默认密码
        member.setTruename(signInfo.getTruename());
        member.setOrganization(signInfo.getOrganization());
        member.setPosition(signInfo.getPosition());
        member.setJobTitle(signInfo.getJobTitle());
        member.setPhone(signInfo.getPhone());
        member.setEmail(signInfo.getEmail());
        member.setIsCheck(1);
        member.setCreateId(getUserId());
        memberService.saveMember(member);

        AttendersEntity attenders = new AttendersEntity();
        attenders.setMeetingId(signInfo.getMeetingId());
        attenders.setMemberId(member.getId());
        attenders.setName(member.getTruename());
        attenders.setTypeId(signInfo.getTypeId());
        attenders.setServicer(signInfo.getServicer());
        attenders.setNote(signInfo.getNote());
        attenders.setRegflag(2);        // 现场注册
        attenders.setCreater(getUserId());
        attenders.setCreateTime(nowTime);
        attendersService.save(attenders);

        PaymentEntity payment = new PaymentEntity();
        payment.setMeetingId(signInfo.getMeetingId());
        payment.setAttendersId(attenders.getId());
        payment.setIsPay(signInfo.getIsPay());
        payment.setMoney(signInfo.getMoney());
        paymentService.savePayment(payment);

        SignEntity sign = new SignEntity();
        sign.setMeetingId(signInfo.getMeetingId());
        sign.setAttendersId(attenders.getId());
        sign.setStatus(1);
        sign.setBadge(signInfo.getBadge());
        sign.setCreateTime(nowTime);
        sign.setLastTime(nowTime);
        sign.setFlag(1L);
		signService.save(sign);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("admin:signinfo:update")
    public R update(@RequestBody SignInfoEntity signInfo){
        SignInfoEntity formerSignInfo = signInfoService.getById(signInfo.getId());
        AttendersEntity attenders = attendersService.getById(formerSignInfo.getAId());
        MemberEntity member = memberService.getById(attenders.getMemberId());
        // MemberEntity member = new MemberEntity();
        // AttendersEntity attenders = new AttendersEntity();
        PaymentEntity payment = paymentService.getOne(new QueryWrapper<PaymentEntity>().eq("attenders_id", formerSignInfo.getAId()));

        Date nowTime = new Date();
        member.setId(attenders.getMemberId());
        member.setUsername(signInfo.getPhone());
        member.setTruename(signInfo.getTruename());
        member.setPhone(signInfo.getPhone());
        member.setModifyTime(nowTime);
        member.setModifyId(getUserId());
        memberService.updateById(member);

        attenders.setName(signInfo.getTruename());
        attenders.setPhone(signInfo.getPhone());
        attenders.setOrganization(signInfo.getOrganization());
        attenders.setNote(signInfo.getOrganization());
        attenders.setServicer(signInfo.getServicer());
        attendersService.updateById(attenders);

        payment.setIsPay(signInfo.getIsPay());
        payment.setMoney(signInfo.getMoney());
        paymentService.updateById(payment);

        return R.ok();
    }

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

    //     return R.ok();
    // }


    @PostMapping("/downloadxlsxc")
    @RequiresPermissions("admin:signinfo:list")
    public void makeExcelsc(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("序号");
        titles.add("姓名");
        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;
        int i = 0;

        List<SignInfoEntity> sEntities = signInfoService.getList(params);
        SimpleDateFormat lastdate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (SignInfoEntity signInfoEntity : sEntities) {
            row = new ArrayList<Object>();
            row.add(i + 1);
            row.add(signInfoEntity.getTruename());
            row.add(signInfoEntity.getOrganization());
            row.add(signInfoEntity.getTypeAttenders());
            row.add(signInfoEntity.getIsPay());
            row.add(signInfoEntity.getRegflag());
            row.add(signInfoEntity.getBadge());
            row.add(signInfoEntity.getServername());
            row.add(signInfoEntity.getNote());
            String creatTime = lastdate.format(signInfoEntity.getCreateTime());
            row.add(creatTime);
            rows.add(row);
            row = null;
            i++;
        }
        data.setRows(rows);
        SimpleDateFormat fdate=new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        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());
    }

}
