package io.renren.modules.admin.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
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 javax.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
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 org.springframework.web.multipart.MultipartFile;

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.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.admin.entity.MemberEntity;
import io.renren.modules.admin.service.MemberService;
import io.renren.modules.sys.controller.AbstractController;


/**
 * 
 *
 * @author huwhois
 * @email huwhois@163.com
 * @date 2020-12-09 14:33:56
 */
@RestController
@RequestMapping("admin/member")
public class MemberController extends AbstractController {
    @Autowired
    private MemberService memberService;

    @Value("${file.datapath}")
    private String dataPath; // 读取配置文件中的指定目录

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

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

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

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

    /**
     * 保存
     */
    @PostMapping("/save")
    @RequiresPermissions("admin:member:save")
    public R save(@RequestBody MemberEntity member){
        ValidatorUtils.validateEntity(member, AddGroup.class);
        memberService.saveMember(member);

        return R.ok();
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    @RequiresPermissions("admin:member:update")
    public R update(@RequestBody MemberEntity member){
        ValidatorUtils.validateEntity(member, UpdateGroup.class);
		memberService.updateMember(member);

        return R.ok();
    }

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

        return R.ok();
    }

    /**
     * 改变备注
     * @param params
     * @return
     */
    @PostMapping("/remark")
    @RequiresPermissions("admin:member:update")
    public R remark(@RequestBody Map<String, Object> params){   
        Long id = Long.valueOf(params.get("id").toString());
        String remark =params.get("remark").toString();
        int res = memberService.updateRemark(id, remark);
        if (res == 0) {
            return R.error("更改备注失败");
        }
        return R.ok();
    }

    /**
     * 修改flag
     * @param params
     * @return
     */
    @PostMapping("/flag")
    @RequiresPermissions("admin:member:update")
    public R flag(@RequestBody Map<String, Object> params){   
        Long id = Long.valueOf(params.get("id").toString());
        Integer flag = Integer.valueOf(params.get("flag").toString());
        int res = memberService.updateFlag(id, flag);
        if (res == 0) {
            return R.error("用户不存在");
        }
        return R.ok();
    }

    /**
     * 会员导入
     * 
     * @param file
     * @param meetingId
     * @return
     * @throws Exception
     */
    @PostMapping("import")
    @RequiresPermissions("admin:member:save")
    public R importExcel(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return R.error("error,file is empty!");
        }
        if (ExcelUtils.isExcel(file) == false) {
            return R.error("error,file is not excel!");
        }

        Map<String, Integer> statistics = new HashMap<>();
        List<MemberEntity> successList = new ArrayList<>();
        List<MemberEntity> failList = new ArrayList<>();

