package com.ff.weijinxiao.controller;


import com.ff.weijinxiao.domain.*;
import com.ff.weijinxiao.jwt.JwtHelper;
import com.ff.weijinxiao.service.*;
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.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

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

/**
 * 供应商还款接口
 */
@RestController
@RequestMapping("api/supplierpayback")
@Api(value = "供应商还款controller", tags = {"供应商还款接口"})
public class SupplierPayBackController {

    @Resource
    private SupplierPayBackService supplierPayBackService;

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private CUserService cUserService;

    @Resource
    private SupplierService supplierService;

    @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> updateSupplierPayBack(@RequestBody SupplierPayBack supplierPayBack, HttpServletRequest request) {
        try {
            supplierPayBackService.saveSupplierPayBack(supplierPayBack);
            return ResultTool.genSuccessResult("修改成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "修改失败:" + e.getMessage());
        }
    }

    @PostMapping("/create")
    @ApiOperation(value = "创建供应商还款信息", notes = "创建供应商还款信息")
    public Map<String, Object> saveSupplierPayBack(@RequestBody SupplierPayBack supplierPayBack, HttpServletRequest request) {
        try {
            supplierPayBack.setIsDelete(0);
            supplierPayBackService.saveSupplierPayBack(supplierPayBack);
            return ResultTool.genSuccessResult("创建成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "创建失败:" + e.getMessage());
        }
    }


    @PostMapping("/delete")
    @ApiOperation(value = "删除供应商还款信息", notes = "删除供应商还款信息")
    public Map<String, Object> deleteSupplierPayBack(@ApiParam(required = true, value = "供应商还款id") @RequestBody String jsonId) {
        Integer id = JsonTool.parseJsonIdStr(jsonId);
        if (id < 0) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "id参数错误");
        }
        SupplierPayBack supplierPayBack = supplierPayBackService.findById(id);
        if (null == supplierPayBack) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "供应商还款不存在");
        }
        supplierPayBack.setIsDelete(1);
        supplierPayBackService.saveSupplierPayBack(supplierPayBack);
        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 {
            SupplierPayBack supplierPayBack = supplierPayBackService.findById(Integer.valueOf(id));
            if (null != supplierPayBack) {
                result.put("data", supplierPayBack);
                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<SupplierPayBack> list = supplierPayBackService.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<SupplierPayBack> list = supplierPayBackService.findPage(pageNo, pageSize, param);
        if (null != list && list.getTotalElements() > 0) {
            List<SupplierPayBack> data = list.getContent();
            for (SupplierPayBack supplierPayBack : data) {
                UserInfo userInfo = userInfoService.findByUid(supplierPayBack.getUid());
                if (null != userInfo) {
                    supplierPayBack.setUserName(userInfo.getWechatName());
                }
            }
            result.put("data", list);
            result.put("message", "分页查询成功");
            result.put("code", 10000);
        } else {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "没有查询到数据");
        }

        return result;
    }

    @PostMapping("/wxapi/update")
    @ApiOperation(value = "更新供应商还款信息", notes = "更新供应商还款信息")
    public Map<String, Object> wxupdateSupplierPayBack(@RequestBody SupplierPayBack supplierPayBack, HttpServletRequest request) {
        try {
            supplierPayBackService.saveSupplierPayBack(supplierPayBack);
            return ResultTool.genSuccessResult("修改成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "修改失败:" + e.getMessage());
        }
    }

    @PostMapping("/wxapi/create")
    @ApiOperation(value = "创建供应商还款信息", notes = "创建供应商还款信息")
    public Map<String, Object> wxsaveSupplierPayBack(@RequestBody SupplierPayBack supplierPayBack,
                                                     HttpServletRequest request) {
        try {
            Supplier supplier = supplierService.findByOnlyID(supplierPayBack.getSupplier().getOnlyID());
            if (null == supplier) {
                return ResultTool.genFailResult(ResultTool.ErrorCode_2, "创建失败，供应商不存在");
            }
            supplierPayBack.setSupplier(supplier);
            supplierPayBack.setOnlyID(RandomUtil.genOnlyId());
            supplierPayBack.setIsDelete(0);
            UserInfo userInfo = getUserInfoByToken(request);
            if (null != userInfo) {
                supplierPayBack.setUid(userInfo.getUid());
            }
            AccountBook accountBook = accountBookService.getDefaultAccountBook(userInfo);
            supplierPayBack.setAccountBook(accountBook);//设置默认账本
            supplierPayBackService.saveSupplierPayBack(supplierPayBack);
            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 = false, value = "供应商onlyid") @RequestParam(required = false) String supplierOnlyId,
                                              @ApiParam(required = false, value = "供应商电话") @RequestParam(required = false) String phone,
                                              @ApiParam(required = false, value = "供应商姓名") @RequestParam(required = false) String name,
                                              @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<>();
        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_customer.phone", phone);
        }
        if (null != name && name.length() > 0) {
            param.put("LIKE_customer.name", name);
        }
        UserInfo userInfo = getUserInfoByToken(request);
        if (null == userInfo) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "获取失败，未注册有效账号");
        }
        //param.put("EQ_uid", userInfo.getUid());
        param.put("EQ_accountBook.id", userInfo.getAccountBookId());
        if (StringUtils.isNotBlank(supplierOnlyId)) {
            Supplier supplier = supplierService.findByOnlyID(supplierOnlyId);
            if (null == supplier) {
                return ResultTool.genFailResult(ResultTool.ErrorCode_2, "获取失败，供应商不存在");
            }
            param.put("EQ_supplier.onlyID", supplier.getOnlyID());
        }
        Page<SupplierPayBack> list = supplierPayBackService.findPage(pageNo, pageSize, param);
        if (null != list && list.getTotalElements() > 0) {
            List<SupplierPayBack> data = list.getContent();
            for (SupplierPayBack supplierPayBack : data) {
                supplierPayBack.setUserName(userInfo.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 {
            SupplierPayBack supplierPayBack = supplierPayBackService.findById(Integer.valueOf(id));
            if (null != supplierPayBack) {
                result.put("data", supplierPayBack);
                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> wxdeleteSupplierPayBack(@ApiParam(required = true, value = "供应商还款id") @RequestBody String jsonId) {
        Integer id = JsonTool.parseJsonIdStr(jsonId);
        if (id < 0) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "id参数错误");
        }
        SupplierPayBack supplierPayBack = supplierPayBackService.findById(id);
        if (null == supplierPayBack) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "供应商还款不存在");
        }
        supplierPayBack.setIsDelete(1);
        supplierPayBackService.saveSupplierPayBack(supplierPayBack);
        return ResultTool.genSuccessResult("删除成功");
    }

}
