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

import java.io.*;
import java.nio.file.Files;
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.MkStorePromChnlEntity;
import com.kmall.admin.entity.mk.store.MkStorePromEntity;
import com.kmall.admin.fromcomm.entity.SysUserEntity;
import com.kmall.admin.service.mk.store.MkStorePromService;
import com.kmall.admin.utils.ParamUtils;
import com.kmall.admin.utils.ShiroUtils;
import com.kmall.common.constant.Dict;
import com.kmall.common.fileserver.util.FileManager;
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.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
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.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

/**
 * 门店推广Controller
 *
 * @author huangyq
 * @email admin@qhdswl.com
 * @date 2019-04-26 15:52:20
 */
@Controller
@RequestMapping("mkstoreprom")
public class MkStorePromController {
    @Autowired
    private MkStorePromService mkStorePromService;

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

        List<MkStorePromEntity> mkStorePromList = mkStorePromService.queryList(query);

        int total = mkStorePromService.queryTotal(query);
        PageUtils pageUtil = new PageUtils(mkStorePromList, total, query.getLimit(), query.getPage());

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

    /**
     * 查看信息
     */
    @RequestMapping("/info/{promId}")
    @RequiresPermissions("mkstoreprom:info")
    @ResponseBody
    public R info(@PathVariable("promId") Integer promId) {
        MkStorePromEntity mkStoreProm = mkStorePromService.queryObject(promId);

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

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("mkstoreprom:save")
    @ResponseBody
    public R save(@RequestBody MkStorePromEntity mkStoreProm) {
        Map<String, Object> valideDate = MapBeanUtil.fromObject(mkStoreProm);
        ImmutableBiMap.Builder builder = new ImmutableBiMap.Builder();
        builder.put("promName", "推广名称");
        builder.put("thirdMerchSn", "所属三方商户");
        builder.put("storeId", "所属门店");
        builder.put("promBegTime", "推广起始时间");
        builder.put("promEndTime", "推广结束时间");
        builder.put("promType", "推广分类");
        builder.put("promChnlId", "推广渠道");
        R r = ValidatorUtil.isEmpty(builder.build(), valideDate);
        if (Integer.valueOf(r.get("code").toString()) != 0) {
            throw new RRException(r.get("msg").toString());
        }
        if(mkStoreProm.getPromType().equalsIgnoreCase("00")){
            builder.put("storeTopicId", "推广活动");
        }
        if(mkStoreProm.getPromType().equalsIgnoreCase("10")){
            builder.put("goodsId", "推广商品");
        }
        r = ValidatorUtil.isEmpty(builder.build(), valideDate);
        if (Integer.valueOf(r.get("code").toString()) != 0) {
            throw new RRException(r.get("msg").toString());
        }
        if(!DateUtils.compareDate(mkStoreProm.getPromBegTime(), mkStoreProm.getPromEndTime())){
            throw new RRException("结束时间不能超过开始时间");
        }

        mkStorePromService.save(mkStoreProm);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("mkstoreprom:update")
    @ResponseBody
    public R update(@RequestBody MkStorePromEntity mkStoreProm) {
        Map<String, Object> valideDate = MapBeanUtil.fromObject(mkStoreProm);
        ImmutableBiMap.Builder builder = new ImmutableBiMap.Builder();
        builder.put("promName", "推广名称");
        builder.put("thirdMerchSn", "所属三方商户");
        builder.put("storeId", "所属门店");
        builder.put("promBegTime", "推广起始时间");
        builder.put("promEndTime", "推广结束时间");
        builder.put("promType", "推广分类");
        builder.put("promChnlId", "推广渠道");
        R r = ValidatorUtil.isEmpty(builder.build(), valideDate);
        if (Integer.valueOf(r.get("code").toString()) != 0) {
            throw new RRException(r.get("msg").toString());
        }
        if(mkStoreProm.getPromType().equalsIgnoreCase("00")){
            builder.put("storeTopicId", "推广活动");
        }
        if(mkStoreProm.getPromType().equalsIgnoreCase("10")){
            builder.put("goodsId", "推广商品");
        }
        r = ValidatorUtil.isEmpty(builder.build(), valideDate);
        if (Integer.valueOf(r.get("code").toString()) != 0) {
            throw new RRException(r.get("msg").toString());
        }
        if(!DateUtils.compareDate(mkStoreProm.getPromBegTime(), mkStoreProm.getPromEndTime())){
            throw new RRException("结束时间不能超过开始时间");
        }
        mkStorePromService.update(mkStoreProm);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("mkstoreprom:delete")
    @ResponseBody
    public R delete(@RequestBody Integer[]promIds) {
        mkStorePromService.deleteBatch(promIds);

        return R.ok();
    }

    @RequestMapping("/updateFinished")
    @RequiresPermissions("mkstoreprom:update")
    @ResponseBody
    public R updateFinished(@RequestBody Integer promId) {
        SysUserEntity user = ShiroUtils.getUserEntity();
        MkStorePromEntity mkStorePromEntity = mkStorePromService.queryObject(promId);
        if(mkStorePromEntity != null){
            if(mkStorePromEntity.getIsFinished().equalsIgnoreCase(Dict.isFinished.item_0.getItem())){
                throw new RRException("该推广信息已结束，不能再次操作！");
            }else{
                MkStorePromEntity promEntity = new MkStorePromEntity();
                promEntity.setPromId(promId);
                promEntity.setIsFinished(Dict.isFinished.item_0.getItem());
                promEntity.setPromEndTime(new Date());
                promEntity.setModTime(new Date());
                promEntity.setModerSn(user.getUsername());
                mkStorePromService.updateStartedOrFinished(promEntity);
            }
        }

        return R.ok();
    }

    @RequestMapping("/updateStarted")
    @RequiresPermissions("mkstoreprom:update")
    @ResponseBody
    public R updateStarted(@RequestBody Integer promId) {
        SysUserEntity user = ShiroUtils.getUserEntity();
        MkStorePromEntity mkStorePromEntity = mkStorePromService.queryObject(promId);
        if(mkStorePromEntity != null){
            if(mkStorePromEntity.getIsFinished().equalsIgnoreCase(Dict.isFinished.item_0.getItem())){
                throw new RRException("该推广信息已结束，不能进行操作！");
            }else if(mkStorePromEntity.getIsFinished().equalsIgnoreCase(Dict.isFinished.item_1.getItem())){
                throw new RRException("该推广信息正在进行中，不能再次操作！");
            }else{
                MkStorePromEntity promEntity = new MkStorePromEntity();
                promEntity.setPromId(promId);
                promEntity.setIsFinished(Dict.isFinished.item_1.getItem());
                promEntity.setPromBegTime(new Date());
                promEntity.setModTime(new Date());
                promEntity.setModerSn(user.getUsername());
                mkStorePromService.updateStartedOrFinished(promEntity);
            }
        }

        return R.ok();
    }

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

        List<MkStorePromEntity> list = mkStorePromService.queryList(params);

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

    @RequestMapping("/qrcodeCanvas/{promId}")
//    @RequiresPermissions("mkstoreprom:qrcodeCanvas")
    @ResponseBody
    public R qrcodeCanvas(@PathVariable("promId") Integer promId) {
        MkStorePromEntity storePromEntity = mkStorePromService.queryObject(promId);
        if(storePromEntity==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>();
        if(storePromEntity.getPromType().equalsIgnoreCase(Dict.promType.item_10.getItem())){
            params.put("scene", storePromEntity.getGoodsId()+"&"+storePromEntity.getStoreId()+"&"+storePromEntity.getPromId());//参数
            params.put("page", "pages/goods/goods");//商品详情页面
        }
        if(storePromEntity.getPromType().equalsIgnoreCase(Dict.promType.item_00.getItem())){
            params.put("scene", storePromEntity.getStoreTopicId()+"&"+storePromEntity.getStoreId()+"&"+storePromEntity.getPromId());//参数
            params.put("page", "pages/goods/goods");//活动详情页面
        }
        params.put("width", 430);
        String mapToXml = JSON.toJSONString(params);

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