package io.renren.modules.admin.controller;

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

import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.AttendersEntity;
import io.renren.modules.admin.entity.MemberEntity;
import io.renren.modules.admin.entity.SignEntity;
import io.renren.modules.admin.entity.SignviewEntity;
import io.renren.modules.admin.service.AttendersService;
import io.renren.modules.admin.service.MemberService;
import io.renren.modules.admin.service.SignService;
import io.renren.modules.admin.service.SignviewService;
import io.renren.common.utils.ExcelData;
import io.renren.common.utils.ExcelUtils;
import io.renren.common.utils.MyUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.QRCodeUtils;
import io.renren.common.utils.R;

/**
 * 签到表
 *
 * @author huwhois
 * @email huwhois@163.com
 * @date 2020-12-18 11:34:30
 */
@RestController
@RequestMapping("admin/sign")
public class SignController {
    @Autowired
    private SignService signService;
    @Autowired
    private SignviewService signviewService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private AttendersService attendersService;
    @Value("${url}")
    private String infourl; // 读取配置文件中的指定目录

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

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

    /**
     * 获取打印条码等值
     */
    @GetMapping("/codeinfo/{aid}")
    @RequiresPermissions("admin:sign:info")
    public R codeInfo(@PathVariable("aid") Long aid) {
        SignviewEntity signinfo = signviewService.getByAid(aid);
        if (signinfo == null) {
            return R.error("用户不存在");
        }
        
        SignEntity sign = new SignEntity();

        if (signinfo.getId()==null || signinfo.getId()==0L) {
            String token = MyUtils.md5(aid + signinfo.getSymbol());
            sign.setToken(token);
            sign.setAttendersId(aid);
            sign.setStatus(1);
            sign.setBadge(1);
            sign.setPrintNum(1);
            sign.setPrintTime(new Date());
            sign.setCreateTime(new Date());
            signService.save(sign);
        } else {
            sign.setId(signinfo.getId());
            Integer printNum = sign.getPrintNum() == null ? 1 : sign.getPrintNum() + 1;
            sign.setPrintNum(printNum);
            sign.setPrintTime(new Date());
            signService.updateById(sign);
        }

        String image =null;
        try {
            image = QRCodeUtils.encode(infourl + signinfo.getSymbol());
        } catch (Exception e) {
            e.printStackTrace();
        }
        signinfo.setImage( "data:image/jpeg;base64," + image);
        return R.ok().put("signinfo", signinfo);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    @RequiresPermissions("admin:sign:save")
    public R save(@RequestBody SignviewEntity signForm){
        Long meetingId = signForm.getMeetingId();
        if (meetingId == 0L) {
            return R.error("会议id不可为空");
        }

        String symbol = MyUtils.md5(signForm.getTruename() + signForm.getPhone());

        MemberEntity member = memberService.getBySymbol(symbol);

        // 存会员表(个人信息, 开票信息)
        if (member == null) {
            member = new MemberEntity();
            member.setTruename(signForm.getTruename());
            member.setPhone(signForm.getPhone());
            member.setOrganization(signForm.getOrganization());
            member.setPosition(signForm.getPosition());
            member.setRemark(signForm.getRemark());
            memberService.save(member);
        } else {
            member.setOrganization(signForm.getOrganization());
            member.setPosition(signForm.getPosition());
            member.setRemark(signForm.getRemark());
            memberService.updateById(member);
        }

        Long memberId = member.getId();
        // 存参会信息
        AttendersEntity attenders = new AttendersEntity();
        attenders.setMemberId(memberId);
        attenders.setMeetingId(meetingId);
        attenders.setFeeType(signForm.getFeeType());
        attenders.setIsPay(1);
        attenders.setMoney(signForm.getMoney());
        attendersService.save(attenders);

        // 存签到信息
        SignEntity sign = new SignEntity();
        String token = MyUtils.md5(attenders.getId() + member.getSymbol());
        sign.setToken(token);
        sign.setAttendersId(attenders.getId());
        sign.setStatus(1);
        sign.setCreateTime(new Date());
        signService.save(sign);
        // signService.save(sign);
        return R.ok();
    }

    /**
     * 信息
     */
    @GetMapping("/infobyaid/{aid}")
    @RequiresPermissions("admin:sign:info")
    public R info(@PathVariable("aid") Long aid) {
        SignviewEntity signinfo = signviewService.getByAid(aid);

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

    /**
     * 修改
     */
    @PostMapping("/update")
    @RequiresPermissions("admin:sign:update")
    public R update(@RequestBody SignviewEntity signForm){
        Long meetingId = signForm.getMeetingId();
        if (meetingId == 0L) {
            return R.error("会议id不可为空");
        }

        AttendersEntity attenders = attendersService.getById(signForm.getAid());
        attenders.setFeeType(signForm.getFeeType());
        attenders.setMoney(signForm.getMoney());
        attendersService.updateById(attenders);

        MemberEntity member = memberService.getById(attenders.getMemberId());
        member.setTruename(signForm.getTruename());
        member.setOrganization(signForm.getOrganization());
        member.setPosition(signForm.getPosition());
        member.setPhone(signForm.getPhone());
        member.setRemark(signForm.getRemark());
        memberService.updateMember(member);

        SignEntity sign = new SignEntity();
        String token = MyUtils.md5(attenders.getId() + member.getSymbol());
        sign.setToken(token);
        if (signForm.getId()==null || signForm.getId()==0L) {
            sign.setAttendersId(attenders.getId());
            sign.setStatus(1);
            sign.setCreateTime(new Date());
            signService.save(sign);
        } else {
            sign.setId(signForm.getId());
            signService.updateById(sign);
        }

        return R.ok();
    }

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

        return R.ok();
    }

    /**
     * 导出签到数据
     */
    @GetMapping("/export")
    @RequiresPermissions("admin:sign:list")
    public void makeExcel(HttpServletResponse response, @RequestParam Map<String, Object> params) throws Exception {
        if (!params.containsKey("meetingId")) {
            throw new Exception("会议id不可为空");
        }
        Long meetingId = Long.valueOf((String) params.get("meetingId"));
        String meetingName = params.containsKey("meetingName") ? params.get("meetingName").toString() : "";
       
        ExcelData data = new ExcelData();
        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("金额");
        titles.add("最后签到时间");
        data.setTitles(titles);
        //添加列
        List<List<Object>> rows = new ArrayList<List<Object>>();
        List<Object> row = null;

        List<SignviewEntity> signExportEntities = signviewService.listSignAll(meetingId);
        SimpleDateFormat lastdate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (SignviewEntity signInfo : signExportEntities) {
            row = new ArrayList<Object>();
            row.add(signInfo.getId());
            row.add(signInfo.getTruename());
            row.add(signInfo.getOrganization());
            row.add(signInfo.getPosition());
            Integer sex = signInfo.getSex();
            if (sex == 1) {
                row.add("男");
            } else if (sex == 2) {
                row.add("女");
            } else {
                row.add("未知");
            }
            row.add(signInfo.getPhone());
            Integer memberType = signInfo.getMemberType();
            if (memberType == 1) {
                row.add("免注册");
            } else {
                row.add("正常");
            }
            Integer feeType = signInfo.getFeeType();
            if (feeType == 2) {
                row.add("学生");
            } else {
                row.add("普通");
            }
            Integer isPay =(Integer) signInfo.getIsPay(); 
            if (isPay == 0) {
                row.add("否");
            } else {
                row.add("是");
            }
            row.add(signInfo.getMoney());
            if (signInfo.getLastTime()==null) {
                row.add("");
            } else {
                String lastTime = lastdate.format((Date) signInfo.getLastTime());
                row.add(lastTime);
            }
            
            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());
    }

    /**
     * 列表
     */
    @GetMapping("/listall/{mid}")
    @RequiresPermissions("admin:sign:list")
    public R listall(@PathVariable("mid") Long mid) {
        List<SignviewEntity> list = signviewService.listSignAll(mid);

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

    /**
     * total
     */
    @GetMapping("/total/{mid}")
    @RequiresPermissions("admin:sign:info")
    public R total(@PathVariable("mid") Long mid){
        Integer total = signviewService.getSignTotal(mid, 0);
        Integer normal = signviewService.getSignTotal(mid, 1);
        Integer student = signviewService.getSignTotal(mid, 2);

        return R.ok().put("total", total).put("normal", normal).put("student", student);
    }
}
