package com.kmall.admin.controller;

import com.google.common.collect.ImmutableBiMap;
import com.kmall.admin.dto.StoreDto;
import com.kmall.admin.entity.StoreEntity;
import com.kmall.admin.service.StoreService;
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.excel.ExcelExport;
import com.kmall.common.utils.excel.ExcelUtil;
import com.kmall.common.utils.file.FileUploadUtil;
import com.kmall.manager.manager.pay.wxpay.WxPayPropertiesBuilder;
import com.kmall.admin.fromcomm.entity.SysUserEntity;
import com.kmall.common.utils.*;
import com.kmall.common.utils.wechat.AccessToken;
import com.kmall.manager.manager.wechat.wxtemplate.WxTemplateUtil;
import org.apache.commons.lang3.StringUtils;
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 java.util.*;

import com.alibaba.fastjson.JSON;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Controller
 *
 * @author Scott
 * @email
 * @date 2017-12-02 00:53:32
 */
@Controller
@RequestMapping("store")
public class StoreController {
    @Autowired
    private StoreService storeService;
    @Autowired
    private ExcelUtil excelUtil;

    /**
     * 查看列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("store:list")
    @ResponseBody
    public R list(@RequestParam Map<String, Object> params) {

        ParamUtils.setQueryPowerByRoleType(params, "id", "merchSn", "thirdPartyMerchCode");
        ParamUtils.setName(params, "storeName");
        //查询列表数据
        Query query = new Query(params);

        List<StoreEntity> storeList = storeService.queryList(query);
        int total = storeService.queryTotal(query);

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

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

    /**
     * 查看信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("store:info")
    @ResponseBody
    public R info(@PathVariable("id") Integer id) {
        StoreEntity store = storeService.queryObject(id);

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

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("store:save")
    @ResponseBody
    public R save(@RequestBody StoreEntity store) {
        SysUserEntity user = ShiroUtils.getUserEntity();
        if(user == null) {
            return R.error("用户登录超时，请重新登录");
        }
        if (user.getRoleType().equalsIgnoreCase("2")) {
            return R.error("当前用户角色为【店员】，店员不能新增其他门店信息");
        }
        Map<String, Object> valideDate = MapBeanUtil.fromObject(store);
        ImmutableBiMap.Builder builder = new ImmutableBiMap.Builder();
        builder.put("merchSn", "商户");
        builder.put("storeName", "门店名称");
        builder.put("storeNumber", "门店编号");
        builder.put("thirdPartyMerchCode", "第三方商户编号");
//        builder.put("thirdPartyMerchName", "第三方商户名称");
        builder.put("exprAgreementType", "第三方商户快递协议类型");
        builder.put("latitude", "纬度");
        builder.put("longitude", "经度");
        R r = ValidatorUtil.isEmpty(builder.build(), valideDate);
        if (Integer.valueOf(r.get("code").toString()) != 0) {
            throw new RRException(r.get("msg").toString());
        }
        storeService.save(store);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("store:update")
    @ResponseBody
    public R update(@RequestBody StoreEntity store) {
        SysUserEntity user = ShiroUtils.getUserEntity();
        if(user == null) {
            return R.error("用户登录超时，请重新登录");
        }
        Map<String, Object> valideDate = MapBeanUtil.fromObject(store);
        ImmutableBiMap.Builder builder = new ImmutableBiMap.Builder();
        builder.put("merchSn", "商户");
        builder.put("storeName", "门店名称");
        builder.put("storeNumber", "门店编号");
        builder.put("thirdPartyMerchCode", "第三方商户编号");
//        builder.put("thirdPartyMerchName", "第三方商户名称");
        builder.put("exprAgreementType", "第三方商户快递协议类型");
        builder.put("latitude", "纬度");
        builder.put("longitude", "经度");
        R r = ValidatorUtil.isEmpty(builder.build(), valideDate);
        if (Integer.valueOf(r.get("code").toString()) != 0) {
            throw new RRException(r.get("msg").toString());
        }
        storeService.update(store);

        return R.ok();
    }

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

        return R.ok();
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    @ResponseBody
    public R queryAll(@RequestParam Map<String, Object> params) {

        ParamUtils.setQueryPowerByRoleType(params, "id", "merchSn", "thirdPartyMerchCode");

        List<StoreEntity> list = storeService.queryList(params);

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


    /**
     * 查看所有列表
     */
    @RequestMapping("/getStoresByMerch")
    @ResponseBody
    public R getStoresByMerch(@RequestParam Map<String, Object> params) {

        ParamUtils.setQueryPowerByRoleType(params, "id", "merchSn", "thirdPartyMerchCode");

        List<StoreEntity> list = storeService.queryList(params);
        return R.ok().put("list", list);
    }

    /**
     * 根据第三方商户查看所有列表
     */
    @RequestMapping("/getStoresByThirdMerch")
    @ResponseBody
    public R getStoresByThirdMerch(@RequestParam Map<String, Object> params) {

        ParamUtils.setQueryPowerByRoleType(params, "id", "merchSn", "thirdPartyMerchCode");

        List<StoreEntity> list = storeService.queryList(params);
        return R.ok().put("list", list);
    }

    @RequestMapping("/qrcodeCanvas/{storeId}")
    @RequiresPermissions("store:qrcodeCanvas")
    @ResponseBody
    public R qrcodeCanvas(@PathVariable("storeId") Integer storeId) {
        StoreEntity store = storeService.queryObject(storeId);
        if(store==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", store.getId());//参数
        params.put("page", "pages/index/index");//页面
        params.put("width", 90);
        String mapToXml = JSON.toJSONString(params);

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

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

    /**
     * 订单导出请求
     */
    @RequestMapping(value = "export")
    public Object export(@RequestParam Map<String, Object> params, HttpServletResponse response, HttpServletRequest request) {
        ParamUtils.setQueryPowerByRoleType(params, "id", "merchSn", "thirdPartyMerchCode");
        ParamUtils.setName(params, "storeName");
        //查询列表数据
        List<StoreEntity> storeEntityList = storeService.queryExportList(params);

        ExcelExport ee = new ExcelExport("门店id信息");

        String[] header = new String[]{"门店编号", "门店名称", "oms门店编号"};

        List<Map<String, Object>> list = new ArrayList<>();
        if (storeEntityList != null && storeEntityList.size() != 0) {
            for (StoreEntity storeEntity : storeEntityList) {
                LinkedHashMap<String, Object> map = new LinkedHashMap<>();

                map.put("StoreId", storeEntity.getId());
                map.put("StoreName", storeEntity.getStoreName());
                map.put("StoreNumber", storeEntity.getStoreNumber());
                list.add(map);
            }
        }

        ee.addSheetByMap("门店id信息", list, header);
        ee.export(response);
        return R.ok();
    }

}
