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

import com.github.pagehelper.Page;
import com.jpsoft.shinestar.config.OSSConfig;
import com.jpsoft.shinestar.modules.base.dto.CanteenOutsourcerRechargeRecordDTO;
import com.jpsoft.shinestar.modules.base.entity.CanteenOutsourcerRechargeRecord;
import com.jpsoft.shinestar.modules.base.entity.PersonInfo;
import com.jpsoft.shinestar.modules.base.service.CanteenOutsourcerRechargeRecordService;
import com.jpsoft.shinestar.modules.base.service.PersonInfoService;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.utils.OSSUtil;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import com.jpsoft.shinestar.modules.sys.entity.User;
import com.jpsoft.shinestar.modules.sys.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
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.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/base/canteenOutsourcerRechargeRecord")
@Api(description = "canteenOutsourcerRechargeRecord")
public class CanteenOutsourcerRechargeRecordController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private OSSConfig ossConfig;

    @Autowired
    private CanteenOutsourcerRechargeRecordService canteenOutsourcerRechargeRecordService;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private UserService userService;

    @ApiOperation(value="创建空记录")
    @GetMapping("create")
    public MessageResult<CanteenOutsourcerRechargeRecord> create(){
        MessageResult<CanteenOutsourcerRechargeRecord> msgResult = new MessageResult<>();

        CanteenOutsourcerRechargeRecord canteenOutsourcerRechargeRecord = new CanteenOutsourcerRechargeRecord();

        msgResult.setData(canteenOutsourcerRechargeRecord);
        msgResult.setResult(true);

        return msgResult;
    }
    
    @ApiOperation(value="添加信息")
    @PostMapping("add")
    public MessageResult<Integer> add(@RequestBody CanteenOutsourcerRechargeRecordDTO dto, @RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {

            int affectCount = 0;

            List<PersonInfo> personInfoList = dto.getTags();

            for (PersonInfo personInfo:personInfoList) {
                CanteenOutsourcerRechargeRecord item = new CanteenOutsourcerRechargeRecord();
                item.setPersonId(personInfo.getId());
                item.setRechargeAmount(dto.getRechargeAmount());
                item.setRemark(dto.getRemark());
                item.setId(UUID.randomUUID().toString());
                item.setDelFlag(false);
                item.setCreateBy(subject);
                item.setCreateTime(new Date());

                affectCount += canteenOutsourcerRechargeRecordService.insertAndBalance(item);
            }

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } 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("edit/{personId}")
    public MessageResult<List<PersonInfo>> edit(@PathVariable("personId") String personId){
        MessageResult<List<PersonInfo>> msgResult = new MessageResult<>();

        try {
            List<PersonInfo> personList = new ArrayList<>();

            if(StringUtils.isNotEmpty(personId)){
                if(personId.contains(",")) {
                    String[] personIdArray = personId.split(",");
                    for (String id : personIdArray) {
                        PersonInfo personInfo = personInfoService.get(Long.parseLong(id));
                        personList.add(personInfo);
                    }
                }
                else{
                    PersonInfo personInfo = personInfoService.get(Long.parseLong(personId));
                    personList.add(personInfo);
                }
            }

            msgResult.setResult(true);
            msgResult.setData(personList);

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

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

        return msgResult;
    }


	@ApiOperation(value="删除")
    @PostMapping("delete/{id}")
    public MessageResult<Integer> delete(@PathVariable("id") String id,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            CanteenOutsourcerRechargeRecord canteenOutsourcerRechargeRecord = canteenOutsourcerRechargeRecordService.get(id);
            canteenOutsourcerRechargeRecord.setDelFlag(true);
            canteenOutsourcerRechargeRecord.setUpdateBy(subject);
            canteenOutsourcerRechargeRecord.setUpdateTime(new Date());

            int affectCount = canteenOutsourcerRechargeRecordService.update(canteenOutsourcerRechargeRecord);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } 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")
    public MessageResult<Integer> batchDelete(@RequestBody List<String> idList,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            int affectCount = 0;

            for (String id : idList) {
                CanteenOutsourcerRechargeRecord canteenOutsourcerRechargeRecord = canteenOutsourcerRechargeRecordService.get(id);
                canteenOutsourcerRechargeRecord.setDelFlag(true);
                canteenOutsourcerRechargeRecord.setUpdateBy(subject);
                canteenOutsourcerRechargeRecord.setUpdateTime(new Date());

                affectCount += canteenOutsourcerRechargeRecordService.update(canteenOutsourcerRechargeRecord);
            }

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } 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="列表")
    @RequestMapping(value = "pageList",method = RequestMethod.POST)
    public MessageResult<Object> pageList(
            String personId,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            @RequestParam(value = "exportFlag", defaultValue = "false") Boolean exportFlag,
            @RequestAttribute String 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"));

            searchParams.put("personId", personId);

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

            List<Map> mapList = new ArrayList<>();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

            for (CanteenOutsourcerRechargeRecord item : page) {
                Map<String,Object> map = new HashMap<>();
                String personName="";
                String jobNumber="";
                String createName="";

                PersonInfo personInfo = personInfoService.get(item.getPersonId());
                if (personInfo != null) {
                    personName = personInfo.getName();
                    jobNumber = personInfo.getJobNumber();
                }

                User user = userService.get(item.getCreateBy());
                if (user != null) {
                    createName = user.getRealName();
                }

                map.put("personName",personName);
                map.put("jobNumber",jobNumber);
                map.put("createName",createName);
                map.put("createTime", sdf.format(item.getCreateTime()));
                map.put("cardNumber",item.getCardNumber());
                map.put("remark",item.getRemark());
                map.put("rechargeAmount",item.getRechargeAmount());

                mapList.add(map);
            }

            if(exportFlag) {
                String filePath = exportXls(mapList);
                msgResult.setData(filePath);
            }
            else{
                Map<String, Object> dataMap = PojoUtils.pageWrapper(page);
                dataMap.put("data", mapList);
                msgResult.setData(dataMap);
            }

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


    private String exportXls(List<Map> mapList) throws IOException {
        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<mapList.size();i++){
            Map<String,Object> map = mapList.get(i);

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

            int colIndex = 0;
            row.createCell(colIndex++).setCellValue(i+1);
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("createTime"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("jobNumber"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("personName"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("cardNumber"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("rechargeAmount"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("createName"),""));
            row.createCell(colIndex++).setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("remark"),""));
        }

        ByteArrayOutputStream output = new ByteArrayOutputStream();

        try {
            workbook.write(output);

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

            downloadUrl = OSSUtil.upload(ossConfig,"CanteenOutsourcerRechargeRecord","员工充值记录.xls",input);
        }
        catch (Exception ex){
            logger.error(ex.getMessage(),ex);
        }

        return downloadUrl;
    }
}
