package com.iformall.controller.market;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageInfo;
import com.iformall.annotation.SystemControllerLog;
import com.iformall.common.ErrorCode;
import com.iformall.common.Result;
import com.iformall.common.ResultData;
import com.iformall.controller.base.BaseController;
import com.iformall.domain.po.base.BaseEntity;
import com.iformall.domain.po.WxCampaign;
import com.iformall.domain.po.WxCoupon;
import com.iformall.domain.po.WxCouponChannel;
import com.iformall.domain.vo.WxCouponChannelVo;
import com.iformall.enums.EnumCampaignStatus;
import com.iformall.enums.EnumCampaignType;
import com.iformall.enums.EnumCouponChannelType;
import com.iformall.enums.EnumCouponStatus;
import com.iformall.service.WxCampaignService;
import com.iformall.service.WxCouponChannelService;
import com.iformall.service.WxCouponService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("wxCampaign")
@Api(description = "促销和banner接口")
public class WxCampaignController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxCampaignService wxCampaignService;

    @Autowired
    WxCouponService wxCouponService;

    @Autowired
    private WxCouponChannelService wxCouponChannelService;

    @ApiOperation("分页列表接口")
    @GetMapping("list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query", required = true)})
    @SystemControllerLog(description = "宣传页-列表")
    public ResultData list(@ModelAttribute WxCampaign wxCampaign, Integer pageNum, Integer pageSize) {
        logger.debug("[" + getIpAddr() + "] WxCampaignController::list");
        if (null == wxCampaign) wxCampaign = new WxCampaign();
        if (wxCampaign.getStatus() != null && wxCampaign.getStatus() == -1) {
            wxCampaign.setStatus(null);
        }
        wxCampaign.setTenantId(getTenantId());
        wxCampaign.setSortColumns(BaseEntity.SortField.CreateTime_DESC,BaseEntity.SortField.Id_DESC);
        final PageInfo<WxCampaign> page = wxCampaignService.listAsPage(wxCampaign, pageNum, pageSize);
        return new ResultData(page);
    }

    @ApiOperation("新增接口")
    @PostMapping("add")
    @SystemControllerLog(description = "宣传页-新增")
    public ResultData add(@RequestBody WxCampaign wxCampaign) {
        logger.debug("[" + getIpAddr() + "] WxCampaignController::add");
        if (StringUtils.isNotBlank(wxCampaign.getCouponIds())) {
            String[] arys = wxCampaign.getCouponIds().split(",");
            wxCampaign.setCouponIds(JSON.toJSONString(arys));
        } else {
            wxCampaign.setCouponIds(JSONArray.toJSONString(new String[0]));
        }
        wxCampaign.setStatus(EnumCampaignStatus.STATUS_THROW_IN.getCode());
        wxCampaign.setTenantId(getTenantId());
        wxCampaignService.saveOrUpdate(wxCampaign);
        return new ResultData();
    }

    @ApiOperation(value = "新增接口-小程序路径", notes = "produceType,produceId,pagePath,pageScene必填")
    @PostMapping("addByPath")
    @SystemControllerLog(description = "宣传页-新增")
    public ResultData addByPath(@RequestBody WxCampaign wxCampaign) {
        logger.debug("[" + getIpAddr() + "] WxCampaignController::addByPath");
        wxCampaign.setStatus(EnumCampaignStatus.STATUS_THROW_IN.getCode());
        wxCampaign.setTenantId(getTenantId());
        wxCampaignService.addForPath(wxCampaign);
        return new ResultData();
    }

    @ApiOperation("根据id更新接口")
    @PostMapping("update")
    @SystemControllerLog(description = "宣传页-id更新")
    public ResultData update(@RequestBody WxCampaign wxCampaign) {
        logger.debug("[" + getIpAddr() + "] WxCampaignController::update");

        if (StringUtils.isNotBlank(wxCampaign.getCouponIds())) {
            String[] arys = wxCampaign.getCouponIds().split(",");
            wxCampaign.setCouponIds(JSON.toJSONString(arys));
        } else {
            wxCampaign.setCouponIds(JSONArray.toJSONString(new String[0]));
        }
        return wxCampaignService.saveOrUpdate(wxCampaign);
    }

    @ApiOperation("根据id更新接口")
    @PostMapping("updateStatus")
    @SystemControllerLog(description = "宣传页-更新状态")
    public ResultData updateStatus(@RequestBody WxCampaign wxCampaign) {
        logger.debug("[" + getIpAddr() + "] WxCampaignController::updateStatus");
        WxCampaign campaign = wxCampaignService.getById(wxCampaign.getId());
        // check coupon 状态
        if (campaign.getType().equals(EnumCampaignType.STABLE.getCode())) {
            if (campaign.getStatus().equals(EnumCampaignStatus.STATUS_THROW_IN.getCode())
                    && !wxCampaign.getStatus().equals(EnumCampaignStatus.STATUS_TAKE_OFFF.getCode())) {
                // 宣传页 - 下架不检查状态
                List<String> ids = JSONArray.parseArray(campaign.getCouponIds(), String.class);
                for (String couponIdStr : ids) {
                    Long couponId = Long.parseLong(couponIdStr);

                    WxCoupon wxCoupon = wxCouponService.getById(couponId);
                    if (wxCoupon == null) {
                        return new ResultData(ErrorCode.COUPON_IS_EMPTY);
                    }
                    if (wxCoupon.getStatus() != EnumCouponStatus.COUPON_STATUS_THROW_IN.getCode()) {
                        return new ResultData(ErrorCode.COUPON_IS_TAKE_OFF);
                    }
                    if (wxCoupon.getValidEndDate() != null && wxCoupon.getValidEndDate().before(new Date())) {
                        return new ResultData(ErrorCode.COUPON_IS_TAKE_OFF);
                    }
                }
            }
        }
        return wxCampaignService.updateStatus(wxCampaign);
    }

    @ApiOperation("根据id删除接口")
    @GetMapping("/del")
    @ApiImplicitParam(name = "id", value = "id", dataType = "Long", paramType = "query", required = true)
    @SystemControllerLog(description = "宣传页-删除")
    public ResultData delete(Long id) {
        logger.debug("[" + getIpAddr() + "] WxCampaignController::delete");
        wxCampaignService.deleteById(id);
        return new ResultData(Result.SUCCESS, "删除成功", null);
    }

    @ApiOperation("根据id查询接口")
    @GetMapping("/findById")
    @ApiImplicitParam(name = "id", value = "id", dataType = "Long", paramType = "query", required = true)
    @SystemControllerLog(description = "宣传页-查询")
    public ResultData findById(Long id) {
        logger.debug("[" + getIpAddr() + "] WxCampaignController::findById");
        WxCampaign wxCampaign = wxCampaignService.getById(id);
        if (wxCampaign != null) {
            WxCouponChannel wxCouponChannel = new WxCouponChannel();
            wxCouponChannel.setTenantId(getTenantId());
            wxCouponChannel.setTargetAd(EnumCouponChannelType.COUPON_CHANNEL_ID_CAMPAIN.getCode());
            wxCouponChannel.setSubTargetId(wxCampaign.getId());
            wxCouponChannel.setStatus(EnumCampaignStatus.STATUS_THROW_IN.getCode());
            List<WxCouponChannelVo> couponList = wxCouponChannelService.listVo(wxCouponChannel);
            wxCampaign.setCoupons(couponList);
        }
        return new ResultData(Result.SUCCESS, "查询成功", wxCampaign);
    }

    @ApiOperation("调整顺序")
    @GetMapping("/move")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sourceId", value = "", dataType = "Long", paramType = "query", required = true),
            @ApiImplicitParam(name = "targetId", value = "", dataType = "Long", paramType = "query", required = true)})
    @SystemControllerLog(description = "宣传页-调整顺序")
    public ResultData move(Long sourceId, Long targetId) {
        logger.debug("[" + getIpAddr() + "] WxCampaignController::move");
        WxCampaign source = wxCampaignService.getById(sourceId);
        WxCampaign target = wxCampaignService.getById(targetId);
        if (source == null || target == null) {
            return new ResultData(Result.ERROR, "调整顺序失败", null);
        }
        int temp = source.getSortNum();
        source.setSortNum(target.getSortNum());
        target.setSortNum(temp);
        wxCampaignService.saveOrUpdate(source);
        wxCampaignService.saveOrUpdate(target);
        return new ResultData(Result.SUCCESS, "调整顺序成功", null);
    }


}
