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.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

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

import org.apache.commons.lang.StringUtils;
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.AttendersEntity;
import io.renren.modules.admin.entity.ExcelEntity;
import io.renren.modules.admin.service.AttendersService;
import io.renren.common.utils.ExcelUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.modules.sys.controller.AbstractController;

/**
 * 
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2020-02-21 15:10:27
 */
@RestController
@RequestMapping("admin/attenders")
public class AttendersController extends AbstractController  {
    @Autowired
    private AttendersService attendersService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("admin:attenders:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = attendersService.queryPage(params);
        
        return R.ok().put("page", page);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("admin:attenders:info")
    public R info(@PathVariable("id") Long id) {
        AttendersEntity attenders = attendersService.getById(id);

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

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("admin:attenders:save")
    public R save(@RequestBody AttendersEntity attenders) {
        attenders.setCreateTime(new Date());
        attenders.setCreater(getUserId());
        attendersService.save(attenders);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("admin:attenders:update")
    public R update(@RequestBody AttendersEntity attenders) {
        attenders.setModifyTime(new Date());
        attenders.setModifier(getUserId());
        attendersService.updateById(attenders);

        return R.ok();
    }

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

        return R.ok();
    }

    /**
     * 改变参会意向
     * @param value
     * @param id
     */
    @PostMapping("/intention")
    @RequiresPermissions("admin:attenders:satus")
    public R intention(@RequestParam("id") Long id, @RequestParam("value") Integer value) {
         int result = changeColumnValue("intention", value, id);
        if (result == 1) {
            return R.ok();
        }
        return R.error();
    }

     /**
     * 是否需要订酒店
     * @param value
     * @param id
     */
    @PostMapping("/room")
    @RequiresPermissions("admin:attenders:satus")
    public R room(@RequestParam("id") Long id, @RequestParam("value") Integer value) {
        int result = changeColumnValue("room", value, id);
       if (result == 1) {
           return R.ok();
       }
       return R.error();
   }

    /**
     * 是否需要接送
     * @param value
     * @param id
     */
    @PostMapping("/transfer")
    @RequiresPermissions("admin:attenders:satus")
    public R transfer(@RequestParam("id") Long id, @RequestParam("value") Integer value) {
        int result = changeColumnValue("transfer", value, id);
       if (result == 1) {
           return R.ok();
       }
       return R.error();
   }

    /**
     * 改变单个字段值
     * @param params
     * @return
     */
    @PostMapping("/status")
    @RequiresPermissions("admin:attenders:satus")
    public R satus(@RequestBody Map<String, Object> params) {
        String column = (String) params.get("column");
        Integer value = (Integer) params.get("value"); 
        Long id =Long.valueOf(params.get("value").toString());
        int result = changeColumnValue(column, value, id);
        if (result != 0) {
           return R.ok(); 
        } 
        return R.error();
    }

    public int changeColumnValue(String column, Integer value, Long id) {
        return attendersService.changeColumnValue(column, value, id);
    }

    
    /**
     * 根据name模糊查询
     */
    @GetMapping("/selectbyname")
    @RequiresPermissions("admin:attenders:info")
    public R getListByName(@RequestParam Map<String, Object> params) {
        if (!params.containsKey("name") || !params.containsKey("meetingId") ) {
            return R.error("姓名不能为空 or 会议id不为空");
        }
        String name = params.get("name").toString();
        Long meetingId = Long.valueOf(params.get("meetingId").toString());
        List<AttendersEntity> list = attendersService.list(
            new QueryWrapper<AttendersEntity>().eq("meeting_id", meetingId).like(StringUtils.isNotBlank(name) ,"name", name)
        );
        return R.ok().put("list", list);
    }

    @GetMapping("/downloadxls")
    @RequiresPermissions("admin:attenders: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("用户类型");
        data.setTitles(titles);
        //添加列
        List<List<Object>> rows = new ArrayList<List<Object>>();
        List<Object> row = null;
        Long meetingId = Long.valueOf(params.get("meetingId").toString());
        List<Map<String, Object>> list = attendersService.getMapList(meetingId);
        SimpleDateFormat lastdate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (Map<String, Object> aMap : list) {
            row = new ArrayList<Object>();
            row.add(aMap.get("id"));
            row.add(aMap.get("truename"));
            row.add(aMap.get("organization"));
            row.add(aMap.get("position"));
            row.add(aMap.get("jobTitle"));
            row.add(aMap.get("phone"));
            row.add(aMap.get("email"));
            row.add(aMap.get("typeName"));
            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());
    }
}
