package com.ssm.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ssm.core.bean.GenericResponse;
import com.ssm.core.bean.WXMssVo;
import com.ssm.core.bean.WXTemplateDataVo;
import com.ssm.core.util.WXHttpRequest;
import com.ssm.core.utils.QRCodeUtil;
import com.ssm.manage.dao.SsmCashDao;
import com.ssm.manage.entity.BaseStore;
import com.ssm.manage.entity.CashList;
import com.ssm.manage.entity.SmsException;
import com.ssm.manage.query.CashListRequest;
import com.ssm.manage.query.StoreRequest;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.service.SsmBaseStoreService;
import com.ssm.manage.service.SsmCashService;
import com.ssm.manage.utils.CommonUtils;
import com.ssm.manage.utils.DateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

@Api(value="门店controller",tags={"门店相关接口"})
@RestController
@RequestMapping("/demay/ssm/store")
@Slf4j
public class SsmBaseStoreController {
    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;

    @Autowired
    private SsmCashDao ssmCashDao;


    @ApiOperation(value = "查询所拥有门店 美发版-查询所拥有门店",httpMethod = "POST",notes = "",response = GenericResponse.class)
    @RequestMapping("/list")
    public GenericResponse<BaseStore> list(@RequestBody StoreRequest storeRequest) {
        GenericResponse<BaseStore> genericResponse = new GenericResponse<>();
        BaseStore baseStore = new BaseStore();
        BeanUtils.copyProperties(storeRequest, baseStore);
        List<BaseStore> list = new ArrayList<>();
        try {
            list = ssmBaseStoreService.select(baseStore);
        } catch (Exception e) {
            log.error("SsmBaseStoreController.list", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        genericResponse.setRows(list);
        return genericResponse;
    }

    @ApiOperation(value = "分店注册 美发版-分店注册",httpMethod = "POST",notes = "",response = GenericResponse.class)
    @RequestMapping("/addStore")
    public GenericResponse<BaseStore> addStore(@RequestBody StoreRequest storeRequest) {
        GenericResponse<BaseStore> genericResponse = new GenericResponse<>();
        if (StringUtils.isBlank(storeRequest.getRegistrant())) {
            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S, "注册人");
            return genericResponse;
        }
        if (StringUtils.isBlank(storeRequest.getRegistrantMobilePhone())) {
            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S, "注册人手机");
            return genericResponse;
        }
        if (!CommonUtils.isMobile(storeRequest.getRegistrantMobilePhone())){
            genericResponse.setCodeAndMsg(ResponseCode.NOT_MEET_REQUIREMENTS_S,"注册人手机");
            return genericResponse;
        }
//        if (StringUtils.isBlank(storeRequest.getTelephone())) {
//            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S, "门店服务电话");
//            return genericResponse;
//        }
        if (StringUtils.isNotBlank(storeRequest.getTelephone()) && !CommonUtils.isTelephone(storeRequest.getTelephone())){
            genericResponse.setCodeAndMsg(ResponseCode.NOT_MEET_REQUIREMENTS_S,"门店服务电话");
            return genericResponse;
        }
        if (StringUtils.isBlank(storeRequest.getStoreName())) {
            genericResponse.setCodeAndMsg(ResponseCode.PARAMETER_NOT_EXIST_S, "门店名称");
            return genericResponse;
        }
        if (StringUtils.isNotBlank(storeRequest.getRegistrantIdentity()) && !CommonUtils.isIdentityCard(storeRequest.getRegistrantIdentity())) {
            genericResponse.setCodeAndMsg(ResponseCode.NOT_MEET_REQUIREMENTS_S, "身份证号");
            return genericResponse;
        }
        String userNum = "";
        int i = 0;
        try {
            i = ssmBaseStoreService.addStore(storeRequest,userNum);
        }catch (SmsException e){
            genericResponse.setCodeAndMsg(e);
            return genericResponse;
        }catch (Exception e) {
            log.error("SsmBaseStoreController.addStore", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        }
        return genericResponse;
    }

    @ApiOperation(value = "获取微信小程序session_key 美发版-获取微信小程序session_key",httpMethod = "POST",notes = "",response = GenericResponse.class)
    @RequestMapping("/getSessionKey")
    public GenericResponse getSessionKey(@RequestParam Map<String, String> formMap) {
        GenericResponse genericResponse = new GenericResponse<>();
        Map<String, String> map = new HashMap<>();
        String appid = ObjectUtils.toString(formMap.get("appid"));
        String secret = ObjectUtils.toString(formMap.get("secret"));
        String js_code = ObjectUtils.toString(formMap.get("js_code"));
        String grant_type = ObjectUtils.toString(formMap.get("grant_type"));

        try {
            //1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid
            //请求参数
            String params = "appid=" + appid + "&secret=" + secret + "&js_code=" + js_code + "&grant_type=" + grant_type;
            //发送请求
            String sr = WXHttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
            //解析相应内容（转换成json对象）
            JSONObject json = JSONObject.parseObject(sr);
            //获取会话密钥（session_key）
            String session_key = json.get("session_key").toString();
            //用户的唯一标识（openid）
            String openid = (String) json.get("openid");
            map.put("session_key",session_key);
            map.put("openid", openid);
        } catch (Exception e) {
            log.error("SsmBaseStoreController.getSessionKey", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        genericResponse.setData(map);
        return genericResponse;
    }

    @ApiOperation(value = "门店明细查询  美发版-门店明细查询",httpMethod = "POST",notes = "",response = GenericResponse.class)
    @RequestMapping("/one")
    public GenericResponse<BaseStore> selectOne(@RequestBody StoreRequest storeRequest) {
        GenericResponse<BaseStore> genericResponse = new GenericResponse<>();
        BaseStore baseStore = new BaseStore();
        try {
            baseStore = ssmBaseStoreService.selectOne(storeRequest);
        } catch (Exception e) {
            log.error("SsmBaseStoreController.selectOne", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        genericResponse.setData(baseStore);
        return genericResponse;
    }

    @ApiOperation(value = "生成微信小程序二维码 美发版-生成微信小程序二维码",httpMethod = "POST",notes = "",response = GenericResponse.class)
    @RequestMapping("/getQRCode")
    public GenericResponse getQRCode(@RequestParam Map<String, String> formMap) {
        GenericResponse genericResponse = new GenericResponse<>();
        Map<String, String> map = new HashMap<>();
        String appid = ObjectUtils.toString(formMap.get("appid"));
        String secret = ObjectUtils.toString(formMap.get("secret"));
        String grant_type = ObjectUtils.toString(formMap.get("grant_type"));
        String page = ObjectUtils.toString(formMap.get("page"));
        String storeId = ObjectUtils.toString(formMap.get("storeId"));
        JSONObject json = new JSONObject();
        try {
            //1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid
            //请求参数
            String params = "appid=" + appid + "&secret=" + secret + "&grant_type=" + grant_type;
            //发送请求
            String sr = WXHttpRequest.sendGet(" https://api.weixin.qq.com/cgi-bin/token", params);
            //解析相应内容（转换成json对象）
            json = JSONObject.parseObject(sr);
            //获取（access_token）

        }catch (Exception e){
            log.error("SsmBaseStoreController.getQRCode", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        String access_token = json.get("access_token").toString();
        //生成二维码资源
        map.put("page",page);
        map.put("scene",storeId);
//        String str = "{\"scene\":" + storeId + ",\"page\":" + page + " }";
        String str = JSON.toJSONString(map);
        byte[] data = WXHttpRequest.post("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + access_token, str);

//        //new一个文件对象用来保存图片
//        File imageFile = new File(Path);
//        //创建输出流
//        FileOutputStream outStream = null;
//        try {
//            outStream = new FileOutputStream(imageFile);
//            //写入数据
//            outStream.write(data);
//        } catch (Exception e) {
//            log.error("SsmBaseStoreController.getQRCode", e);
//            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
//            return genericResponse;
//        } finally {
//            try {
//                //关闭输出流
//                outStream.close();
//            } catch (IOException e) {
//                log.error("SsmBaseStoreController.getQRCode", e);
//                genericResponse.setCodeAndMsg(ResponseCode.FAILED);
//                return genericResponse;
//            }
//        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        genericResponse.setData(data);
        return genericResponse;
    }

    @ApiOperation(value = "微信小程序消息推送 美发版-微信小程序消息推送",httpMethod = "POST",notes = "",response = GenericResponse.class)
    @RequestMapping("/push")
    public GenericResponse push(@RequestParam Map<String, String> formMap) {
        GenericResponse genericResponse = new GenericResponse<>();
        Map<String, String> map = new HashMap<>();
        String appid = ObjectUtils.toString(formMap.get("appid"));
        String secret = ObjectUtils.toString(formMap.get("secret"));
        String openid = ObjectUtils.toString(formMap.get("openid"));
        String grant_type = ObjectUtils.toString(formMap.get("grant_type"));
        String page = ObjectUtils.toString(formMap.get("page"));
        String templateid = ObjectUtils.toString(formMap.get("templateid"));
        Long docId = Long.parseLong(ObjectUtils.toString(formMap.get("docId")));
        JSONObject json = new JSONObject();
        try {
            //1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid
            //请求参数
            String params = "appid=" + appid + "&secret=" + secret + "&grant_type=" + grant_type;
            //发送请求
            String sr = WXHttpRequest.sendGet(" https://api.weixin.qq.com/cgi-bin/token", params);
            //解析相应内容（转换成json对象）
            json = JSONObject.parseObject(sr);
            //获取（access_token）

        }catch (Exception e){
            log.error("SsmBaseStoreController.push", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        String access_token = json.get("access_token").toString();
        //对消息进行推送
        RestTemplate restTemplate = new RestTemplate();
        //这里简单起见我们每次都获取最新的access_token（时间开发中，应该在access_token快过期时再重新获取）
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + access_token;
        //拼接推送的模版
        WXMssVo wxMssVo = new WXMssVo();
        wxMssVo.setTouser(openid);//用户的openid（要发送给那个用户，通常这里应该动态传进来的）
        wxMssVo.setTemplate_id(templateid);//订阅消息模板id
        wxMssVo.setPage(page);

        Map<String, WXTemplateDataVo> m = new HashMap<>();
        CashListRequest cashListRequest = new CashListRequest();
        cashListRequest.setId(docId);
        cashListRequest.setCashDate(new Date());
        CashList cashList = ssmCashDao.one(cashListRequest);
        m.put("thing4", new WXTemplateDataVo(cashList.getStoreName()));
        m.put("thing3", new WXTemplateDataVo(cashList.getProjectName()));
        m.put("thing2", new WXTemplateDataVo(cashList.getServiceZhonggongOneStaffName()));
        m.put("date6", new WXTemplateDataVo(DateUtils.ymdFormat(cashList.getCashDate())));
        m.put("thing1", new WXTemplateDataVo("请对本次服务进行评价！"));
        wxMssVo.setData(m);
        ResponseEntity<String> responseEntity =
                restTemplate.postForEntity(url, wxMssVo, String.class);
        log.error("返回信息", responseEntity);

        genericResponse.setCodeAndMsg(ResponseCode.OK);
        genericResponse.setData(responseEntity);
        return genericResponse;
    }
}
