package com.iformall.service.impl;

import java.io.*;
import java.util.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iformall.common.Result;
import com.iformall.common.ResultData;
import com.iformall.domain.po.WxShop;
import com.iformall.enums.*;
import com.iformall.mapper.WxShopMapper;
import com.iformall.service.WxShopService;
import com.iformall.utils.Constant;
import com.iformall.utils.DownFileUtil;
import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.iformall.common.IdWorker;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class WxShopServiceImpl implements WxShopService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
    WxShopMapper wxShopMapper;

    @Override
    public PageInfo<WxShop> listAsPage(WxShop record, Integer pageIndex, Integer pageSize) {
        return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> wxShopMapper.findList(record));
    }

    @Override
    public PageInfo<Map<String,Object>> listMapAsPage(WxShop record, Integer pageIndex, Integer pageSize) {
        PageHelper.startPage(pageIndex, pageSize);
        List<Map<String,Object>> shops = wxShopMapper.findListMap(record);
        PageInfo<Map<String,Object>> pageInfo = new PageInfo<>(shops);
        return pageInfo;
    }

    @Override
    public WxShop getById(Long id) {
        return wxShopMapper.selectByPrimaryKey(id);
    }

    @Override
    public ResultData saveOrUpdate(WxShop record) {
        if (record.getId() == null) {
            final IdWorker idWorker = IdWorker.get();
        	record.setId(idWorker.nextId());
        	record.setStatus(EnumShopStatus.NOT_RENT.getCode());
            Date date = new Date();
            record.setUpdateDate(date);
        	record.setCreateDate(date);
            wxShopMapper.insertSelective(record);
            return new ResultData(Result.SUCCESS,"添加成功");
        } else {
            record.setUpdateDate(new Date());
            wxShopMapper.updateByPrimaryKeySelective(record);
            return new ResultData(Result.SUCCESS,"更新成功");
        }
    }

    @Override
    public void deleteById(Long id) {
        wxShopMapper.deleteByPrimaryKey(id);
    }

    @Override
    public ResultData getbshoplist(String tenantId, String shopNumber) {
        Map<String,Object> params=new HashMap<>();
        params.put("tenantId",tenantId);
        params.put("shopNumber",shopNumber);
        List<Map<String,Object>> list=wxShopMapper.getbshoplist(params);
        return new ResultData(ResultData.SUCCESS,"",list);
    }

    @Override
    public ResultData getMerchantShopByShopId(String tenantId, String shopId) {
        Map<String,Object> params=new HashMap<>();
        params.put("tenantId",tenantId);
        params.put("shopId",shopId);
        Map<String,Object> map=wxShopMapper.getMerchantShopByShopId(params);
        return new ResultData(ResultData.SUCCESS,"",map);
    }

    @Override
    public ResultData hasShopNumber(String tenantId, String shopNumber, Long id, Integer type) {
        WxShop wxShop = new WxShop();
        wxShop.setTenantId(tenantId);
        wxShop.setShopNumber(shopNumber);
        wxShop.setType(type);
        wxShop.setId(id);
        int count = wxShopMapper.hasShopNumber(wxShop);
        return new ResultData(ResultData.SUCCESS, "查询成功", count > 0 ? true : false);
    }

    @Override
    public PageInfo<Map<String, Object>> listShopFromContract(WxShop wxShop, Integer pageIndex, Integer pageSize) {
        PageHelper.startPage(pageIndex, pageSize);
        List<Map<String,Object>> shops = wxShopMapper.listShopFromContract(wxShop);
        PageInfo<Map<String,Object>> pageInfo = new PageInfo<>(shops);
        return pageInfo;
    }

    @Override
    public void exportShop(WxShop wxShop, HttpServletRequest request, HttpServletResponse response) {
        List<Map<String,Object>> shopList = wxShopMapper.findListWithMerchantMap(wxShop);

        SXSSFWorkbook workbook;
        String filepath = Constant.fileDirectory;
        File savefile = new File(filepath);
        if (!savefile.exists()) {
            savefile.mkdirs();
        }
        String filename = UUID.randomUUID() + ".xlsx";
        filepath = filepath + filename;

        try {
            File file = new File(filepath);
            workbook = new SXSSFWorkbook(100);
            String sheetName = EnumRentShopType.SHOP.getCode().equals(wxShop.getType())?"店铺列表":"多经点位列表";
            SXSSFSheet sheetTwo = workbook.createSheet(sheetName);
            Row rowtwo = sheetTwo.createRow(0);

            Cell cell1,cell2,cell3,cell4,cell5,cell6,cell7,cell8,cell9,cell10,cell11;
            if(EnumRentShopType.POINT.getCode().equals(wxShop.getType())){
                Cell cell0 = rowtwo.createCell(0);
                cell0.setCellValue("多经点位类型");
                cell1 = rowtwo.createCell(1);
                cell2 = rowtwo.createCell(2);
                cell3 = rowtwo.createCell(3);
                cell4 = rowtwo.createCell(4);
                cell5 = rowtwo.createCell(5);
                cell6 = rowtwo.createCell(6);
                cell7 = rowtwo.createCell(7);
                cell8 = rowtwo.createCell(8);
                cell9 = rowtwo.createCell(9);
                cell10 = rowtwo.createCell(10);
                cell11 = rowtwo.createCell(11);
            }else{
                cell1 = rowtwo.createCell(0);
                cell2 = rowtwo.createCell(1);
                cell3 = rowtwo.createCell(2);
                cell4 = rowtwo.createCell(3);
                cell5 = rowtwo.createCell(4);
                cell6 = rowtwo.createCell(5);
                cell7 = rowtwo.createCell(6);
                cell8 = rowtwo.createCell(7);
                cell9 = rowtwo.createCell(8);
                cell10 = rowtwo.createCell(9);
                cell11 = rowtwo.createCell(10);
            }

            cell1.setCellValue(EnumRentShopType.SHOP.getCode().equals(wxShop.getType())?"商铺号":"多经点位号");
            cell2.setCellValue("租赁商户");
            cell3.setCellValue("楼层");
            cell4.setCellValue("楼座");
            cell5.setCellValue("建筑面积(㎡)");
            cell6.setCellValue("计租面积(㎡)");
            cell7.setCellValue(EnumRentShopType.SHOP.getCode().equals(wxShop.getType())?"商铺状态":"多经点位状态");
            // 商户信息
            cell8.setCellValue("经营业态");
            cell9.setCellValue("品牌");
            cell10.setCellValue("负责人");
            cell11.setCellValue("负责人电话");

            for (int i = 0; i < shopList.size(); i++) {
                rowtwo = sheetTwo.createRow(i + 1);
                Map<String,Object> entity = shopList.get(i);

                if(EnumRentShopType.POINT.getCode().equals(wxShop.getType())){
                    Cell cell0 = rowtwo.createCell(0);
                    if (entity.get("pointType") != null) {
                        cell0.setCellValue(EnumPointType.getEnum((Integer) entity.get("pointType")).getMessage());
                    }
                    cell1 = rowtwo.createCell(1);
                    cell2 = rowtwo.createCell(2);
                    cell3 = rowtwo.createCell(3);
                    cell4 = rowtwo.createCell(4);
                    cell5 = rowtwo.createCell(5);
                    cell6 = rowtwo.createCell(6);
                    cell7 = rowtwo.createCell(7);
                    cell8 = rowtwo.createCell(8);
                    cell9 = rowtwo.createCell(9);
                    cell10 = rowtwo.createCell(10);
                    cell11 = rowtwo.createCell(11);
                }else{
                    cell1 = rowtwo.createCell(0);
                    cell2 = rowtwo.createCell(1);
                    cell3 = rowtwo.createCell(2);
                    cell4 = rowtwo.createCell(3);
                    cell5 = rowtwo.createCell(4);
                    cell6 = rowtwo.createCell(5);
                    cell7 = rowtwo.createCell(6);
                    cell8 = rowtwo.createCell(7);
                    cell9 = rowtwo.createCell(8);
                    cell10 = rowtwo.createCell(9);
                    cell11 = rowtwo.createCell(10);
                }
                cell1.setCellValue((String)entity.get("shopNumber"));
                cell2.setCellValue((String)entity.get("merchantName"));
                cell3.setCellValue((String)entity.get("floor"));
                cell4.setCellValue((String)entity.get("building"));
                cell5.setCellValue((String)entity.get("buildArea"));
                cell6.setCellValue((String)entity.get("operationArea"));
                if(entity.get("status") != null) {
                    if(EnumShopStatus.RENT.getCode().equals(entity.get("status"))) {
                        cell7.setCellValue("已出租");
                        // 查询商户信息
                        cell8.setCellValue((String)entity.get("title"));
                        cell9.setCellValue((String)entity.get("brand"));
                        cell10.setCellValue((String)entity.get("link_person"));
                        cell11.setCellValue((String)entity.get("link_phone"));
                    }else{
                        cell7.setCellValue("未出租");
                    }
                }
            }

            FileOutputStream fileOut = new FileOutputStream(file);
            workbook.write(fileOut);
            fileOut.close();
            workbook.close();
            String name = EnumRentShopType.SHOP.getCode().equals(wxShop.getType())?"店铺列表":"多经点位列表";
            DownFileUtil.downFile(filepath,name+".xlsx",response, request);
            FileUtils.forceDelete(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
