package com.jpsoft.shinestar.modules.business.controller;

import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.Page;
import com.jpsoft.shinestar.config.OSSConfig;
import com.jpsoft.shinestar.modules.base.entity.PersonInfo;
import com.jpsoft.shinestar.modules.base.service.PersonInfoService;
import com.jpsoft.shinestar.modules.business.dao.GuestInfoRecordDAO;
import com.jpsoft.shinestar.modules.business.dto.GuestInfoRecordDTO;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.business.entity.GuestInfoRecord;
import com.jpsoft.shinestar.modules.business.service.GuestInfoRecordService;
import com.jpsoft.shinestar.modules.common.utils.OSSUtil;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.mapping.ResultMap;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/business/guestInfoRecord")
public class GuestInfoRecordController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private GuestInfoRecordService guestInfoRecordService;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private OSSConfig ossConfig;

    @ApiOperation(value="添加信息")
    @PostMapping("add")
    public MessageResult<GuestInfoRecord> add(@ModelAttribute GuestInfoRecord guestInfoRecord){
        MessageResult<GuestInfoRecord> msgResult = new MessageResult<>();

        try {
            guestInfoRecord.setId(UUID.randomUUID().toString());

            int affectCount = guestInfoRecordService.insert(guestInfoRecord);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(guestInfoRecord);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库添加失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="获取信息")
    @GetMapping("detail/{id}")
    public MessageResult<GuestInfoRecord> detail(@PathVariable("id") String id){
        MessageResult<GuestInfoRecord> msgResult = new MessageResult<>();

        try {
            GuestInfoRecord guestInfoRecord = guestInfoRecordService.get(id);

            if (guestInfoRecord != null) {
                msgResult.setResult(true);
                msgResult.setData(guestInfoRecord);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库不存在该记录!");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="更新用户")
    @PostMapping("update")
    public MessageResult<GuestInfoRecord> update(@ModelAttribute GuestInfoRecord guestInfoRecord){
        MessageResult<GuestInfoRecord> msgResult = new MessageResult<>();

        try {
            int affectCount = guestInfoRecordService.update(guestInfoRecord);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(guestInfoRecord);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库更新失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }

    @ApiOperation(value="删除用户")
    @PostMapping("delete/{id}")
    public MessageResult<GuestInfoRecord> delete(@PathVariable("id") String id){
        MessageResult<GuestInfoRecord> msgResult = new MessageResult<>();

        try {
            int affectCount = guestInfoRecordService.delete(id);

            if (affectCount > 0) {
                msgResult.setResult(true);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库删除失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }


    @ApiOperation(value="批量删除")
    @PostMapping("batchDelete/{id}")
    public MessageResult<GuestInfoRecord> batchDelete(@PathVariable("id") String id){
        MessageResult<GuestInfoRecord> msgResult = new MessageResult<>();

        msgResult.setResult(false);
        msgResult.setMessage("未实现");

        return msgResult;
    }

    @ApiOperation(value="列表")
    @RequestMapping(value = "pageList",method = RequestMethod.POST)
    public MessageResult<Object> pageList(
            @RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "20") int pageSize,
            @RequestParam(value = "exportFlag", defaultValue = "false") Boolean exportFlag,
            HttpServletRequest request){
        String subject = (String)request.getAttribute("subject");

        //当前用户ID
        System.out.println(subject);

        MessageResult<Object> msgResult = new MessageResult<>();

        try {

            Map<String, Object> searchParams = new HashMap<>();

            List<Sort> sortList = new ArrayList<>();
            sortList.add(new Sort("create_time", "desc"));

            Page<GuestInfoRecord> page = guestInfoRecordService.pageSearch(searchParams, pageIndex, pageSize, true, sortList);

            Page<GuestInfoRecordDTO> pageDto = new Page<>();

            for (GuestInfoRecord guestInfoRecord : page) {
                GuestInfoRecordDTO guestInfoRecordDTO = new GuestInfoRecordDTO();

                guestInfoRecordDTO.setVisitDate(guestInfoRecord.getVisitDate());

                guestInfoRecordDTO.setName(guestInfoRecord.getName());

                guestInfoRecordDTO.setMobilePhone(guestInfoRecord.getMobilePhone());

                guestInfoRecordDTO.setUnit(guestInfoRecord.getUnit());

                guestInfoRecordDTO.setVisitReasons(guestInfoRecord.getVisitReasons());

                PersonInfo personInfo = personInfoService.get(guestInfoRecord.getIntervieweeId());

                guestInfoRecordDTO.setIntervieweeName(personInfo.getName());

                guestInfoRecordDTO.setIntervieweePhone(personInfo.getPhone());

                guestInfoRecordDTO.setComeInTime(guestInfoRecord.getComeInTime());

                guestInfoRecordDTO.setOutTime(guestInfoRecord.getOutTime());

                pageDto.add(guestInfoRecordDTO);
            }

            pageDto.setPageSize(page.getPageSize());
            pageDto.setTotal(page.getTotal());
            pageDto.setPageNum(page.getPageNum());

            if (exportFlag) {
                String filePath = exportXls(pageDto);
                msgResult.setData(filePath);
            } else {
                msgResult.setData(PojoUtils.pageWrapper(pageDto));
            }

            msgResult.setResult(true);


        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msgResult.setResult(false);
        }


        return msgResult;
    }


    private String exportXls(Page<GuestInfoRecordDTO> pageDto) {
        String downloadUrl = "";

        Workbook workbook = new HSSFWorkbook();
        Sheet sheet = workbook.createSheet();

        //表头
        Row rowTitle = sheet.createRow(0);

        String[] titles = new String[]{"序号","来访时间","来访人姓名","来访人电话","来访人单位",
                "来访人事由","受访人","受访人电话","进厂日期","出厂日期"};

        for (int i=0;i<titles.length;i++) {
            Cell cell = rowTitle.createCell(i);
            cell.setCellValue(titles[i]);
        }

        for (int i=0;i<pageDto.size();i++){
            GuestInfoRecordDTO guestInfoRecordDTO = pageDto.get(i);

            Row row = sheet.createRow(i+1);

            int colIndex = 0;
            row.createCell(colIndex++).setCellValue(i+1);

            String visitDate = "";
            if(guestInfoRecordDTO.getVisitDate()!=null) {
                visitDate = DateUtil.formatDateTime(guestInfoRecordDTO.getVisitDate());
            }
            row.createCell(colIndex++).setCellValue(visitDate);
            row.createCell(colIndex++).setCellValue(guestInfoRecordDTO.getName());
            row.createCell(colIndex++).setCellValue(guestInfoRecordDTO.getMobilePhone());
            row.createCell(colIndex++).setCellValue(guestInfoRecordDTO.getUnit());
            row.createCell(colIndex++).setCellValue(guestInfoRecordDTO.getVisitReasons());
            row.createCell(colIndex++).setCellValue(guestInfoRecordDTO.getIntervieweeName());
            row.createCell(colIndex++).setCellValue(guestInfoRecordDTO.getIntervieweePhone());

            String comeInTime = "";
            if(guestInfoRecordDTO.getComeInTime()!=null) {
                comeInTime = DateUtil.formatDateTime(guestInfoRecordDTO.getComeInTime());
            }
            row.createCell(colIndex++).setCellValue(comeInTime);

            String outTime = "";
            if(guestInfoRecordDTO.getOutTime()!=null) {
                outTime = DateUtil.formatDateTime(guestInfoRecordDTO.getOutTime());
            }
            row.createCell(colIndex++).setCellValue(outTime);
        }

        ByteArrayOutputStream output = new ByteArrayOutputStream();

        try {
            workbook.write(output);

            byte[] buffer = output.toByteArray();
            ByteArrayInputStream input = new ByteArrayInputStream(buffer);

            downloadUrl = OSSUtil.upload(ossConfig,"guestInfoRecord","访客记录.xls",input);
        }
        catch (Exception ex){
            logger.error(ex.getMessage(),ex);
        }

        return downloadUrl;
    }
}
