package com.kmall.admin.controller.mk.store;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.ImmutableBiMap;
import com.kmall.admin.entity.mk.store.MkStoreTicketDiscountEntity;
import com.kmall.admin.service.mk.store.MkStoreTicketDiscountService;
import com.kmall.admin.utils.ParamUtils;
import com.kmall.common.constant.Dict;
import com.kmall.common.utils.*;
import com.kmall.common.utils.file.FileUploadUtil;
import com.kmall.common.utils.wechat.AccessToken;
import com.kmall.manager.manager.pay.wxpay.WxPayPropertiesBuilder;
import com.kmall.manager.manager.wechat.wxtemplate.WxTemplateUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * 门店优惠券活动Controller
 *
 * @author emato
 * @email admin@qhdswl.com
 * @date 2019-05-07 16:06:28
 */
@Controller
@RequestMapping("mkstoreticketdiscount")
public class MkStoreTicketDiscountController {
    @Autowired
    private MkStoreTicketDiscountService mkStoreTicketDiscountService;

    /**
     * 查看列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("mkstoreticketdiscount:list")
    @ResponseBody
    public R list(@RequestParam Map<String, Object> params) {
        ParamUtils.setQueryPowerByRoleType(params, "storeId", "merchSn", "thirdPartyMerchCode");
        ParamUtils.setName(params, "name");
        //查询列表数据
        Query query = new Query(params);

        List<MkStoreTicketDiscountEntity> mkStoreTicketDiscountList = mkStoreTicketDiscountService.queryList(query);
        int total = mkStoreTicketDiscountService.queryTotal(query);
        for (MkStoreTicketDiscountEntity discountEntity : mkStoreTicketDiscountList) {
            if(discountEntity.getEffectTimeType().equalsIgnoreCase(Dict.effectTimeType.item_00.getItem())){
                String startDate = DateUtils.format(discountEntity.getFixBegTime(), DateUtils.DATE_PATTERN);
                String endDate = DateUtils.format(discountEntity.getFixEndTime(), DateUtils.DATE_PATTERN);
                String inValidDate = startDate + " - " + endDate;
                discountEntity.setInValidTime(inValidDate);
                if(discountEntity.getFixEndTime() != null) {
                    if (DateUtils.compareDate(new Date(), discountEntity.getFixEndTime())) {
                        discountEntity.setInValidStatus("未过期");
                        discountEntity.setValidStatus(0);
                    } else {
                        discountEntity.setInValidStatus("已过期");
                        discountEntity.setValidStatus(1);
                    }
                }
            }
            if(discountEntity.getEffectTimeType().equalsIgnoreCase(Dict.effectTimeType.item_01.getItem())){
                String postponeNum = StringUtils.isNotEmpty(discountEntity.getPostponeNum()) ? discountEntity.getPostponeNum() : "0";
                String validDayNum = StringUtils.isNotEmpty(discountEntity.getValidDayNum()) ? discountEntity.getValidDayNum() : "0";
                String inValidDate = "领取后" + postponeNum + "天生效" + validDayNum + "天有效";
                Integer day = Integer.parseInt(postponeNum) + Integer.parseInt(validDayNum);
//                Date endDate = DateUtils.addDay(day);
                Date endDate = DateUtils.addDay(new Date(), day);

                discountEntity.setInValidTime(inValidDate);
                if(DateUtils.compareDate(new Date(), endDate)) {
                    discountEntity.setInValidStatus("未过期");
                    discountEntity.setValidStatus(0);
                }else{
                    discountEntity.setInValidStatus("已过期");
                    discountEntity.setValidStatus(1);
                }
            }
        }

        PageUtils pageUtil = new PageUtils(mkStoreTicketDiscountList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }

    /**
     * 查看信息
     */
    @RequestMapping("/info/{tickDiscId}")
    @RequiresPermissions("mkstoreticketdiscount:info")
    @ResponseBody
    public R info(@PathVariable("tickDiscId") Integer tickDiscId) {
        MkStoreTicketDiscountEntity mkStoreTicketDiscount = mkStoreTicketDiscountService.queryObject(tickDiscId);
        if(mkStoreTicketDiscount.getEffectTimeType().equalsIgnoreCase(Dict.effectTimeType.item_00.getItem())){
            String startDate = DateUtils.format(mkStoreTicketDiscount.getFixBegTime(), DateUtils.DATE_PATTERN);
            String endDate = DateUtils.format(mkStoreTicketDiscount.getFixEndTime(), DateUtils.DATE_PATTERN);
            String inValidDate = startDate + " - " + endDate;
            mkStoreTicketDiscount.setInValidTime(inValidDate);
        }
        if(mkStoreTicketDiscount.getEffectTimeType().equalsIgnoreCase(Dict.effectTimeType.item_01.getItem())){
            String postponeNum = StringUtils.isNotEmpty(mkStoreTicketDiscount.getPostponeNum()) ? mkStoreTicketDiscount.getPostponeNum() : "0";
            String validDayNum = StringUtils.isNotEmpty(mkStoreTicketDiscount.getValidDayNum()) ? mkStoreTicketDiscount.getValidDayNum() : "0";
            String inValidDate = "领取后" + postponeNum + "天生效" + validDayNum + "天有效";
            Integer day = Integer.parseInt(postponeNum) + Integer.parseInt(validDayNum);
            mkStoreTicketDiscount.setInValidTime(inValidDate);
        }
        return R.ok().put("mkStoreTicketDiscount", mkStoreTicketDiscount);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("mkstoreticketdiscount:save")
    @ResponseBody
    public R save(@RequestBody MkStoreTicketDiscountEntity mkStoreTicketDiscount) {
        Map<String, Object> valideDate = MapBeanUtil.fromObject(mkStoreTicketDiscount);
        ImmutableBiMap.Builder builder = new ImmutableBiMap.Builder();
        builder.put("thirdMerchSn", "所属三方商户");
        builder.put("storeId", "所属门店");
        builder.put("name", "优惠券标题");
        builder.put("effectTimeType", "生效时间");
        builder.put("tickDiscType", "优惠类型");
        builder.put("ticketNum", "库存");
        builder.put("advImgUrl", "活动图片url(小图)");
        builder.put("storeLogoUrl", "门店logo图url");
        builder.put("ticketColor", "券面颜色");
        builder.put("optDecl", "操作说明");
        builder.put("discDecl", "优惠说明");
        builder.put("useNoti", "使用须知");
        R r = ValidatorUtil.isEmpty(builder.build(), valideDate);
        if (Integer.valueOf(r.get("code").toString()) != 0) {
            throw new RRException(r.get("msg").toString());
        }
        if(mkStoreTicketDiscount.getEffectTimeType().equalsIgnoreCase(Dict.effectTimeType.item_00.getItem())){
            builder.put("fixBegTime", "固定开始时间");
            builder.put("fixEndTime", "固定结束时间");
        }
        if(mkStoreTicketDiscount.getEffectTimeType().equalsIgnoreCase(Dict.effectTimeType.item_01.getItem())){
            builder.put("postponeNum", "领券天数");
            builder.put("validDayNum", "有效天数");
        }
        if(mkStoreTicketDiscount.getTickDiscType().equalsIgnoreCase(Dict.tickDiscType.item_00.getItem())){
            builder.put("voucherMoney", "代金券减免金额");
            builder.put("voucherCond", "代金券使用条件");
        }
        if(mkStoreTicketDiscount.getTickDiscType().equalsIgnoreCase(Dict.tickDiscType.item_01.getItem())){
            builder.put("discRatio", "折扣券折扣");
            builder.put("discCond", "折扣券使用条件");
        }
        //// TODO: 2019/5/21 代金券暂时无用
        /*if(mkStoreTicketDiscount.getTickDiscType().equalsIgnoreCase(Dict.tickDiscType.item_02.getItem())){
            builder.put("exchCond", "兑换券使用条件");
        }*/
        r = ValidatorUtil.isEmpty(builder.build(), valideDate);
        if (Integer.valueOf(r.get("code").toString()) != 0) {
            throw new RRException(r.get("msg").toString());
        }
        if(mkStoreTicketDiscount.getEffectTimeType().equalsIgnoreCase(Dict.effectTimeType.item_00.getItem())){
            if(!DateUtils.compareDate(mkStoreTicketDiscount.getFixBegTime(), mkStoreTicketDiscount.getFixEndTime())){
                throw new RRException("固定结束时间不能超过固定开始时间");
            }else{
                String startDate = DateUtils.format(mkStoreTicketDiscount.getFixBegTime())+" 00:00:00";
                String endDate = DateUtils.format(mkStoreTicketDiscount.getFixEndTime())+" 23:59:59";
                mkStoreTicketDiscount.setFixBegTime(DateUtils.strToDate(startDate));
                mkStoreTicketDiscount.setFixEndTime(DateUtils.strToDate(endDate));
            }
        }

        if(mkStoreTicketDiscount.getTickDiscType().equalsIgnoreCase(Dict.tickDiscType.item_00.getItem())){
            if(mkStoreTicketDiscount.getVoucherMoney().compareTo(mkStoreTicketDiscount.getVoucherCond()) == 1){
                throw new RRException("代金券减免金额不能大于使用条件");
            }
        }

        if(StringUtils.isNotEmpty(mkStoreTicketDiscount.getSvrTel())) {
            if (!PhoneFormatCheckUtils.isPhoneLegal(mkStoreTicketDiscount.getSvrTel())) {
                throw new RRException("手机号格式有误");
            }
        }
        mkStoreTicketDiscount.setName(mkStoreTicketDiscount.getName().trim());
        mkStoreTicketDiscount.setTickDiscSubTitle(mkStoreTicketDiscount.getTickDiscSubTitle().trim());
        mkStoreTicketDiscountService.save(mkStoreTicketDiscount);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("mkstoreticketdiscount:update")
    @ResponseBody
    public R update(@RequestBody MkStoreTicketDiscountEntity mkStoreTicketDiscount) {
        Map<String, Object> valideDate = MapBeanUtil.fromObject(mkStoreTicketDiscount);
        ImmutableBiMap.Builder builder = new ImmutableBiMap.Builder();
        builder.put("thirdMerchSn", "所属三方商户");
        builder.put("storeId", "所属门店");
        builder.put("name", "优惠券标题");
        builder.put("effectTimeType", "生效时间");
        builder.put("tickDiscType", "优惠类型");
        builder.put("ticketNum", "库存");
        builder.put("advImgUrl", "活动图片url(小图)");
        builder.put("storeLogoUrl", "门店logo图url");
        builder.put("ticketColor", "券面颜色");
        builder.put("optDecl", "操作说明");
        builder.put("discDecl", "优惠说明");
        builder.put("useNoti", "使用须知");
        R r = ValidatorUtil.isEmpty(builder.build(), valideDate);
        if (Integer.valueOf(r.get("code").toString()) != 0) {
            throw new RRException(r.get("msg").toString());
        }
        if(mkStoreTicketDiscount.getEffectTimeType().equalsIgnoreCase(Dict.effectTimeType.item_00.getItem())){
            builder.put("fixBegTime", "固定开始时间");
            builder.put("fixEndTime", "固定结束时间");
        }
        if(mkStoreTicketDiscount.getEffectTimeType().equalsIgnoreCase(Dict.effectTimeType.item_01.getItem())){
            builder.put("postponeNum", "领券天数");
            builder.put("validDayNum", "有效天数");
        }
        if(mkStoreTicketDiscount.getTickDiscType().equalsIgnoreCase(Dict.tickDiscType.item_00.getItem())){
            builder.put("voucherMoney", "代金券减免金额");
            builder.put("voucherCond", "代金券使用条件");
        }
        if(mkStoreTicketDiscount.getTickDiscType().equalsIgnoreCase(Dict.tickDiscType.item_01.getItem())){
            builder.put("discRatio", "折扣券折扣");
            builder.put("discCond", "折扣券使用条件");
        }
        //// TODO: 2019/5/21 代金券暂时无用
        /*if(mkStoreTicketDiscount.getTickDiscType().equalsIgnoreCase(Dict.tickDiscType.item_02.getItem())){
            builder.put("exchCond", "兑换券使用条件");
        }*/
        r = ValidatorUtil.isEmpty(builder.build(), valideDate);
        if (Integer.valueOf(r.get("code").toString()) != 0) {
            throw new RRException(r.get("msg").toString());
        }

        if(mkStoreTicketDiscount.getTickDiscType().equalsIgnoreCase(Dict.tickDiscType.item_00.getItem())){
            if(mkStoreTicketDiscount.getVoucherMoney().compareTo(mkStoreTicketDiscount.getVoucherCond()) == 1){
                throw new RRException("代金券减免金额不能大于使用条件");
            }
        }
        if(mkStoreTicketDiscount.getEffectTimeType().equalsIgnoreCase(Dict.effectTimeType.item_00.getItem())){
            if(!DateUtils.compareDate(mkStoreTicketDiscount.getFixBegTime(), mkStoreTicketDiscount.getFixEndTime())){
                throw new RRException("固定结束时间不能超过固定开始时间");
            }else{
                String startDate = DateUtils.format(mkStoreTicketDiscount.getFixBegTime())+" 00:00:00";
                String endDate = DateUtils.format(mkStoreTicketDiscount.getFixEndTime())+" 23:59:59";
                mkStoreTicketDiscount.setFixBegTime(DateUtils.strToDate(startDate));
                mkStoreTicketDiscount.setFixEndTime(DateUtils.strToDate(endDate));
            }
        }

        if(StringUtils.isNotEmpty(mkStoreTicketDiscount.getSvrTel())) {
            if (!PhoneFormatCheckUtils.isPhoneLegal(mkStoreTicketDiscount.getSvrTel())) {
                throw new RRException("手机号格式有误");
            }
        }
        mkStoreTicketDiscountService.update(mkStoreTicketDiscount);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("mkstoreticketdiscount:delete")
    @ResponseBody
    public R delete(@RequestBody Integer[]tickDiscIds) {
        mkStoreTicketDiscountService.deleteBatch(tickDiscIds);

        return R.ok();
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    @ResponseBody
    public R queryAll(@RequestParam Map<String, Object> params) {
        ParamUtils.setQueryPowerByRoleType(params, "storeId", "merchSn", "thirdPartyMerchCode");

        List<MkStoreTicketDiscountEntity> list = mkStoreTicketDiscountService.queryList(params);

        return R.ok().put("list", list);
    }

    @RequestMapping("/qrcodeCanvasByTickDiscId/{tickDiscId}")
//    @RequiresPermissions("mkstoreticketdiscount:qrcodeCanvasByTickDiscId")
    @ResponseBody
    public R qrcodeCanvasByTickDiscId(@PathVariable("tickDiscId") Integer tickDiscId) {
        MkStoreTicketDiscountEntity ticketDiscountEntity = mkStoreTicketDiscountService.queryObject(tickDiscId);
        if(ticketDiscountEntity == null){
            throw new RRException("门店优惠券信息不存在");
        }
        AccessToken accessToken = WxTemplateUtil.getAccessToken(WxPayPropertiesBuilder.instance().getAppId(),WxPayPropertiesBuilder.instance().getSecret());
        if(accessToken == null){
            throw new RRException("token获取失败");
        }
        String token = accessToken.getToken();

        //构建请求参数
        Map<Object, Object> params = new HashMap<Object, Object>();
        //dictId&storeId&isShare,isShare为0则是分享页进来的
        params.put("scene", ticketDiscountEntity.getTickDiscId()+"&"+ticketDiscountEntity.getStoreId()+"&0");//参数
        params.put("page", "pages/ucenter/couponDetail/couponDetail");//优惠券详情页面
        params.put("width", 430);
        String mapToXml = JSON.toJSONString(params);

        String url = FileUploadUtil.getUploadUrl(mapToXml, token, tickDiscId);
        return R.ok().put("url", url);
    }
}
