package com.gxwebsoft.shop.controller;

import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.shop.service.UsersService;
import com.gxwebsoft.shop.entity.Users;
import com.gxwebsoft.shop.param.UsersParam;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.system.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 控制器
 *
 * @author 科技小王子
 * @since 2024-07-12 01:10:04
 */
@Api(tags = "会员管理")
@RestController
@RequestMapping("/api/shop/users")
public class UsersController extends BaseController {
    @Resource
    private UsersService usersService;

    @ApiOperation("分页查询")
    @GetMapping("/page")
    public ApiResult<PageResult<Users>> page(UsersParam param) {
        // 使用关联查询
        return success(usersService.pageRel(param));
    }

    @ApiOperation("查询全部")
    @GetMapping()
    public ApiResult<List<Users>> list(UsersParam param) {
        // 使用关联查询
        return success(usersService.listRel(param));
    }

    @PreAuthorize("hasAuthority('shop:users:list')")
    @ApiOperation("根据id查询")
    @GetMapping("/{id}")
    public ApiResult<Users> get(@PathVariable("id") Integer id) {
        // 使用关联查询
        return success(usersService.getByIdRel(id));
    }

  @PreAuthorize("hasAnyAuthority('sys:auth:user')")
  @ApiOperation("根据手机查询用户")
  @GetMapping("/getByPhone")
  public ApiResult<Users> getByPhone(UsersParam param) {
    Users result;
    final List<Users> users = usersService.listRel(param);
    if (users.isEmpty()) {
      // 同步注册用户
      final Users addUsers = new Users();
      addUsers.setPhone(param.getPhone());
      addUsers.setUsername("微信用户");
      addUsers.setOpenId("");
      addUsers.setAvatarUrl("");
      addUsers.setGender(0);
      addUsers.setIsAdmin(2);
      addUsers.setCountry("");
      addUsers.setProvince("");
      addUsers.setCity("");
      long longValue = System.currentTimeMillis() / 1000;
      usersService.save(addUsers);
      result = addUsers;
    } else {
      result = param.getOne(users);
    }
    return success(result);
  }

  @ApiOperation("添加用户")
  @PostMapping()
  public ApiResult<?> save(@RequestBody Users users) {
    if (usersService.save(users)) {
      return success("添加成功");
    }
    return fail("添加失败");
  }

    @ApiOperation("修改")
    @PutMapping()
    public ApiResult<?> update(@RequestBody Users users) {
      if (usersService.updateById(users)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @ApiOperation("删除")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (usersService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @ApiOperation("批量添加")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<Users> list) {
        if (usersService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @ApiOperation("批量修改")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<Users> batchParam) {
        if (batchParam.update(usersService, "id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

  @ApiOperation("批量删除用户")
  @DeleteMapping("/batch")
  public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
    if (usersService.removeByIds(ids)) {
      return success("删除成功");
    }
    return fail("删除失败");
  }
  @ApiOperation("上传身份证")
  @GetMapping("/idCardOcr")
  public ApiResult<?> idCardOcr() throws IOException {
    String url = "https://idcardocrc.shumaidata.com/getidcardocrc";
    String appCode = "1e74aff57b2542359290e877975b8377";

    Map<String, String> params = new HashMap<>();
    //image 和 url 二选一 ，选择其中一个时，请注释另外一个参数,默认使用image
    //params.put("url", "http://.../image.jpg");
    params.put("url", "https://oss.wsdns.cn/20240710/56cef2c4269d4ec7967eedbac6765254.jpeg");
    String result = postForm(appCode, url, params);
    System.out.println(result);
    return success(result);
  }

  public static String postForm(String appCode, String url, Map<String, String> params) throws IOException {
    OkHttpClient client = new OkHttpClient.Builder().build();
    FormBody.Builder formbuilder = new FormBody.Builder();
    Iterator<String> it = params.keySet().iterator();
    while (it.hasNext()) {
      String key = it.next();
      formbuilder.add(key, params.get(key));
    }
    FormBody body = formbuilder.build();
    Request request = new Request.Builder().url(url).addHeader("Authorization", "APPCODE " + appCode).post(body).build();
    Response response = client.newCall(request).execute();
    System.out.println("返回状态码" + response.code() + ",message:" + response.message());
    String result = response.body().string();
    return result;
  }

}
