package com.ff.weijinxiao.controller;


import com.ff.weijinxiao.domain.CUser;
import com.ff.weijinxiao.domain.AccountBook;
import com.ff.weijinxiao.domain.UserInfo;
import com.ff.weijinxiao.jwt.JwtHelper;
import com.ff.weijinxiao.service.CUserService;
import com.ff.weijinxiao.service.AccountBookService;
import com.ff.weijinxiao.service.UserInfoService;
import com.ff.weijinxiao.util.JsonTool;
import com.ff.weijinxiao.util.RandomUtil;
import com.ff.weijinxiao.util.ResultTool;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 记账本接口
 */
@RestController
@RequestMapping("api/accountbook")
@Api(value = "记账本controller", tags = {"记账本接口"})
public class AccountBookController {

    @Resource
    private AccountBookService accountBookService;

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private CUserService cUserService;

    public UserInfo getUserInfoByToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            return null;
        }
        String openId = JwtHelper.parseToken(token);
        if (StringUtils.isBlank(openId)) {
            return null;
        }

        CUser cUser = cUserService.findByOpenId(openId);
        if (null == cUser) {
            return null;
        }
        return cUser.getUserInfo();
    }

    @PostMapping("/update")
    @ApiOperation(value = "更新记账本信息", notes = "更新记账本信息")
    public Map<String, Object> updateAccountBook(@RequestBody AccountBook accountBook, HttpServletRequest request) {
        try {
            accountBookService.saveAccountBook(accountBook);
            return ResultTool.genSuccessResult("修改成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "修改失败:" + e.getMessage());
        }
    }

    @PostMapping("/create")
    @ApiOperation(value = "创建记账本信息", notes = "创建记账本信息")
    public Map<String, Object> saveAccountBook(@RequestBody AccountBook accountBook, HttpServletRequest request) {
        try {
            accountBookService.saveAccountBook(accountBook);
            return ResultTool.genSuccessResult("创建成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "创建失败:" + e.getMessage());
        }
    }


    @PostMapping("/delete")
    @ApiOperation(value = "删除记账本信息", notes = "删除记账本信息")
    public Map<String, Object> deleteAccountBook(@ApiParam(required = true, value = "记账本id") @RequestBody String jsonId) {
        Integer id = JsonTool.parseJsonIdStr(jsonId);
        if (id < 0) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "id参数错误");
        }
        AccountBook accountBook = accountBookService.findById(id);
        if (null == accountBook) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "记账本不存在");
        }
        accountBook.setIsDelete(1);
        accountBookService.saveAccountBook(accountBook);
        return ResultTool.genSuccessResult("删除成功");
    }

    @GetMapping("/findbyid")
    @ApiOperation(value = "根据id查询记账本信息", notes = "根据id查询记账本信息")
    public Map<String, Object> findById(@ApiParam(required = true, value = "记账本id") @RequestParam String id,
                                        HttpServletRequest request) {

        Map<String, Object> result = new HashMap<>();
        try {
            AccountBook accountBook = accountBookService.findById(Integer.valueOf(id));
            if (null != accountBook) {
                result.put("data", accountBook);
                result.put("message", "查询成功");
                result.put("code", ResultTool.SuccessCode);
            } else {
                result.put("message", "查询失败，没有结果");
                result.put("code", ResultTool.ErrorCode_1);
            }

        } catch (Exception e) {
            e.printStackTrace();
            result.put("message", "查询失败" + e.getMessage());
            result.put("code", ResultTool.ErrorCode_2);
        }

        return result;
    }


    @GetMapping("/list")
    @ApiOperation(value = "查询记账本列表", notes = "查询记账本列表")
    public Map<String, Object> findList(@ApiParam(required = false, value = "记账本名字") @RequestParam(required = false) String phone,
                                        HttpServletRequest request) {

        Map<String, Object> result = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        param.put("GT_id", 0);
        param.put("EQ_isDelete", 0);
        if (null != phone && phone.length() > 0) {
            param.put("LIKE_phone", phone);
        }
        List<AccountBook> list = accountBookService.findList(param);
        if (null != list && list.size() > 0) {
            result.put("data", list);
            result.put("total", list.size());
            result.put("message", "查询成功");
            result.put("code", 10000);
        } else {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "没有查询到数据");
        }

        return result;
    }

    @GetMapping("/listpage")
    @ApiOperation(value = "查询记账本分页列表", notes = "查询记账本分页列表")
    public Map<String, Object> findListPage(@ApiParam(required = false, value = "记账本电话") @RequestParam(required = false) String phone,
                                            @ApiParam(required = false, value = "页码 1开始") @RequestParam(required = false) Integer pageNo,
                                            @ApiParam(required = false, value = "每页显示条数 默认10") @RequestParam(required = false) Integer pageSize) {

        Map<String, Object> result = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        if (null == pageNo) {
            pageNo = 1;
        } else if (pageNo < 1) {
            pageNo = 1;
        }
        if (null == pageSize) {
            pageSize = 10;
        }
        param.put("GT_id", 0);
        param.put("EQ_isDelete", 0);
        if (null != phone && phone.length() > 0) {
            param.put("LIKE_phone", phone);
        }

        Page<AccountBook> list = accountBookService.findPage(pageNo, pageSize, param, null);
        if (null != list && list.getTotalElements() > 0) {
            result.put("data", list);
            result.put("message", "分页查询成功");
            result.put("code", 10000);
        } else {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "没有查询到数据");
        }

        return result;
    }

    @PostMapping("/wxapi/create")
    @ApiOperation(value = "创建账本信息", notes = "创建账本信息")
    public Map<String, Object> createAccountBook(@RequestBody AccountBook accountBook, HttpServletRequest request) {
        try {
            accountBook.setOnlyID(RandomUtil.genOnlyId());
            UserInfo userInfo = getUserInfoByToken(request);
            if (null != userInfo) {
                accountBook.setUid(userInfo.getUid());
            }
            List<UserInfo> userInfos = new ArrayList<>();
            userInfos.add(userInfo);
            accountBook.setUserInfos(userInfos);
            accountBookService.saveAccountBook(accountBook);
            userInfo.setAccountBookId(accountBook.getId());
            userInfoService.saveUserInfo(userInfo);
            //设置其他账本为非默认账本
            //accountBookService.setNoneDefaultByUidAndId(userInfo.getUid(), accountBook.getId());
            return ResultTool.genSuccessResult("创建账本信息成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "创建账本信息失败:" + e.getMessage());
        }
    }

    @PostMapping("/wxapi/update")
    @ApiOperation(value = "更新记账本信息", notes = "更新记账本信息")
    public Map<String, Object> wxupdateAccountBook(@RequestBody AccountBook accountBook, HttpServletRequest request) {
        try {
            accountBookService.saveAccountBook(accountBook);
            return ResultTool.genSuccessResult("修改成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "修改失败:" + e.getMessage());
        }
    }

    @GetMapping("/wxapi/list")
    @ApiOperation(value = "查询记账本分页列表", notes = "查询记账本分页列表")
    public Map<String, Object> wxfindListPage(@ApiParam(required = false, value = "账本名称") @RequestParam(required = false) String name,
                                              HttpServletRequest request) {

        Map<String, Object> result = new HashMap<>();
        UserInfo userInfo = getUserInfoByToken(request);
        if (null == userInfo) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "获取失败，未注册有效账号");
        }

        List<AccountBook> list = accountBookService.getMyAccountBooks(userInfo.getUid(), name);
        if (null != list && list.size() > 0) {
            for (AccountBook accountBook : list) {
                UserInfo user = userInfoService.findByUid(accountBook.getUid());
                accountBook.setUserName(user.getWechatName());
            }
            result.put("data", list);
            result.put("message", "分页查询成功");
            result.put("code", 10000);
        } else {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "没有查询到数据");
        }

        return result;
    }

    @GetMapping("/wxapi/findbyid")
    @ApiOperation(value = "根据id查询记账本信息", notes = "根据id查询记账本信息")
    public Map<String, Object> wxfindById(@ApiParam(required = true, value = "记账本id") @RequestParam String id,
                                          HttpServletRequest request) {

        Map<String, Object> result = new HashMap<>();
        try {
            AccountBook accountBook = accountBookService.findById(Integer.valueOf(id));
            if (null != accountBook) {
                UserInfo user = userInfoService.findByUid(accountBook.getUid());
                if (null != user) {
                    accountBook.setUserName(user.getWechatName());
                }
                result.put("data", accountBook);
                result.put("message", "查询成功");
                result.put("code", ResultTool.SuccessCode);
            } else {
                result.put("message", "查询失败，没有结果");
                result.put("code", ResultTool.ErrorCode_1);
            }

        } catch (Exception e) {
            e.printStackTrace();
            result.put("message", "查询失败" + e.getMessage());
            result.put("code", ResultTool.ErrorCode_2);
        }

        return result;
    }

    @PostMapping("/wxapi/setdefault")
    @ApiOperation(value = "设置默认记账本", notes = "设置默认记账本")
    public Map<String, Object> wxSetDefaultAccountBook(@ApiParam(required = true, value = "加入信息 格式: {\"accountBookId\":123}") @RequestBody String jsonStr, HttpServletRequest request) {
        try {
            UserInfo userInfo = getUserInfoByToken(request);
            if (null == userInfo) {
                return ResultTool.genFailResult(ResultTool.ErrorCode_1, "获取失败，未注册有效账号");
            }
            JSONObject json = JSONObject.fromObject(jsonStr);
            Integer accountBookId = json.getInt("accountBookId");
            AccountBook accountBook = accountBookService.findById(accountBookId);
            if (null == accountBook) {
                ResultTool.genFailResult(ResultTool.ErrorCode_2, "账本id错误");
            }
            userInfo.setAccountBookId(accountBookId);
            userInfoService.saveUserInfo(userInfo);
            return ResultTool.genSuccessResult("设置默认记账本成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "设置默认记账本失败:" + e.getMessage());
        }
    }

    @GetMapping("/wxapi/getdefault")
    @ApiOperation(value = "查询默认账本信息", notes = "查询默认账本信息")
    public Map<String, Object> wxGetDefaultAccountBook(HttpServletRequest request) {

        Map<String, Object> result = new HashMap<>();
        try {
            UserInfo userInfo = getUserInfoByToken(request);
            if (null == userInfo) {
                return ResultTool.genFailResult(ResultTool.ErrorCode_1, "获取失败，未注册有效账号");
            }
            if (null == userInfo.getAccountBookId()) {
                Map<String, Object> param = new HashMap<>();
                param.put("EQ_isDelete", 0);
                param.put("EQ_uid", userInfo.getUid());
                List<AccountBook> list = accountBookService.findList(param);
                if (null != list) {
                    userInfo.setAccountBookId(list.get(0).getId());
                    userInfoService.saveUserInfo(userInfo);
                }
            }
            AccountBook accountBook = accountBookService.findById(userInfo.getAccountBookId());
            if (null != accountBook) {
                result.put("data", accountBook);
                result.put("message", "查询成功");
                result.put("code", ResultTool.SuccessCode);
            } else {
                result.put("message", "查询失败，没有结果");
                result.put("code", ResultTool.ErrorCode_1);
            }

        } catch (Exception e) {
            e.printStackTrace();
            result.put("message", "查询失败" + e.getMessage());
            result.put("code", ResultTool.ErrorCode_2);
        }

        return result;
    }

    @PostMapping("/wxapi/join")
    @ApiOperation(value = "加入记账本", notes = "加入记账本")
    public Map<String, Object> wxJoinAccountBook(@ApiParam(required = true, value = "加入信息 格式: {\"accountBookId\":123,\"userIds\":[{userId:456},{userId:789}...]}") @RequestBody String jsonStr, HttpServletRequest request) {
        try {
            JSONObject json = JSONObject.fromObject(jsonStr);
            Integer accountBookId = json.getInt("accountBookId");
            if (null == accountBookId) {
                return ResultTool.genFailResult(ResultTool.ErrorCode_2, "加入失败，账本id不可以为空");
            }
            AccountBook accountBook = accountBookService.findById(accountBookId);
            if (null == accountBook) {
                return ResultTool.genFailResult(ResultTool.ErrorCode_2, "加入失败，账本不存在");
            }
            String uid = accountBook.getUid();//账本拥有人
            UserInfo accountBookOwner = userInfoService.findByUid(uid);
            if (null == accountBookOwner) {
                return ResultTool.genFailResult(ResultTool.ErrorCode_2, "账本信息错误");
            }
            Integer maxNum = accountBookOwner.getAccountBookNum();//账本最多可用人数
            if (null == maxNum) {
                maxNum = 1;
                accountBookOwner.setAccountBookNum(1);
                userInfoService.saveUserInfo(accountBookOwner);// 保存默认最多记账人数=1
            }
            JSONArray jsonArray = json.getJSONArray("userIds");

            List<UserInfo> userInfos = accountBook.getUserInfos();
            if (null == userInfos) {
                userInfos = new ArrayList<>();
            }
            Integer currentNum = userInfos.size();
            if (currentNum >= maxNum) {
                return ResultTool.genFailResult(ResultTool.ErrorCode_1, "已超出可用记账人数，请充值会员套餐");
            }
            if (null != jsonArray && jsonArray.size() > 0) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject ob = jsonArray.getJSONObject(i);
                    Integer userId = ob.getInt("userId");
                    UserInfo userInfo = userInfoService.findById(userId);
                    if (null != userInfos && !userInfos.contains(userInfo)) {
                        userInfos.add(userInfo);
                    }
                }
            }
            accountBook.setUserInfos(userInfos);
            accountBookService.saveAccountBook(accountBook);
            return ResultTool.genSuccessResult("加入账本成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "加入失败:" + e.getMessage());
        }
    }


    @PostMapping("/wxapi/left")
    @ApiOperation(value = "退出记账本", notes = "退出记账本")
    public Map<String, Object> wxLeftAccountBook(@ApiParam(required = true, value = "离开信息 格式: {\"accountBookId\":123,\"userIds\":[{userId:456},{userId:789}...]}") @RequestBody String jsonStr, HttpServletRequest request) {
        try {
            JSONObject json = JSONObject.fromObject(jsonStr);
            Integer accountBookId = json.getInt("accountBookId");
            if (null == accountBookId) {
                ResultTool.genFailResult(ResultTool.ErrorCode_2, "退出失败，账本id不可以为空");
            }
            AccountBook accountBook = accountBookService.findById(accountBookId);
            if (null == accountBook) {
                ResultTool.genFailResult(ResultTool.ErrorCode_2, "退出失败，账本不存在");
            }
            JSONArray jsonArray = json.getJSONArray("userIds");
            List<UserInfo> userInfos = accountBook.getUserInfos();
            if (null == userInfos) {
                userInfos = new ArrayList<>();
            }
            if (null != jsonArray && jsonArray.size() > 0) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject ob = jsonArray.getJSONObject(i);
                    Integer userId = ob.getInt("userId");
                    UserInfo userInfo = userInfoService.findById(userId);
                    if (null != userInfos && userInfos.contains(userInfo)) {
                        userInfos.remove(userInfo);
                    }
                }
            }
            accountBook.setUserInfos(userInfos);
            accountBookService.saveAccountBook(accountBook);
            return ResultTool.genSuccessResult("退出账本成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "退出失败:" + e.getMessage());
        }
    }

    @PostMapping("/wxapi/delete")
    @ApiOperation(value = "删除记账本信息", notes = "删除记账本信息")
    public Map<String, Object> wxdeleteAccountBook(@ApiParam(required = true, value = "记账本id") @RequestBody String jsonId) {
        Integer id = JsonTool.parseJsonIdStr(jsonId);
        if (id < 0) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "id参数错误");
        }
        AccountBook accountBook = accountBookService.findById(id);
        if (null == accountBook) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "记账本不存在");
        }
        accountBook.setIsDelete(1);
        accountBookService.saveAccountBook(accountBook);
        return ResultTool.genSuccessResult("删除成功");
    }
}
