package com.kmall.admin.controller;

import com.google.common.collect.ImmutableBiMap;
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.manager.manager.pay.wxpay.WxPayPropertiesBuilder;
import com.kmall.admin.fromcomm.entity.SysUserEntity;
import com.kmall.common.fileserver.util.FileManager;
import com.kmall.common.utils.*;
import com.kmall.common.utils.wechat.AccessToken;
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.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.nio.file.Files;
import java.util.List;
import java.util.Map;

import java.util.HashMap;

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 com.alibaba.fastjson.JSON;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

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

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

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

        String storeName = (String) params.get("storeName");
        if(org.apache.commons.lang3.StringUtils.isNotEmpty(storeName)){
            try{
                storeName = new String(storeName.getBytes("iso-8859-1"),"utf-8");
            }catch (Exception e){
                e.printStackTrace();
            }
            params.put("storeName", 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("scene", "1181135&40&1111");//参数
//        params.put("page", "pages/goods/goods");//页面
        params.put("width", 430);
        String mapToXml = JSON.toJSONString(params);

        try {
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();

            HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+token);
            httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
            StringEntity entity = new StringEntity(mapToXml);
            entity.setContentType("image/png");

            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);
            InputStream inputStream = response.getEntity().getContent();

            String fileName = System.currentTimeMillis()+"_"+storeId+".png";
            String dirName = "\\upload";
            File dirFile = new File(dirName);
            //删除之前的图片文件夹
            deleteFile(dirFile);
            if(!dirFile.exists()){
                dirFile.mkdirs();
            }

            File file = new File(dirName, fileName);// 可以是任何图片格式.jpg,.png等
            FileOutputStream fos = new FileOutputStream(file);
            if (inputStream != null) {
                try {
                    byte[] b = new byte[1024];
                    int nRead = 0;
                    while ((nRead = inputStream.read(b)) != -1) {
                        fos.write(b, 0, nRead);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {

                    try {
                        fos.flush();
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            FileItem fileItem = new DiskFileItem("mainFile", Files.probeContentType(file.toPath()), false,
                    file.getName(), (int) file.length(), file.getParentFile());
            try (InputStream input = new FileInputStream(file); OutputStream os = fileItem.getOutputStream();) {
                IOUtils.copy(input, os);
                MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
                String url = FileManager.upload(multipartFile);
                return R.ok().put("url", url);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return R.ok().put("url", "");
    }

    private void deleteFile(File dirFile){
        if(dirFile.exists()){
            if(dirFile.isFile()){
                dirFile.delete();
            }else {
                for(File file:dirFile.listFiles()){
                    deleteFile(file);
                }
            }
        }
    }
}