        Workbook workbook = ExcelUtils.createWorkbook(file);
        if (workbook != null) {
            // 获取工作表
            Sheet sheet = workbook.getSheetAt(0);
            // 获取sheet中第一行行号
            int firstRowNum = sheet.getFirstRowNum();
            // 获取sheet中最后一行行号
            int lastRowNum = sheet.getLastRowNum();
            // 循环插入数据
            int failNum = 0;
            int totalNum = 0;
            for (int i = firstRowNum + 1; i <= lastRowNum; i++) { // 标题的下一行开始
                totalNum++;
                Row row = sheet.getRow(i);
                if (ExcelUtils.isEmptyRow(row) == false) {
                    String name = ExcelUtils.getVal(row.getCell(1));
                    String sex = ExcelUtils.getVal(row.getCell(2));
                    String organization = ExcelUtils.getVal(row.getCell(3));
                    String position = ExcelUtils.getVal(row.getCell(4));
                    String phone = ExcelUtils.getVal(row.getCell(5));
                    String email = ExcelUtils.getVal(row.getCell(6));
                    String tax_type = ExcelUtils.getVal(row.getCell(7));
                    String tax_ttitle = ExcelUtils.getVal(row.getCell(8));
                    String tax_number = ExcelUtils.getVal(row.getCell(9));
                    String company_address = ExcelUtils.getVal(row.getCell(10));
                    String company_phone = ExcelUtils.getVal(row.getCell(11));
                    String bank_account = ExcelUtils.getVal(row.getCell(12));
                    String mailing_address = ExcelUtils.getVal(row.getCell(13));
                    String postcode = ExcelUtils.getVal(row.getCell(14));
                    String remark = ExcelUtils.getVal(row.getCell(15));

                    MemberEntity member = new MemberEntity();

                    member.setTruename(name);
                    member.setPhone(phone);
                    member.setSex(Integer.valueOf(sex));
                    member.setOrganization(organization);
                    member.setPosition(position);
                    member.setEmail(email);
                    member.setTaxType(Integer.valueOf(tax_type));
                    member.setTaxTitle(tax_ttitle);
                    member.setTaxNumber(tax_number);
                    member.setCompanyAddress(company_address);
                    member.setCompanyPhone(company_phone);
                    member.setBankAccount(bank_account);
                    member.setMailingAddress(mailing_address);
                    member.setPostcode(postcode);
                    member.setRemark(remark);
                   
                    if (StringUtils.isBlank(name)) {
                        member.setRemark(member.getRemark() + "==>姓名不能为空");
                        failList.add(member);
                        failNum++;
                    } else if (StringUtils.isBlank(phone) || !MyUtils.checkPhone(phone)) {
                        member.setRemark(member.getRemark() + "==>电话格式不正确");
                        failList.add(member);
                        failNum++;
                    } else {
                        successList.add(member);
                    }
                }
            }
            doImport(successList, failList);
            statistics.put("total", totalNum);
            statistics.put("succes", totalNum - failNum);
            statistics.put("fail", failNum);
        }

        return R.ok("上传成功!").put("statistics", statistics);
    }

    @Async
    public void doImport(List<MemberEntity> successList, List<MemberEntity> failList) {
        for (MemberEntity member : successList) {
            try {
                memberService.saveMember(member);
            } catch (Exception e) {
                e.printStackTrace();
                member.setRemark(member.getRemark() + "==>" + e.getMessage());
                failList.add(member);
            }
        }

        ExcelData data = new ExcelData();
        data.setName("error");
        // 添加表头
        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("发票抬头");
        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;

        // SimpleDateFormat lastdate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int i = 1;
        for (MemberEntity member : failList) {
            row = new ArrayList<Object>();
            row.add(i);
            row.add(member.getTruename());
            row.add(member.getSex());
            row.add(member.getOrganization());
            row.add(member.getPosition());
            row.add(member.getPhone());
            row.add(member.getEmail());
            row.add(member.getTaxType());
            row.add(member.getTaxTitle());
            row.add(member.getTaxNumber());
            row.add(member.getCompanyAddress());
            row.add(member.getCompanyPhone());
            row.add(member.getBankAccount());
            row.add(member.getMailingAddress());
            row.add(member.getPostcode());
            row.add(member.getRemark());

            rows.add(row);
            row = null;
            i++;
        }

        data.setRows(rows);

        try {
            Long userId = getUserId();
            String fileName = "member_" + userId + ".xlsx";
            String filePath = "/uploads/fails/" + fileName;
            String savePath = dataPath + filePath;

            OutputStream os = new FileOutputStream(savePath);
            ExcelUtils.exportExcel(data, os);

            os.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

        /**
     * 导出最近上传出租哦文件
     * @param response
     */
    @GetMapping("downloadfails")
    @RequiresPermissions("admin:member:save")
    public void downloadFailFile(HttpServletResponse response) {
        Long userId = getUserId();
        String filePath = dataPath + "/uploads/fails/member_" + userId + ".xlsx";
        
        try {
            File file = new File(filePath);
            if (file.exists()) {
                InputStream fis = new BufferedInputStream(new FileInputStream(file));
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();

                response.reset();
                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"));
                OutputStream os = new BufferedOutputStream(response.getOutputStream());
                os.write(buffer);
                os.flush();
                os.close();
            } else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "没有最近出错文件");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1){
            e1.printStackTrace();
        } catch (IOException e2){
            e2.printStackTrace();
        }
    }

}
