package io.renren.modules.admin.service.impl;

import java.util.Map;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

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.Query;
import io.renren.modules.admin.dao.AttendersDao;
import io.renren.modules.admin.entity.AttendersEntity;
import io.renren.modules.admin.entity.AttendersviewEntity;
import io.renren.modules.admin.entity.MemberEntity;
import io.renren.modules.admin.service.AttendersService;
import io.renren.modules.admin.service.MemberService;


@Service("attendersService")
public class AttendersServiceImpl extends ServiceImpl<AttendersDao, AttendersEntity> implements AttendersService {

    @Autowired
    private MemberService memberService;

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

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttendersEntity> page = this.page(new Query<AttendersEntity>().getPage(params),
                new QueryWrapper<AttendersEntity>());

        return new PageUtils(page);
    }

    @Override
    public AttendersEntity getByMMId(Long memberId, Long meetingId) {
        return this.getOne(new QueryWrapper<AttendersEntity>().eq("member_id", memberId).eq("meeting_id", meetingId));
    }

    @Override
    public int removeReport(Long id) {
        return baseMapper.removeReport(id);
    }

    @Override
    public boolean saveAttendes(AttendersviewEntity attendersform) {
        try {
            String symbol = MyUtils.md5(attendersform.getTruename() + attendersform.getPhone());

            MemberEntity member = memberService.getBySymbol(symbol);

            // 存会员表(个人信息, 开票信息)
            if (member == null) {
                member = new MemberEntity();
                member.setTruename(attendersform.getTruename());
                member.setPhone(attendersform.getPhone());
            }
            member.setOrganization(attendersform.getOrganization());
            member.setPosition(attendersform.getPosition());
            member.setEmail(attendersform.getEmail());
            member.setSex(attendersform.getSex());
            member.setRemark(attendersform.getRemark());
            member.setTaxType(attendersform.getTaxType());
            member.setTaxTitle(attendersform.getTaxTitle());
            member.setTaxNumber(attendersform.getTaxNumber());
            member.setCompanyAddress(attendersform.getCompanyAddress());
            member.setCompanyPhone(attendersform.getCompanyPhone());
            member.setBankAccount(attendersform.getBankAccount());
            member.setMailingAddress(attendersform.getMailingAddress());
            member.setPostcode(attendersform.getPostcode());

            if (member.getId() == null || member.getId() == 0L) {
                memberService.saveMember(member);
            } else {
                memberService.updateMember(member);
            }

            // 存参会信息
            AttendersEntity attenders = this.getByMMId(member.getId(), attendersform.getMeetingId());
            if (attenders == null) {
                attenders = new AttendersEntity();
                attenders.setMemberId(member.getId());
                attenders.setMeetingId(attendersform.getMeetingId());
            }

            attenders.setMemberType(attendersform.getMemberType());
            attenders.setFeeType(attendersform.getFeeType());
            attenders.setPaperType(attendersform.getPaperType());
            attenders.setIsReport(attendersform.getIsReport());
            attenders.setReportTitle(attendersform.getReportTitle());
            attenders.setHotelType(attendersform.getHotelType());
            attenders.setRoomType(attendersform.getRoomType());
            attenders.setIsShare(attendersform.getIsShare());
            attenders.setCheckInDate(attendersform.getCheckInDate());
            attenders.setCheckOutDate(attendersform.getCheckOutDate());
            attenders.setPayType(attendersform.getPayType());
            attenders.setIsPay(attendersform.getIsPay());
            attenders.setMoney(attendersform.getMoney());
            attenders.setCreateTime(new Date());

            this.save(attenders);
        } catch (Exception e) {
            return false;
        }

        return true;
    }

    @Override
    @Async
    public void doImport(List<AttendersviewEntity> successList, List<AttendersviewEntity> failList, Long userId) {
        for (AttendersviewEntity attendersInfo : successList) {
            try {
                saveAttendes(attendersInfo);
            } catch (Exception e) {
                e.printStackTrace();
                attendersInfo.setRemark(attendersInfo.getRemark() + " 导入错误原因:未知");
                failList.add(attendersInfo);
            }
        }

        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("备注");
        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 (AttendersviewEntity attender : failList) {
            row = new ArrayList<Object>();
            row.add(i);
            row.add(attender.getTruename());
            row.add(attender.getSex());
            row.add(attender.getOrganization());
            row.add(attender.getPosition());
            row.add(attender.getPhone());
            row.add(attender.getEmail());
            row.add(attender.getTaxType());
            row.add(attender.getTaxTitle());
            row.add(attender.getTaxNumber());
            row.add(attender.getCompanyAddress());
            row.add(attender.getCompanyPhone());
            row.add(attender.getBankAccount());
            row.add(attender.getMailingAddress());
            row.add(attender.getPostcode());
            row.add(attender.getRemark());
            row.add(attender.getMemberType());
            row.add(attender.getFeeType());
            row.add(attender.getPaperType());
            row.add(attender.getIsReport());
            row.add(attender.getReportTitle());
            row.add(attender.getHotelType());
            row.add(attender.getRoomType());
            row.add(attender.getCheckInDate());
            row.add(attender.getCheckOutDate());
            row.add(attender.getPayType());
            row.add(attender.getIsPay());
            row.add(attender.getMoney());

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

        data.setRows(rows);

        try {
            String fileName = "attenders_" + 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();
        }
    }
}
