package com.ff.weijinxiao.controller;


import com.ff.weijinxiao.domain.AccountBook;
import com.ff.weijinxiao.domain.CUser;
import com.ff.weijinxiao.domain.Expend;
import com.ff.weijinxiao.domain.UserInfo;
import com.ff.weijinxiao.jwt.JwtHelper;
import com.ff.weijinxiao.service.AccountBookService;
import com.ff.weijinxiao.service.CUserService;
import com.ff.weijinxiao.service.ExpendService;
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 org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.ff.weijinxiao.controller.UserInfoController.getLastDayOfMonth;

/**
 * 支出接口
 */
@RestController
@RequestMapping("api/expend")
@Api(value = "支出controller", tags = {"支出接口"})
public class ExpendController {

    private Logger logger = LoggerFactory.getLogger(ExpendController.class);

    @Resource
    private ExpendService expendService;

    @Resource
    private CUserService cUserService;

    @Resource
    private AccountBookService accountBookService;

    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> updateExpend(@RequestBody Expend expend, HttpServletRequest request) {
        try {
            expendService.saveExpend(expend);
            return ResultTool.genSuccessResult("修改成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "修改失败:" + e.getMessage());
        }
    }

    @PostMapping("/create")
    @ApiOperation(value = "创建支出信息", notes = "创建支出信息")
    public Map<String, Object> saveExpend(@RequestBody Expend expend, HttpServletRequest request) {
        try {
            UserInfo userInfo = getUserInfoByToken(request);
            AccountBook accountBook = accountBookService.getDefaultAccountBook(userInfo);
            expend.setAccountBook(accountBook);
            expendService.saveExpend(expend);
            return ResultTool.genSuccessResult("创建成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "创建失败:" + e.getMessage());
        }
    }


    @PostMapping("/delete")
    @ApiOperation(value = "删除支出信息", notes = "删除支出信息")
    public Map<String, Object> deleteExpend(@ApiParam(required = true, value = "支出id") @RequestBody String jsonId) {
        Integer id = JsonTool.parseJsonIdStr(jsonId);
        if (id < 0) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "id参数错误");
        }
        Expend expend = expendService.findById(id);
        if (null == expend) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "支出不存在");
        }
        expend.setIsDelete(1);
        expendService.saveExpend(expend);
        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 {
            Expend expend = expendService.findById(Integer.valueOf(id));
            if (null != expend) {
                result.put("data", expend);
                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<Expend> list = expendService.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<Expend> list = expendService.findPage(pageNo, pageSize, param);
        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> createExpend(@RequestBody Expend expend, HttpServletRequest request) {
        try {
            expend.setOnlyID(RandomUtil.genOnlyId());
            UserInfo userInfo = getUserInfoByToken(request);
            if (null != userInfo) {
                expend.setUid(userInfo.getUid());
            }
            AccountBook accountBook = accountBookService.getDefaultAccountBook(userInfo);
            expend.setAccountBook(accountBook);
            expendService.saveExpend(expend);
            return ResultTool.genSuccessResult("增加支出成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "增加支出失败:" + e.getMessage());
        }
    }

    @GetMapping("/wxapi/listpage")
    @ApiOperation(value = "查询支出分页列表", notes = "查询支出分页列表")
    public Map<String, Object> wxfindListPage(@ApiParam(required = true, value = "统计维度 1=日 2=月 3=年 4=日期区间") @RequestParam Integer dim,
                                              @ApiParam(required = false, value = "指定统计日 格式yyyy-MM-dd") @RequestParam(required = false) String day,
                                              @ApiParam(required = false, value = "指定统计月 格式yyyy-MM") @RequestParam(required = false) String month,
                                              @ApiParam(required = false, value = "指定统计年 格式yyyy") @RequestParam(required = false) String year,
                                              @ApiParam(required = false, value = "当统计纬度为4时，开始日期:yyyy-MM-dd") @RequestParam(required = false) String beginDate,
                                              @ApiParam(required = false, value = "当统计纬度为4时，结束日期:yyyy-MM-dd") @RequestParam(required = false) String endDate,
                                              @ApiParam(required = false, value = "支出类型id") @RequestParam(required = false) Integer expendTypeId,
                                              @ApiParam(required = false, value = "页码 1开始") @RequestParam(required = false) Integer pageNo,
                                              @ApiParam(required = false, value = "每页显示条数 默认10") @RequestParam(required = false) Integer pageSize,
                                              HttpServletRequest request) {

        Map<String, Object> result = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        UserInfo userInfo = getUserInfoByToken(request);
        if (null == userInfo) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "登录信息获取失败");
        }
        if (null == pageNo) {
            pageNo = 1;
        } else if (pageNo < 1) {
            pageNo = 1;
        }
        if (null == pageSize) {
            pageSize = 10;
        }

        try {

            if (null == dim || dim < 1 || dim > 3) {
                dim = 1;
            }
            String beginTime = "";
            String endTime = "";
            if (dim == 1) {
                //按日
                String reportDay = "";
                if (StringUtils.isNotBlank(day)) {
                    reportDay = day;
                } else {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    reportDay = sdf.format(new Date());
                }
                beginTime = reportDay + " 00:00:00";
                endTime = reportDay + " 23:59:59";
                logger.info("beginTime:" + beginTime + " endTime:" + endTime);
            } else if (dim == 2) {
                //按月

                if (StringUtils.isBlank(month)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                    month = sdf.format(new Date());
                }
                beginTime = month + "-01 00:00:00";
                endTime = getLastDayOfMonth(Integer.valueOf(month.substring(0, 4)), Integer.valueOf(month.substring(5, 7))) + " 23:59:59";
                logger.info("beginTime:" + beginTime + " endTime:" + endTime);
            } else if (dim == 3) {
                //按年
                if (StringUtils.isBlank(year)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                    year = sdf.format(new Date());
                }
                beginTime = year + "-01-01 00:00:00";
                endTime = year + "-12-31 23:59:59";
                logger.info("beginTime:" + beginTime + " endTime:" + endTime);
            } else if (dim == 4) {
                if (StringUtils.isBlank(beginDate) || StringUtils.isBlank(endDate)) {
                    return ResultTool.genFailResult(ResultTool.ErrorCode_1, "开始日期和结束日期不能为空");
                }
                beginTime = beginDate + " 00:00:00";
                endTime = endDate + " 23:59：59";
                logger.info("beginTime:" + beginTime + " endTime:" + endTime);
            }

            param.put("GT_id", 0);
            param.put("EQ_isDelete", 0);
            if (null != expendTypeId) {
                param.put("EQ_expendType.id", expendTypeId);
            }
            param.put("GTE_dateStr", beginTime);
            param.put("LTE_dateStr", endTime);
            param.put("EQ_accountBook.id", userInfo.getAccountBookId());
            Page<Expend> list = expendService.findPage(pageNo, pageSize, param);
            if (null != list && list.getTotalElements() > 0) {
                List<Expend> data = list.getContent();
                for (Expend expend : data) {
                    expend.setUserName(userInfo.getWechatName());
                }
                result.put("data", list);
                result.put("message", "分页查询成功");
                result.put("code", 10000);
            } else {
                return ResultTool.genFailResult(ResultTool.ErrorCode_1, "没有查询到数据");
            }

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

        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 {
            Expend expend = expendService.findById(Integer.valueOf(id));
            if (null != expend) {
                result.put("data", expend);
                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/delete")
    @ApiOperation(value = "删除支出信息", notes = "删除支出信息")
    public Map<String, Object> wxdeleteExpend(@ApiParam(required = true, value = "支出id") @RequestBody String jsonId) {
        Integer id = JsonTool.parseJsonIdStr(jsonId);
        if (id < 0) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "id参数错误");
        }
        Expend expend = expendService.findById(id);
        if (null == expend) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "支出不存在");
        }
        //expend.setIsDelete(1);
        expendService.deleteById(id);
        return ResultTool.genSuccessResult("删除成功");
    }

    @PostMapping("/wxapi/update")
    @ApiOperation(value = "更新支出信息", notes = "更新支出信息")
    public Map<String, Object> wxupdateExpend(@RequestBody Expend expend, HttpServletRequest request) {
        try {
            expendService.saveExpend(expend);
            return ResultTool.genSuccessResult("修改成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "修改失败:" + e.getMessage());
        }
    }

}
