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.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.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 客户接口
 */
@RestController
@RequestMapping("api/customer")
@Api(value = "客户controller", tags = {"客户接口"})
public class CustomerController {

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

    @Resource
    private CustomerService customerService;

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private CUserService cUserService;

    @Resource
    private CustomerPayBackService customerPayBackService;

    @Resource
    private CustomerAddressService customerAddressService;

    @Resource
    private OrderService orderService;

    @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> updateCustomer(@RequestBody Customer customer, HttpServletRequest request) {
        try {
            customerService.saveCustomer(customer);
            return ResultTool.genSuccessResult("修改成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "修改失败:" + e.getMessage());
        }
    }

    @PostMapping("/create")
    @ApiOperation(value = "创建客户信息", notes = "创建客户信息")
    public Map<String, Object> saveCustomer(@RequestBody Customer customer, HttpServletRequest request) {
        try {
            customerService.saveCustomer(customer);
            return ResultTool.genSuccessResult("创建成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "创建失败:" + e.getMessage());
        }
    }


    @PostMapping("/delete")
    @ApiOperation(value = "删除客户信息", notes = "删除客户信息")
    public Map<String, Object> deleteCustomer(@ApiParam(required = true, value = "客户id") @RequestBody String jsonId) {
        Integer id = JsonTool.parseJsonIdStr(jsonId);
        if (id < 0) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "id参数错误");
        }
        Customer customer = customerService.findById(id);
        if (null == customer) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "客户不存在");
        }
        customer.setIsDelete(1);
        customerService.saveCustomer(customer);
        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 {
            Customer customer = customerService.findById(Integer.valueOf(id));
            if (null != customer) {
                result.put("data", customer);
                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<Customer> list = customerService.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_tel", phone);
        }
        Page<Customer> list = customerService.findPage(pageNo, pageSize, null, param);
        if (null != list && list.getTotalElements() > 0) {
            List<Customer> data = list.getContent();
            for (Customer customer : data) {
                UserInfo userInfo = userInfoService.findByUid(customer.getUid());
                if (null != userInfo) {
                    customer.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> wxupdateCustomer(@RequestBody Customer customer, HttpServletRequest request) {
        try {
            customerService.saveCustomer(customer);
            return ResultTool.genSuccessResult("修改成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "修改失败:" + e.getMessage());
        }
    }

    @PostMapping("/wxapi/create")
    @ApiOperation(value = "创建客户信息", notes = "创建客户信息")
    public Map<String, Object> wxsaveCustomer(@RequestBody Customer customer,
                                              @ApiParam(required = false, value = "地址") @RequestParam(required = false) String address,
                                              HttpServletRequest request) {
        try {
            customer.setOnlyID(RandomUtil.genOnlyId());
            UserInfo userInfo = getUserInfoByToken(request);
            if (null != userInfo) {
                customer.setUid(userInfo.getUid());
            }
            AccountBook accountBook = accountBookService.getDefaultAccountBook(userInfo);
            if (null != accountBook) {
                customer.setAccountBook(accountBook);
            }
            customerService.saveCustomer(customer);
            CustomerAddress customerAddress = customerAddressService.findByAddressAndUid(address, userInfo.getUid());
            if (null == customerAddress) {
                customerAddress = new CustomerAddress();
                customerAddress.setAddress(address);
                customerAddress.setName(customer.getName());
                customerAddress.setTel(customer.getTel());
                customerAddress.setCustomer(customer);
                customerAddress.setUid(userInfo.getUid());
                customerAddress.setOnlyID(RandomUtil.genOnlyId());
                customerAddressService.saveCustomerAddress(customerAddress);
            }
            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 = "客户姓名或者电话") @RequestParam(required = false) String nameOrPhone,
                                              @ApiParam(required = false, value = "创建人uid") @RequestParam(required = false) String creatorUid,
                                              @ApiParam(required = false, value = "页码 1开始") @RequestParam(required = false) Integer pageNo,
                                              @ApiParam(required = false, value = "每页显示条数 默认10") @RequestParam(required = false) Integer pageSize,
                                              HttpServletRequest request) {
        logger.info("===getCustomerListPage: {},{}", nameOrPhone, creatorUid);
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        Map<String, Object> orParam = 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 != creatorUid && creatorUid.length() > 0) {
            param.put("EQ_uid", creatorUid);
        }
        if (StringUtils.isNotBlank(nameOrPhone)) {
            orParam.put("LIKE_tel", nameOrPhone);
            orParam.put("LIKE_name", nameOrPhone);
        }
        UserInfo userInfo = getUserInfoByToken(request);
        if (null == userInfo) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "获取失败，未注册有效账号");
        }
        param.put("EQ_accountBook.id", userInfo.getAccountBookId());
        Page<Customer> list = customerService.findPage(pageNo, pageSize, orParam, param);
        if (null != list && list.getTotalElements() > 0) {
            List<Customer> data = list.getContent();
            for (Customer customer : data) {
                customer.setUserName(userInfo.getWechatName());
                Double amount = customerService.getCustomerTotalAmountByCustomerOnlyId(userInfo.getUid(), customer.getOnlyID());
                customer.setAmount(amount);
                Double payed1 = customerService.getCustomerAleadyPayed1ByCostomerOnlyId(userInfo.getUid(), customer.getOnlyID());
                Double payed2 = customerService.getCustomerAleadyPayed2ByCostomerOnlyId(userInfo.getUid(), customer.getOnlyID());
                customer.setDebt(amount - payed1 - payed2);
            }
            result.put("data", list);
            result.put("total", list.getTotalElements());//客户总数
            logger.info("getCustomerListPage uid:" + userInfo.getUid());
            Double totalAmount = customerService.getCustomerTotalAmount(userInfo.getUid()); //订单金额
            logger.info("getCustomerListPage totalAmount:" + totalAmount);
            Double alreadyPayed1 = customerService.getCustomerAleadyPayed1(userInfo.getUid());//订单已收款
            logger.info("getCustomerListPage alreadyPayed1:" + alreadyPayed1);
            Double alreadyPayed2 = customerService.getCustomerAleadyPayed2(userInfo.getUid());//客户付款
            logger.info("getCustomerListPage alreadyPayed2:" + alreadyPayed2);
            result.put("totalAmount", totalAmount);//总采购金额
            result.put("totalPayed", alreadyPayed1 + alreadyPayed2);//已付款
            result.put("totalDebt", totalAmount - alreadyPayed1 - alreadyPayed2);//应付款
            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 {
            Customer customer = customerService.findById(Integer.valueOf(id));
            if (null != customer) {
                UserInfo creatorUserInfo = userInfoService.findByUid(customer.getUid());
                if (null != creatorUserInfo) {
                    customer.setUserName(creatorUserInfo.getWechatName());
                }
                result.put("data", customer);

                UserInfo userInfo = getUserInfoByToken(request);
                Map<String, Object> orderParam = new HashMap<>();
                orderParam.put("GT_id", 0);
                orderParam.put("EQ_isDelete", 0);
                orderParam.put("EQ_customer.id", customer.getId());
                orderParam.put("EQ_uid", userInfo.getUid());
                List<Order> orderList = orderService.findList(orderParam);
                Double totalAmount = 0.0;
                Double totalFreight = 0.0;
                Double totalPayed = 0.0;
                if (null != orderList && orderList.size() > 0) {
                    for (Order order : orderList) {
                        Double salesPrice = order.getSalesPrice();
                        if (null != salesPrice) {
                            totalAmount += salesPrice;
                        }
                        Double freight = order.getFreight();
                        if (null != freight) {
                            totalFreight += freight;
                        }
                        Float realReceive = order.getRealReceive();
                        if (null != realReceive) {
                            totalPayed += realReceive;
                        }
                    }
                }
                Double payed2 = customerService.getCustomerAleadyPayed2ByCostomerOnlyId(userInfo.getUid(), customer.getOnlyID());//已还款
                result.put("totalAmount", totalAmount);//总消费金额
                result.put("totalGoods", customerService.countCustomerBuyedGoods(userInfo.getUid(), customer.getOnlyID()));//商品数量
                result.put("totalFreight", totalFreight);//运费
                result.put("totalPayed", totalPayed + payed2);//已付款
                result.put("totalDebt", totalAmount - totalPayed - payed2);//欠款
                result.put("orderList", orderList);//购买记录
                Map<String, Object> payBackParam = new HashMap<>();
                payBackParam.put("GT_id", 0);
                payBackParam.put("EQ_isDelete", 0);
                payBackParam.put("EQ_customer.id", customer.getId());
                payBackParam.put("EQ_uid", userInfo.getUid());
                List<CustomerPayBack> payBackList = customerPayBackService.findList(payBackParam);
                if (null != payBackList) {
                    for (CustomerPayBack customerPayBack : payBackList) {
                        customerPayBack.setUserName(userInfo.getWechatName());
                    }
                }
                result.put("payBackList", payBackList);//还款记录
                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> wxdeleteCustomer(@ApiParam(required = true, value = "客户id") @RequestBody String jsonId) {
        Integer id = JsonTool.parseJsonIdStr(jsonId);
        if (id < 0) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "id参数错误");
        }
        Customer customer = customerService.findById(id);
        if (null == customer) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "客户不存在");
        }
        customer.setIsDelete(1);
        customerService.saveCustomer(customer);
        return ResultTool.genSuccessResult("删除成功");
    }

}
