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.MkStoreCampMinusEntity;
import com.kmall.admin.entity.mk.store.StoreTopicEntity;
import com.kmall.admin.fromcomm.entity.SysUserEntity;
import com.kmall.admin.service.mk.store.MkStoreCampMinusService;
import com.kmall.admin.service.mk.store.StoreTopicService;
import com.kmall.admin.utils.ParamUtils;
import com.kmall.admin.utils.ShiroUtils;
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-29 14:43:28
 */
@Controller
@RequestMapping("mkstorecampminus")
public class MkStoreCampMinusController {
    @Autowired
    private MkStoreCampMinusService mkStoreCampMinusService;
    @Autowired
    private StoreTopicService storeTopicService;

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

        List<MkStoreCampMinusEntity> mkStoreCampMinusList = mkStoreCampMinusService.queryList(query);
        int total = mkStoreCampMinusService.queryTotal(query);

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

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

    /**
     * 查看信息
     */
    @RequestMapping("/info/{campMinusId}")
    @RequiresPermissions("mkstorecampminus:info")
    @ResponseBody
    public R info(@PathVariable("campMinusId") Integer campMinusId) {
        MkStoreCampMinusEntity mkStoreCampMinus = mkStoreCampMinusService.queryObject(campMinusId);

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

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("mkstorecampminus:save")
    @ResponseBody
    public R save(@RequestBody MkStoreCampMinusEntity mkStoreCampMinus) {
        Map<String, Object> valideDate = MapBeanUtil.fromObject(mkStoreCampMinus);
        ImmutableBiMap.Builder builder = new ImmutableBiMap.Builder();
        builder.put("campName", "活动名称");
        builder.put("campBegTime", "活动起始时间");
        builder.put("campEndTime", "活动结束时间");
        builder.put("campMinusType", "减免活动类型");
        builder.put("thirdMerchSn", "所属三方商户");
        builder.put("storeId", "所属门店");
        builder.put("goodsBizType", "货品业务类型");
        builder.put("applyType", "适用类型");
        builder.put("advImgUrl", "活动图片url");
        R r = ValidatorUtil.isEmpty(builder.build(), valideDate);
        if (Integer.valueOf(r.get("code").toString()) != 0) {
            throw new RRException(r.get("msg").toString());
        }
        mkStoreCampMinusService.save(mkStoreCampMinus);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("mkstorecampminus:update")
    @ResponseBody
    public R update(@RequestBody MkStoreCampMinusEntity mkStoreCampMinus) {
        Map<String, Object> valideDate = MapBeanUtil.fromObject(mkStoreCampMinus);
        ImmutableBiMap.Builder builder = new ImmutableBiMap.Builder();
        builder.put("campName", "活动名称");
        builder.put("campBegTime", "活动起始时间");
        builder.put("campEndTime", "活动结束时间");
        builder.put("campMinusType", "减免活动类型");
        builder.put("thirdMerchSn", "所属三方商户");
        builder.put("storeId", "所属门店");
        builder.put("goodsBizType", "货品业务类型");
        builder.put("applyType", "适用类型");
        builder.put("advImgUrl", "活动图片url");
        R r = ValidatorUtil.isEmpty(builder.build(), valideDate);
        if (Integer.valueOf(r.get("code").toString()) != 0) {
            throw new RRException(r.get("msg").toString());
        }
        mkStoreCampMinusService.update(mkStoreCampMinus);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("mkstorecampminus:delete")
    @ResponseBody
    public R delete(@RequestBody Integer[]campMinusIds) {
        mkStoreCampMinusService.deleteBatch(campMinusIds);

        return R.ok();
    }

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

        List<MkStoreCampMinusEntity> list = mkStoreCampMinusService.queryList(params);

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

    /**
     * 结束活动
     * @param campMinusId
     * @return
     */
    @RequestMapping("/updatePastById")
//    @RequiresPermissions("mkstorecampminus:updatePastById")
    @ResponseBody
    public R updatePastById(@RequestBody Integer campMinusId) {
        SysUserEntity user = ShiroUtils.getUserEntity();
        MkStoreCampMinusEntity campMinusEntity = mkStoreCampMinusService.queryObject(campMinusId);
        if(campMinusEntity != null) {
            MkStoreCampMinusEntity entity = new MkStoreCampMinusEntity();
            entity.setIsPast(Dict.isPast.item_1.getItem());
            entity.setIsValid(Dict.isValid.item_1.getItem());
            entity.setCampMinusId(campMinusId);
            entity.setCampEndTime(new Date());
            entity.setModTime(new Date());
            entity.setModerSn(user.getUsername());
            mkStoreCampMinusService.updatePastById(entity);

            //修改为无效活动
            StoreTopicEntity storeTopicEntity = new StoreTopicEntity();
            storeTopicEntity.setId(campMinusEntity.getStoreTopicId());
            storeTopicEntity.setIsValid(Dict.isValid.item_1.getItem());
            storeTopicEntity.setModTime(new Date());
            storeTopicEntity.setModerSn(user.getUsername());
            storeTopicService.update(storeTopicEntity);
        }
        return R.ok();
    }

    /**
     * 开始活动
     * @param campMinusId
     * @return
     */
    @RequestMapping("/updateStartPastById")
//    @RequiresPermissions("mkstorecampminus:updateStartPastById")
    @ResponseBody
    public R updateStartPastById(@RequestBody Integer campMinusId) {
        SysUserEntity user = ShiroUtils.getUserEntity();
        MkStoreCampMinusEntity campMinusEntity = mkStoreCampMinusService.queryObject(campMinusId);
        if(campMinusEntity != null) {
            MkStoreCampMinusEntity entity = new MkStoreCampMinusEntity();
            entity.setIsPast(Dict.isPast.item_0.getItem());
            entity.setCampMinusId(campMinusId);
            entity.setCampBegTime(new Date());
            entity.setModTime(new Date());
            entity.setModerSn(user.getUsername());
            mkStoreCampMinusService.updatePastById(entity);
        }
        return R.ok();
    }

    @RequestMapping("/qrcodeCanvasByCampMinus/{campMinusId}")
//    @RequiresPermissions("mkstorecampminus:qrcodeCanvas")
    @ResponseBody
    public R qrcodeCanvasByCampMinus(@PathVariable("campMinusId") Integer campMinusId) {
        MkStoreCampMinusEntity campMinusEntity = mkStoreCampMinusService.queryObject(campMinusId);
        if(campMinusEntity==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", campMinusEntity.getCampMinusId()+"&"+campMinusEntity.getStoreId()+"&0");//参数
        params.put("page", "pages/ucenter/couponDetail/couponDetail");//优惠券详情页面
        params.put("width", 430);
        String mapToXml = JSON.toJSONString(params);

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