package com.sv.service.oms;

import com.github.pagehelper.PageHelper;
import com.sv.dto.oms.VenueOmsDTO;
import com.sv.entity.Platform;
import com.sv.entity.Venue;
import com.sv.entity.VenueImage;
import com.sv.mapper.VenueMapper;
import com.sv.service.common.OSSClientUtil;
import com.sv.service.common.PlatformService;
import com.ydd.framework.core.common.Pagination;
import com.ydd.framework.core.common.utils.GeoHashUtils;
import com.ydd.framework.core.entity.enums.StatusEnum;
import com.ydd.framework.core.service.CacheService;
import com.ydd.framework.core.service.impl.BaseServiceImpl;
import com.ydd.framework.core.service.impl.WxXCXService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.InputStream;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * Service - 场馆
 *
 * @author zuojie.Liang
 * @since 2018-08-02
 */
@Service("VenueServiceOms")
@Transactional(readOnly = true)
public class VenueService extends BaseServiceImpl {

    private final Logger logger = LoggerFactory.getLogger(VenueService.class);

    @Resource
    private VenueMapper venueMapper;

    @Resource
    private VenueImageService venueImageService;
    @Resource
    private VenuePriceService venuePriceService;

    @Resource
    private PlatformService platformService;

    @Resource
    private OSSClientUtil ossClientUtil;

    @Resource
    private CacheService cacheService;

    /**
     * 创建场馆
     *
     * @param venue 场馆
     */
    @Transactional
    public void save(Venue venue, String[] venueImage) {
        venue.setGeoHash(GeoHashUtils.encodeHash(venue.getLongitude(), venue.getLatitude()));
        setVenueBusinessTime(venue);
        if (venue.getId() != null && venue.getId() > 0) {
            // 更新
            venueMapper.update(venue);
            venueImageService.deleteByVenueId(venue.getId());
        } else {
            // 新建
            venueMapper.insert(venue);
        }
        for (int i = 0; i < venueImage.length; i++) {
            VenueImage vi = new VenueImage();
            vi.setUrl(venueImage[i]);
            vi.setVeneuType(venue.getType());
            vi.setVenueId(venue.getId());
            venueImageService.save(vi);
        }

        // 保存场馆对应的时间段
        venuePriceService.saveVenuePrice(venue.getPriceListStr(), venue.getId(), venue.getType(), venue.getPlatformId());
    }

    private void setVenueBusinessTime(Venue venue) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("HH:mm");
        venue.setBusinessTime(getWeek(venue.getBusinessStartDate()) + "至" + getWeek(venue.getBusinessEndDate()) + " " + df.format(venue.getBusinessStartTime()) + "~" + df.format(venue.getBusinessEndTime()));
    }

    private String getWeek(Integer week) {
        String w = null;
        switch (week) {
            case 1:
                w = "周一";
                break;
            case 2:
                w = "周二";
                break;
            case 3:
                w = "周三";
                break;
            case 4:
                w = "周四";
                break;
            case 5:
                w = "周五";
                break;
            case 6:
                w = "周六";
                break;
            case 7:
                w = "周日";
                break;
        }
        return w;
    }

    /**
     * 更新场馆
     *
     * @param venue 场馆
     */
    @Transactional
    public void update(Venue venue) {
        venueMapper.update(venue);
    }

    /**
     * 删除场馆
     *
     * @param id 编号
     * @return 删除数量
     */
    @Transactional
    public Integer delete(Integer id) {
        if (id == null || id <= 0) {
            return 0;
        }
        return venueMapper.delete(id);
    }

    /**
     * 删除场馆
     *
     * @param ids 编号数组
     * @return 删除数量
     */
    @Transactional
    public Integer deleteByIds(Integer[] ids) {
        if (ids == null || ids.length == 0) {
            return 0;
        }
        return venueMapper.deleteByIds(ids);
    }

    /**
     * 查询场馆
     *
     * @param id 编号
     * @return 场馆
     */
    public VenueOmsDTO findById(Integer id) {
        return venueMapper.findOmsDTOById(id);
    }

    /**
     * 查询场馆
     *
     * @param pagination 分页信息
     * @return 分页结果
     */
    public Pagination findPage(Pagination pagination) {
        PageHelper.startPage(pagination.getPage(), pagination.getPageSize());
        PageHelper.orderBy("id desc");
        pagination.setQueryResult(venueMapper.findAll());
        return pagination;
    }

    @Transactional
    public void updateStatus(Integer id, Byte status) {
        if (status == null) {
            status = StatusEnum.DISABLE.value;
        }
        venueMapper.updateStatus(id, status);
    }

    public List<Venue> findByVenueType(Integer type) {
        return venueMapper.findByType(type);
    }

    public List<Venue> findAlls() {
        return venueMapper.findAlls();
    }

    @Transactional(rollbackFor = Exception.class)
    public void generateCodeUrl(Integer venueId) {
        Venue venue = findById(venueId);
        Platform platform = platformService.findById(1);
        InputStream inputStream = WxXCXService.getNewInstance(platform.getAppId(), platform.getSecret(), "wx_xcx_token", cacheService).getXCXQrCode("pages/basketballGym/index", venueId.toString(), "1280");
        String url = ossClientUtil.uploadImg(inputStream, "qrcode.png");
        venue.setCodeUrl(url);
        venueMapper.update(venue);
    }

    @Transactional(rollbackFor = Exception.class)
    public void clearNumber(Integer id) {
        venueMapper.updateNumber(0, id);
    }
}

