package com.kmall.admin.controller;

import com.alibaba.fastjson.JSON;
import com.kmall.admin.dto.StoreGoodsDto;
import com.kmall.admin.entity.ProductStoreRelaEntity;
import com.kmall.admin.fromcomm.entity.SysUserEntity;
import com.kmall.admin.service.ProductStoreRelaService;
import com.kmall.admin.utils.ParamUtils;
import com.kmall.admin.utils.ShiroUtils;
import com.kmall.common.constant.Dict;
import com.kmall.common.constant.JxlsXmlTemplateName;
import com.kmall.common.utils.*;
import com.kmall.common.utils.excel.ExcelUtil;
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.*;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * Controller
 *
 * @author Scott
 * @email
 * @date 2017-12-27 19:12:46
 */
@Controller
@RequestMapping("productstorerela")
public class ProductStoreRelaController {
    @Autowired
    private ProductStoreRelaService productStoreRelaService;
    @Autowired
    private ExcelUtil excelUtil;

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

        List<ProductStoreRelaEntity> productStoreRelaList = productStoreRelaService.queryList(query);
        //共享库存以商品总库存为准
        for (ProductStoreRelaEntity pro: productStoreRelaList) {
            if(org.apache.commons.lang3.StringUtils.isNotEmpty(pro.getIsStockShare())) {
                if(org.apache.commons.lang3.StringUtils.isNotEmpty(pro.getGoodsBizType())) {
                    if (pro.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_00.getItem())) {
                        if (pro.getIsStockShare().equalsIgnoreCase(Dict.isStockShare.item_1.getItem())) {
                            pro.setStockNum(pro.getGoodsNumber());
                        }
                    }
                }
            }
        }
        int total = productStoreRelaService.queryTotal(query);

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

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

    /**
     * 查看信息
     */
    @RequestMapping("/info/{id}")
    @ResponseBody
    public R info(@PathVariable("id") Integer id) {
        ProductStoreRelaEntity productStoreRela = productStoreRelaService.queryObject(id);

        return R.ok().put("productStoreRela", productStoreRela);
    }
    /**
     * 根据商品id查看信息
     */
    @RequestMapping("/infoByGoodsId")
    @ResponseBody
    public R infoByGoodsId(@RequestParam Map<String, Object> params) {
        ProductStoreRelaEntity productStoreRela = productStoreRelaService.queryObjectByStoreAndGoodsId(params);

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

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("productstorerela:save")
    @ResponseBody
    public R save(@RequestBody ProductStoreRelaEntity productStoreRela) {

        productStoreRelaService.save(productStoreRela);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("productstorerela:update")
    @ResponseBody
    public R update(@RequestBody ProductStoreRelaEntity productStoreRela) {
        if (null == productStoreRela.getProductId() || null == productStoreRela.getGoodsId() ||
            null == productStoreRela.getStoreId()) {
            return R.error("信息不全，保存失败");
        }

        productStoreRelaService.update(productStoreRela);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("productstorerela:delete")
    @ResponseBody
    public R delete(@RequestBody Integer[] ids) {
        productStoreRelaService.deleteBatch(ids);

        return R.ok();
    }

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

        List<ProductStoreRelaEntity> list = productStoreRelaService.queryList(params);

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

    /**
     * 查看优惠券选择商品列表
     * @param params
     * @return
     */
    @RequestMapping("/queryGoodsRealListByDiscountTid")
    @ResponseBody
    public R queryGoodsRealListByDiscountTid(@RequestParam Map<String, Object> params) {
        ParamUtils.setQueryPowerByRoleType(params, "id", "merchSn", "thirdPartyMerchCode");
        ParamUtils.setName(params, "goodsName");
        //查询列表数据
        Query query = new Query(params);

        List<ProductStoreRelaEntity> productStoreRelaList = productStoreRelaService.queryGoodsRealListByDiscountTid(query);
        for (ProductStoreRelaEntity pro: productStoreRelaList) {
            if(pro.getIsCheck()==null){
                pro.setIsCheck(0);//未选中
            }else{
                String guid = (String)params.get("guid");
                if(guid.equalsIgnoreCase(pro.getGuid())) {
                    pro.setIsCheck(1);
                }else{
                    pro.setIsCheck(0);//未选中
                }
            }
            if(org.apache.commons.lang3.StringUtils.isNotEmpty(pro.getIsStockShare())) {
                if(org.apache.commons.lang3.StringUtils.isNotEmpty(pro.getGoodsBizType())) {
                    if (pro.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_00.getItem())) {
                        if (pro.getIsStockShare().equalsIgnoreCase(Dict.isStockShare.item_1.getItem())) {
                            pro.setStockNum(pro.getGoodsNumber());
                        }
                    }
                }
            }
        }
        int total = productStoreRelaService.queryGoodsRealListByDiscountTidTotal(query);

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

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


    /**
     * 根据门店活动id查看门店活动选择商品列表
     * @param params
     * @return
     */
    @RequestMapping("/queryGoodsRealListByTopicId")
    @ResponseBody
    public R queryGoodsRealListByTopicId(@RequestParam Map<String, Object> params) {
        ParamUtils.setQueryPowerByRoleType(params, "id", "merchSn", "thirdPartyMerchCode");
        ParamUtils.setName(params, "goodsName");
        //查询列表数据
        Query query = new Query(params);

        List<ProductStoreRelaEntity> productStoreRelaList = productStoreRelaService.queryGoodsRealListByTopicId(query);
        for (ProductStoreRelaEntity pro: productStoreRelaList) {
            if(pro.getIsCheck()==null){
                pro.setIsCheck(0);//未选中
            }else{
                Integer storeTopicId = Integer.parseInt((String)params.get("storeTopicId"));
                if(storeTopicId.compareTo(pro.getStoreTopicId())==0) {
                    pro.setIsCheck(1);
                }else{
                    pro.setIsCheck(0);//未选中
                }
            }
            if(org.apache.commons.lang3.StringUtils.isNotEmpty(pro.getIsStockShare())) {
                if(org.apache.commons.lang3.StringUtils.isNotEmpty(pro.getGoodsBizType())) {
                    if (pro.getGoodsBizType().equalsIgnoreCase(Dict.orderBizType.item_00.getItem())) {
                        if (pro.getIsStockShare().equalsIgnoreCase(Dict.isStockShare.item_1.getItem())) {
                            pro.setStockNum(pro.getGoodsNumber());
                        }
                    }
                }
            }
        }
        int total = productStoreRelaService.queryGoodsRealListByTopicIdTotal(query);

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

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

    @RequestMapping("/qrcodeCanvas/{id}")
//    @RequiresPermissions("mkstoreprom:qrcodeCanvas")
    @ResponseBody
    public R qrcodeCanvas(@PathVariable("id") Integer id) {
        SysUserEntity user = ShiroUtils.getUserEntity();
        if (user == null) {
            throw new RRException("用户登录超时，请重新登录");
        }
        ProductStoreRelaEntity productStoreRelaEntity = productStoreRelaService.queryObject(id);
        if(productStoreRelaEntity==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>();
        params.put("scene", productStoreRelaEntity.getGoodsId()+"&"+productStoreRelaEntity.getStoreId()+"&&"+user.getUserId());//参数
        params.put("page", "pages/goods/goods");//商品详情页面
        params.put("width", 430);
        String mapToXml = JSON.toJSONString(params);

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

    /**
     * 上传文件
     */
    @RequestMapping("/productStoreRelaUpload")
    public R storeUpload(@RequestParam("file") MultipartFile file) {
        List<StoreGoodsDto> StoreGoodsDtoList = new ArrayList<>();//信息
        try {
            StoreGoodsDto storeGoodsDto = new StoreGoodsDto();
            Map<String, Object> beans = new HashMap<String, Object>();
            beans.put("StoreGoodsDto", storeGoodsDto);
            beans.put("StoreGoodsDtoList", StoreGoodsDtoList);
            if (file.isEmpty()) {
                return R.error("文件不能为空！");
            }
            excelUtil.readExcel(JxlsXmlTemplateName.STORE_GOODS_DTO_LIST, beans, file.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("导入失败！");
        }
        productStoreRelaService.uploadExcel(StoreGoodsDtoList);
        //上传文件
        return R.ok("导入成功！");
    }
}
