package com.iotechn.unimall.admin.api.user;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.iotechn.unimall.core.exception.AdminServiceException;
import com.iotechn.unimall.core.exception.ExceptionDefinition;
import com.iotechn.unimall.core.exception.ServiceException;
import com.iotechn.unimall.data.domain.UserDO;
import com.iotechn.unimall.data.dto.shop.FuziDTO;
import com.iotechn.unimall.data.mapper.UserMapper;
import com.iotechn.unimall.data.model.Page;
import okhttp3.*;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.*;
import java.net.CookieStore;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: kbq
 * Date: 2019-07-11
 * Time: 下午7:57
 */
@Service
public class AdminUserServiceImpl implements AdminUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addUser(Long adminId, UserDO user) throws ServiceException {
        if (user == null){
            throw new AdminServiceException(ExceptionDefinition.USER_INFORMATION_MISSING);
        }
        if(user.getPhone() == null){
            throw new AdminServiceException(ExceptionDefinition.USER_INFORMATION_MISSING);
        }
        if(userMapper.selectCount(new EntityWrapper<UserDO>().eq("phone",user.getPhone())) > 0){
            throw new AdminServiceException(ExceptionDefinition.USER_PHONE_ALREADY_EXIST);
        }
        Date now = new Date();
        user.setId(null);
        user.setPassword(Md5Crypt.md5Crypt(user.getPassword().getBytes(), "$1$" + user.getPhone().substring(0,7)));
        user.setGmtCreate(now);
        user.setGmtUpdate(now);
        return userMapper.insert(user) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteUser(Long adminId, Long id, String nickname) throws ServiceException {
        return userMapper.delete(new EntityWrapper<UserDO>()
                .eq("id", id)
                .eq("nickname",nickname)) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateUser(Long adminId, UserDO user) throws ServiceException {
        if (user == null || user.getId() == null){
            throw new AdminServiceException(ExceptionDefinition.USER_INFORMATION_MISSING);
        }
        if(user.getPhone() == null){
            throw new AdminServiceException(ExceptionDefinition.USER_INFORMATION_MISSING);
        }
        if(userMapper.selectCount(new EntityWrapper<UserDO>().eq("phone",user.getPhone()).notIn("id",user.getId())) > 0){
            throw new AdminServiceException(ExceptionDefinition.USER_PHONE_ALREADY_EXIST);
        }
        Date now = new Date();
        user.setGmtUpdate(now);
        UserDO userDO  = userMapper.selectById(user.getId());
        if(userDO.getPassword().equals(user.getPassword())){
            return userMapper.updateById(user) > 0;
        }
        if(user.getPassword() != null) {
            user.setPassword(Md5Crypt.md5Crypt(user.getPassword().getBytes(), "$1$" + user.getPhone().substring(0, 7)));
        }
        return userMapper.updateById(user) > 0;
    }

    @Override
    public Boolean updateStatus(Long adminId, Long userId,Integer status) throws ServiceException {
        if(userId == null || status == null || (status != 0 && status != 1)){
            throw new AdminServiceException(ExceptionDefinition.USER_INFORMATION_MISSING);
        }
        UserDO userDO = new UserDO();
        userDO.setId(userId);
        userDO.setStatus(status);
        userDO.setGmtUpdate(new Date());
        if(userMapper.updateById(userDO) > 0){
            return true;
        }
        return false;
    }

    @Override
    public Page<UserDO> getUser(Long adminId, Long id, String nickname, Integer level, Integer gender, Integer status,Integer pageNo,Integer limit) throws ServiceException {
        Integer count = userMapper. countUser(id,nickname,level,gender,status);
        List<UserDO> userDOList = userMapper.getUserList(id,nickname,level,gender,status,limit*(pageNo-1),limit);
        Page<UserDO> page = new Page<UserDO>(userDOList,pageNo,limit,count);
        return page;
    }

    @Override
    public String test(String param) throws Exception {

        String cookieVal = "shoppingCartSessionId=8ca49ed8d30b67e4c4136cfe52ca277f; kfz_uuid=97743462-cbc0-439b-b75d-1aa4bb0939ed; reciever_area=18005000000; PHPSESSID=267e4bbaafbbb5413cd4f7be3e601f79399a2a00; kfz_trace=97743462-cbc0-439b-b75d-1aa4bb0939ed|12179203|01e2236b05e0e5d2|; acw_tc=2760828c16537216057521740ed2e98094ffe4c6944af0e72de8dfc7e09466";
//        String url = "https://login.kongfz.com/Pc/Login/account";
//        String username = "天热打空调";
//        String password = "qq19961218";
//        Headers.Builder builder = new Headers.Builder();
//        builder.add("Content-Type", "application/x-www-form-urlencoded");
//        Headers headers = builder.build();
//        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
//                .addFormDataPart("loginName", username)
//                .addFormDataPart("loginPass", password)
//                .build();
//        Response response1 = postData(url, headers, body);
//        System.out.println(response1.code());
//        //拿到cookie
//        String header = response1.header("Set-Cookie");
//        System.out.println(header);

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet get = new HttpGet("https://shop.kongfz.com/buyer/order/getOrderInfo/?orderId="+param);
        try{
            //这里可以设置请求参数，token等
            get.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
            get.addHeader("cookie",cookieVal);
            HttpResponse response = httpClient.execute(get);//执行获取响应
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){//根据状态码处理
                //返回字符串
                String res = unicodeToString(EntityUtils.toString(response.getEntity(),"UTF-8"));
                System.out.println(res);
                JSONObject datas = JSONObject.parseObject(res);//转换成JSON格式
                Boolean status = (Boolean) datas.get("status");//获取返回数据状态，get获取的字段需要根据提供的返回值去获取
                FuziDTO data = new FuziDTO();
                if (status) {//返回的状态
                    data = JSONObject.parseObject(datas.get("data").toString(),FuziDTO.class);//"data"是根据返回值设定
                }
                return res;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        return cookieVal;
    }
    /**
     * Unicode转 汉字字符串
     *
     * @param str
     *            \u6728
     * @return '木' 26408
     */
    public static String unicodeToString(String str) {

        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
        Matcher matcher = pattern.matcher(str);
        char ch;
        while (matcher.find()) {
            // group 6728
            String group = matcher.group(2);
            // ch:'木' 26408
            ch = (char) Integer.parseInt(group, 16);
            // group1 \u6728
            String group1 = matcher.group(1);
            str = str.replace(group1, ch + "");
        }
        return str;
    }
    public static Response postData(String url, Headers headers, RequestBody body) {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();

        Request request = new Request.Builder()
                .url(url)
                .method("POST", body)
                .headers(headers)
                .build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }
}
