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

import com.github.pagehelper.Page;
import com.jpsoft.shinestar.config.OSSConfig;
import com.jpsoft.shinestar.modules.base.entity.*;
import com.jpsoft.shinestar.modules.base.service.CompanyInfoService;
import com.jpsoft.shinestar.modules.base.service.ParkingMerchantService;
import com.jpsoft.shinestar.modules.base.service.ParkingRecordService;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.base.service.ParkingCouponService;
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.DataDictionaryService;
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.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *商户优惠卷
 * sz
 */
@RestController
@RequestMapping("/base/parkingCoupon")
@Api(description = "parkingCoupon")
public class ParkingCouponController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ParkingCouponService parkingCouponService;
    @Autowired
    private ParkingMerchantService parkingMerchantService;
    @Autowired
    private ParkingRecordService parkingRecordService;
    @Autowired
    private CompanyInfoService companyInfoService;
    @Autowired
    private DataDictionaryService dataDictionaryService;
    @Autowired
    private OSSConfig ossConfig;
    @Autowired
    private UserService userService;

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

        ParkingCoupon parkingCoupon = new ParkingCoupon();

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

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

        try {
            parkingCoupon.setId(UUID.randomUUID().toString());
            parkingCoupon.setDelFlag(false);
            parkingCoupon.setCreateBy(subject);
            parkingCoupon.setCreateTime(new Date());
            
            int affectCount = parkingCouponService.insert(parkingCoupon);

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

        try {
            ParkingCoupon parkingCoupon = parkingCouponService.get(id);

            if (parkingCoupon != null) {
                msgResult.setResult(true);
                msgResult.setData(parkingCoupon);
            } 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<ParkingCoupon> update(@RequestBody ParkingCoupon parkingCoupon,@RequestAttribute String subject){
        MessageResult<ParkingCoupon> msgResult = new MessageResult<>();

        try {
            parkingCoupon.setUpdateBy(subject);
            parkingCoupon.setUpdateTime(new Date());
            
            int affectCount = parkingCouponService.update(parkingCoupon);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(parkingCoupon);
            } 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<Integer> delete(@PathVariable("id") String id,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            ParkingCoupon parkingCoupon = parkingCouponService.get(id);
            parkingCoupon.setDelFlag(true);
            parkingCoupon.setUpdateBy(subject);
            parkingCoupon.setUpdateTime(new Date());

            int affectCount = parkingCouponService.update(parkingCoupon);

            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) {
                ParkingCoupon parkingCoupon = parkingCouponService.get(id);
                parkingCoupon.setDelFlag(true);
                parkingCoupon.setUpdateBy(subject);
                parkingCoupon.setUpdateTime(new Date());

                affectCount += parkingCouponService.update(parkingCoupon);
            }

            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<Map> pageList(
            @RequestParam(value="id",defaultValue="") String id,
            @RequestParam(value="merchantName",defaultValue="") String merchantName,
            @RequestParam(value="carNum",defaultValue="") String carNum,
            @RequestParam(value="companyId",defaultValue="") String companyId,
            @RequestParam(value="useStatus",defaultValue="") String useStatus,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date verifyStartTime,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date verifyEndTime,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            @RequestAttribute String subject){

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

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

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

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

        if (StringUtils.isNotEmpty(id)) {
            searchParams.put("id","%" + id + "%");
        }

        if (StringUtils.isNotEmpty(merchantName)) {
            searchParams.put("merchantName","%" + merchantName + "%");
        }

        if (StringUtils.isNotEmpty(carNum)) {
            searchParams.put("carNum","%" + carNum + "%");
        }

        if (StringUtils.isNotEmpty(companyId)) {
            searchParams.put("companyId",companyId);
        }else{
            //当前用户ID
            User user = userService.get(subject);
            if (!userService.hasRole(subject,"SYSADMIN")) {
                CompanyInfo companyInfo = companyInfoService.get(user.getCompanyId());

                searchParams.put("parentCompanyCode", companyInfo.getCode() + "%");
            }
        }

        if (verifyStartTime!=null) {
            searchParams.put("verifyStartTime", verifyStartTime);
        }
        if (verifyEndTime!=null) {
            searchParams.put("verifyEndTime", verifyEndTime);
        }

        if (StringUtils.isNotEmpty(useStatus)) {
            searchParams.put("useStatus",useStatus);
        }

        Page<ParkingCoupon> page = parkingCouponService.pageSearch(searchParams,pageIndex,pageSize,true,sortList);
        //Page<ParkingCouponDTO> pageDTO = PojoUtils.convertPage(page, ParkingCouponDTO.class);
        //for(ParkingCoupon pc : page.getResult()){
           // pc.setTypeName(dataDictionaryService.findNameByCatalogNameAndValue("优惠券类型",pc.getType()));

//            if(StringUtils.isNotEmpty(dto.getMerchantId())) {
//                ParkingMerchant pm = parkingMerchantService.get(dto.getMerchantId());
//                if(pm == null){
//                    continue;
//                }
//                CompanyInfo ci = companyInfoService.get(pm.getCompanyId());
//                if(ci != null) {
//                    dto.setCompanyId(ci.getId());
//                    dto.setCompanyName(ci.getName());
//                }
//            }
//
//            if(StringUtils.isNotEmpty(dto.getParkingRecordId())) {
//                ParkingRecord pr = parkingRecordService.get(dto.getParkingRecordId());
//                if(pr != null) {
//                    dto.setCarNum(pr.getCarNum());
//                    dto.setInParkingTime(pr.getInParkingTime());
//                    dto.setOutParkingTime(pr.getOutParkingTime());
//                }
//            }
        //}

        msgResult.setResult(true);
        msgResult.setData(PojoUtils.pageWrapper(page));

        return msgResult;
    }

    @ApiOperation(value="导出报表停车劵使用明细")
    @RequestMapping(value = "exportXls",method = RequestMethod.POST)
    public MessageResult<String> exportXls(
            @RequestParam(value="id",defaultValue="") String id,
            @RequestParam(value="merchantName",defaultValue="") String merchantName,
            @RequestParam(value="carNum",defaultValue="") String carNum,
            @RequestParam(value="companyId",defaultValue="") String companyId,
            @RequestParam(value="useType",defaultValue="") String useStatus,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date verifyStartTime,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date verifyEndTime,
            @RequestParam(value="pageIndex",defaultValue="0") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="100000") int pageSize,
            @RequestAttribute String subject){

        //当前用户ID
        System.out.println(subject);
        MessageResult<String> msgResult = new MessageResult<>();
        try {
            Map<String, Object> searchParams = new HashMap<>();

            //User user = userService.get(subject);
            //CompanyInfo companyInfo = companyInfoService.get(user.getCompanyId());

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

            if (StringUtils.isNotEmpty(id)) {
                searchParams.put("id","%" + id + "%");
            }

            if (StringUtils.isNotEmpty(merchantName)) {
                searchParams.put("merchantName","%" + merchantName + "%");
            }

            if (StringUtils.isNotEmpty(carNum)) {
                searchParams.put("carNum","%" + carNum + "%");
            }

            if (StringUtils.isNotEmpty(companyId)) {
                searchParams.put("companyId",companyId);
            }

            if (verifyStartTime!=null) {
                searchParams.put("verifyStartTime", verifyStartTime);
            }
            if (verifyEndTime!=null) {
                searchParams.put("verifyEndTime", verifyEndTime);
            }

            if (StringUtils.isNotEmpty(useStatus)) {
                searchParams.put("useStatus",useStatus);
            }

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


            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet();
            //表头
            HSSFRow rowTitle = sheet.createRow(0);
            HSSFCell cellTitle1 = rowTitle.createCell(0);
            cellTitle1.setCellValue("序号");

            HSSFCell cellTitle2 = rowTitle.createCell(1);
            cellTitle2.setCellValue("车牌号码");
            sheet.setColumnWidth(1, 22 * 256);

            HSSFCell cellTitle3 = rowTitle.createCell(2);
            cellTitle3.setCellValue("所属物业");
            sheet.setColumnWidth(2, 22 * 256);

            HSSFCell cellTitle4 = rowTitle.createCell(3);
            cellTitle4.setCellValue("登记商户");
            sheet.setColumnWidth(3, 22 * 256);

            HSSFCell cellTitle5 = rowTitle.createCell(4);
            cellTitle5.setCellValue("使用状态");
            sheet.setColumnWidth(4, 22 * 256);

            HSSFCell cellTitle6 = rowTitle.createCell(5);
            cellTitle6.setCellValue("折扣卷金额(元)");
            sheet.setColumnWidth(5, 22 * 256);

            HSSFCell cellTitle7 = rowTitle.createCell(6);
            cellTitle7.setCellValue("入场时间");
            sheet.setColumnWidth(6, 22 * 256);

            HSSFCell cellTitle8 = rowTitle.createCell(7);
            cellTitle8.setCellValue("出场时间");
            sheet.setColumnWidth(7, 22 * 256);

            HSSFCell cellTitle9 = rowTitle.createCell(8);
            cellTitle9.setCellValue("发放时间");
            sheet.setColumnWidth(8, 22 * 256);

            HSSFCell cellTitle10 = rowTitle.createCell(9);
            cellTitle10.setCellValue("核销时间");
            sheet.setColumnWidth(9, 22 * 256);

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

            for(int i=0; i<page.size(); i++){
                ParkingCoupon pc = page.get(i);

                HSSFRow rowContent = sheet.createRow(i + 1);
                HSSFCell cellContent1 = rowContent.createCell(0);
                cellContent1.setCellValue(i+1);

                //车牌号码
                HSSFCell cellContent2 = rowContent.createCell(1);
                if (pc.getCarNum() != null) {
                    cellContent2.setCellValue(pc.getCarNum());
                }
                //所属物业
                HSSFCell cellContent3 = rowContent.createCell(2);
                if (pc.getCompanyName() != null) {
                    cellContent3.setCellValue(pc.getCompanyName());
                }
                //登记商户
                HSSFCell cellContent4 = rowContent.createCell(3);
                if (pc.getMerchantName() != null) {
                    cellContent4.setCellValue(pc.getMerchantName());
                }
                //使用状态
                HSSFCell cellContent5 = rowContent.createCell(4);
                if (pc.getUseStatus() != null) {
                    cellContent5.setCellValue(pc.getUseStatus()?"是":"否");
                }
                //折扣卷金额(元)
                HSSFCell cellContent6 = rowContent.createCell(5);
                if (pc.getReduce() != null) {
                    cellContent6.setCellValue(pc.getReduce());
                }
                //入场时间
                HSSFCell cellContent7 = rowContent.createCell(6);
                if (pc.getInParkingTime() != null) {
                    cellContent7.setCellValue(sdf.format(pc.getInParkingTime()));
                }
                //出场时间
                HSSFCell cellContent8 = rowContent.createCell(7);
                if (pc.getOutParkingTime() != null) {
                    cellContent8.setCellValue(sdf.format(pc.getOutParkingTime()));
                }
                //发放时间
                HSSFCell cellContent9 = rowContent.createCell(8);
                if (pc.getCreateTime() != null) {
                    cellContent9.setCellValue(sdf.format(pc.getCreateTime()));
                }
                //核销时间
                HSSFCell cellContent10 = rowContent.createCell(9);
                if (pc.getVerifyTime() != null) {
                    cellContent10.setCellValue(sdf.format(pc.getVerifyTime()));
                }
            }

            //todo 将wb保存到oss
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            workbook.write(output);

            byte[] buffer = output.toByteArray();
            ByteArrayInputStream input = new ByteArrayInputStream(buffer);
            //格式化
            SimpleDateFormat sim = new SimpleDateFormat("yyyyMMddHHmmss");
            String fileName = "导出停车劵使用明细" + sim.format(new Date()) + ".xls";
            String downloadUrl = OSSUtil.upload(ossConfig, "import", fileName, input);

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

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


        return msgResult;
    }
}
