package com.iformall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iformall.common.ErrorCode;
import com.iformall.common.IdWorker;
import com.iformall.common.Result;
import com.iformall.common.ResultData;
import com.iformall.domain.po.WxMerchantShop;
import com.iformall.domain.po.WxRentContract;
import com.iformall.domain.po.WxShop;
import com.iformall.domain.vo.WxNotRentShopVo;
import com.iformall.domain.vo.WxShopVo;
import com.iformall.enums.*;
import com.iformall.mapper.WxMerchantShopMapper;
import com.iformall.mapper.WxRentContractMapper;
import com.iformall.mapper.WxShopMapper;
import com.iformall.service.ExcelService;
import com.iformall.service.WxShopService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.*;

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

    @Autowired
    WxMerchantShopMapper wxMerchantShopMapper;

    @Autowired
    ExcelService excelService;

    @Autowired
    WxRentContractMapper wxRentContractMapper;

    @Override
    public List<WxShop> selectList(QueryWrapper<WxShop> queryWrapper) {
        return wxShopMapper.selectList(queryWrapper) ;
    }

    @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 PageInfo<Map<String, Object>> notRentListMapAsPage(WxShop record, Integer pageIndex, Integer pageSize) {
        PageHelper.startPage(pageIndex, pageSize);
        List<Map<String,Object>> shops = wxShopMapper.notRentListMapAsPage(record);
        PageInfo<Map<String,Object>> pageInfo = new PageInfo<>(shops);
        return pageInfo;
    }

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

    public List<WxShop> getByIds(Collection<? extends Serializable> ids) {
        if(CollectionUtils.isEmpty(ids)) {
            return new ArrayList<>() ;
        }
        return wxShopMapper.selectBatchIds(ids) ;
    }

    @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);
        	//若计租面积无值 则采用建筑面积
            if (StringUtils.isBlank(record.getOperationArea()) || "0".equals(record.getOperationArea())) {
                record.setOperationArea(record.getBuildArea());
            }
            wxShopMapper.insert(record);
            return new ResultData(Result.SUCCESS,"添加成功");
        } else {
            record.setUpdateDate(new Date());
            wxShopMapper.updateById(record);
            return new ResultData(Result.SUCCESS,"更新成功");
        }
    }

    @Override
    public ResultData deleteById(Long id, Integer isAdmin) {
        //1、已出租不让删除
        WxShop wxShop = wxShopMapper.selectById(id);
        if (wxShop == null) {
            return new ResultData(ErrorCode.SHOP_IS_NOT_FOUND);
        }
        if (wxShop.getStatus().equals(EnumShopStatus.RENT.getCode())) {
            return new ResultData(ErrorCode.SHOP_BAN_DELETED);
        }
        //2、是否关联过商户
        WxMerchantShop wxMerchantShop = new WxMerchantShop();
        wxMerchantShop.setShopId(wxShop.getId());
        List<WxMerchantShop> wxMerchantShops = wxMerchantShopMapper.selectList(new QueryWrapper(wxMerchantShop));

        if (isAdmin.equals(EnumUserAdmin.ADMIN.getCode())) {
            //3、合同 两种 都要查一下 存在时不能删除
            WxRentContract wxRentContract = new WxRentContract();
            wxRentContract.setShopId(wxShop.getId());
            wxRentContract.setTenantId(wxShop.getTenantId());
            long count = 0;
            if (wxShop.getType().equals(EnumRentShopType.SHOP.getCode())) {
                count = wxRentContractMapper.selectRentContractByShopId(wxRentContract).parallelStream()
                        .filter(r -> !r.getStatus().equals(EnumRentContractStatus.SIGNED_RENT_UNPAID.getCode()) &&
                                !r.getStatus().equals(EnumRentContractStatus.RENT_PAID.getCode()) &&
                                !r.getStatus().equals(EnumRentContractStatus.CONTRACT_END_SOON.getCode())).count();
            } else {
                List<WxRentContract> list = wxRentContractMapper.selectList(new QueryWrapper(wxRentContract));
                count = list.stream().filter(r -> !r.getStatus().equals(EnumRentContractStatus.SIGNED_RENT_UNPAID.getCode()) &&
                        !r.getStatus().equals(EnumRentContractStatus.RENT_PAID.getCode()) &&
                        !r.getStatus().equals(EnumRentContractStatus.CONTRACT_END_SOON.getCode())).count();
            }
            if (count > 0) {
                return new ResultData(ErrorCode.SHOP_CONTRACT_HAS_CONNECT);
            }
        }
        //有关联过商户必须是管理员才能删除
        int count = wxMerchantShops.size();
        if (count > 0) {
            if (!isAdmin.equals(EnumUserAdmin.ADMIN.getCode())) {
                return new ResultData(ErrorCode.SHOP_DELETED_BY_ADMIN);
            }
            //更新标记
            wxShop.setIsDel(EnumDelStatus.DEL.getCode());
            wxShopMapper.updateById(wxShop);
            //关联表
            for (int i = 0; i < count; i++) {
                WxMerchantShop updateMerchantShop = wxMerchantShops.get(i);
                updateMerchantShop.setIsDel(EnumDelStatus.DEL.getCode());
                wxMerchantShopMapper.updateById(updateMerchantShop);
            }
        } else {
            //无关联商铺直接删除
            wxShopMapper.deleteById(id);
        }
        return new ResultData(Result.SUCCESS, "删除成功");
    }

    @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<WxShopVo> list = wxShopMapper.findListWithMerchantMap(wxShop);
        String name = EnumRentShopType.SHOP.getCode().equals(wxShop.getType())?"店铺列表":"多经点位列表";
        excelService.exportExcel(list, null, name, WxShopVo.class, name + ".xlsx", response, false);
    }

    @Override
    public void exportNotRentShop(WxShop wxShop, HttpServletRequest request, HttpServletResponse response) {
        wxShop.setStatus(EnumShopStatus.NOT_RENT.getCode());
        List<Map<String,Object>> shops = wxShopMapper.notRentListMapAsPage(wxShop);
        List<WxNotRentShopVo> notRentShopVoList = new ArrayList<>();
        for (Map<String,Object> m:shops) {
            WxNotRentShopVo notRentShopVo = new WxNotRentShopVo();
            notRentShopVo.setBuildArea(((Long)m.get("buildArea")).toString());
            notRentShopVo.setBuilding(((String)m.get("building")));
            notRentShopVo.setFloor((String)m.get("floor"));
            notRentShopVo.setFreeDay((Long) m.get("freeDay"));
            notRentShopVo.setOperationArea(((Long) m.get("operationArea")).toString());
            Integer point = (Integer) m.get("type");
            if(point != null){
                notRentShopVo.setPointType(EnumRentShopType.getEnum(point).getMessage());
            }
            notRentShopVo.setShopNumber((String) m.get("shopNumber"));
            notRentShopVoList.add(notRentShopVo);
        }
        String name = "未出租商铺列表";
        excelService.exportExcel(notRentShopVoList, null, name, WxNotRentShopVo.class, name + ".xlsx", response, false);
    }
}
