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

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

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

    @Resource
    private SupplierService supplierService;

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private CUserService cUserService;

    @Resource
    private GoodsBatchService goodsBatchService;

    @Resource
    private AccountBookService accountBookService;


    @PostMapping("/update")
    @ApiOperation(value = "更新供应商信息", notes = "更新供应商信息")
    public Map<String, Object> updateSupplier(@RequestBody Supplier supplier, HttpServletRequest request) {
        try {
            supplierService.saveSupplier(supplier);
            return ResultTool.genSuccessResult("修改成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "修改失败:" + e.getMessage());
        }
    }

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


    @PostMapping("/delete")
    @ApiOperation(value = "删除供应商信息", notes = "删除供应商信息")
    public Map<String, Object> deleteSupplier(@ApiParam(required = true, value = "供应商id") @RequestBody String jsonId) {
        Integer id = JsonTool.parseJsonIdStr(jsonId);
        if (id < 0) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "id参数错误");
        }
        Supplier supplier = supplierService.findById(id);
        if (null == supplier) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "供应商不存在");
        }
        supplier.setIsDelete(1);
        supplierService.saveSupplier(supplier);

        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 {
            Supplier supplier = supplierService.findById(Integer.valueOf(id));
            if (null != supplier) {
                result.put("data", supplier);
                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 supplierName,
                                        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 != supplierName && supplierName.length() > 0) {
            param.put("LIKE_name", supplierName);
        }
        List<Supplier> list = supplierService.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 supplierName,
                                            @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 != supplierName && supplierName.length() > 0) {
            param.put("LIKE_name", supplierName);
        }
        Page<Supplier> list = supplierService.findPage(pageNo, pageSize, param);
        if (null != list && list.getTotalElements() > 0) {
            List<Supplier> data = list.getContent();
            for (Supplier supplier : data) {
                UserInfo userInfo = userInfoService.findByUid(supplier.getUid());
                if (null != userInfo) {
                    supplier.setUserName(userInfo.getWechatName());
                }
            }
            result.put("data", list);
            result.put("message", "分页查询成功");
            result.put("code", 10000);
        } else {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "没有查询到数据");
        }

        return result;
    }

    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("/wxapi/create")
    @ApiOperation(value = "创建供应商信息", notes = "创建供应商信息")
    public Map<String, Object> createSupplier(@RequestBody Supplier supplier, HttpServletRequest request) {
        logger.info("createSupplier");
        try {
            UserInfo userInfo = getUserInfoByToken(request);
            if (null != userInfo) {
                supplier.setUid(userInfo.getUid());
            }
            supplier.setOnlyID(RandomUtil.genOnlyId());
            AccountBook accountBook = accountBookService.getDefaultAccountBook(userInfo);
            if (null != accountBook) {
                supplier.setAccountBook(accountBook);
            }
            supplierService.saveSupplier(supplier);
            return ResultTool.genSuccessResult("创建成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "创建失败:" + e.getMessage());
        }
    }

    @PostMapping("/wxapi/update")
    @ApiOperation(value = "更新供应商信息", notes = "更新供应商信息")
    public Map<String, Object> wxupdateSupplier(@RequestBody Supplier supplier) {
        logger.info("wxupdateSupplier");
        try {
            supplierService.saveSupplier(supplier);
            return ResultTool.genSuccessResult("修改成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "修改失败:" + e.getMessage());
        }
    }

    @GetMapping("/wxapi/list")
    @ApiOperation(value = "根据关键字查询供应商列表", notes = "根据关键字查询供应商列表")
    public Map<String, Object> wxfindList(@ApiParam(required = false, value = "供应商名字/电话/地址") @RequestParam(required = false) String tag,
                                          HttpServletRequest request) {
        logger.info("supplier wxfindList {}", tag);
        Map<String, Object> result = new HashMap<>();
        UserInfo userInfo = getUserInfoByToken(request);
        if (null == userInfo) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "获取失败，未注册有效账号");
        }
        List<Supplier> list = supplierService.findListByAccountBook(userInfo.getAccountBookId(), tag);
        if (null != list && list.size() > 0) {
            List<Object> data = new ArrayList<>();
            for (Supplier supplier : list) {
                UserInfo userinfo = userInfoService.findByUid(supplier.getUid());
                if (null != userinfo) {
                    supplier.setUserName(userinfo.getWechatName());
                }
                Map<String, Object> map = new HashMap<>();
                map.put("supplier", supplier);
                List<Object[]> objects = supplierService.getSupplierExtInfo(userInfo.getUid(), supplier.getOnlyID());
                if (null != objects && objects.size() > 0) {
                    Object[] object = objects.get(0);
                    if (null != object[0]) {
                        map.put("totalPurchaseAmount", Double.parseDouble(object[0].toString()));//累计进货金额
                    } else {
                        map.put("totalPurchaseAmount", 0.0);
                    }
                    if (null != object[1]) {
                        map.put("needPay", Double.parseDouble(object[1].toString()));//应付款
                    } else {
                        map.put("needPay", 0.0);
                    }
                    if (null != object[2]) {
                        map.put("stcckNum", Double.parseDouble(object[2].toString()));//剩余库存
                    } else {
                        map.put("stcckNum", 0.0);
                    }
                }
                data.add(map);
            }
            result.put("data", data);
            result.put("total", list.size());//供应商总数
            logger.info("getCustomerListPage uid:" + userInfo.getUid());
            Double totalAmount = supplierService.getSupplierTotalAmount(userInfo.getUid());
            logger.info("getCustomerListPage totalAmount:" + totalAmount);
            Double alreadyPayed1 = supplierService.getSupplierAlreadyPayed1(userInfo.getUid());
            logger.info("getCustomerListPage alreadyPayed1:" + alreadyPayed1);
            Double alreadyPayed2 = supplierService.getSupplierAlreadyPayed2(userInfo.getUid());
            Double totalDiscount = supplierService.getSupplierDiscount(userInfo.getUid());
            logger.info("getCustomerListPage alreadyPayed2:" + alreadyPayed2);
            result.put("totalAmount", totalAmount);//总采购金额
            result.put("alreadyPayed", alreadyPayed1 + alreadyPayed2);//已付款
            result.put("needPay", totalAmount - alreadyPayed1 - alreadyPayed2 - totalDiscount);//应付款
            result.put("message", "查询成功");
            result.put("code", 10000);
        } else {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "没有查询到数据");
        }
        return result;
    }


    @GetMapping("/wxapi/findbyid")
    @ApiOperation(value = "根据id查询供应商信息", notes = "供应商详情")
    public Map<String, Object> wxfindById(@ApiParam(required = true, value = "供应商id") @RequestParam String id,
                                          HttpServletRequest request) {
        logger.info("supplier findbyid {}", id);
        Map<String, Object> result = new HashMap<>();
        try {
            Supplier supplier = supplierService.findById(Integer.valueOf(id));
            if (null != supplier) {
                UserInfo creatorUserInfo = userInfoService.findByUid(supplier.getUid());
                if(null != creatorUserInfo) {
                    supplier.setUserName(creatorUserInfo.getWechatName());
                }
                result.put("data", supplier);

                UserInfo userInfo = getUserInfoByToken(request);
                Double totalAmount = supplierService.getSupplierTotalAmountBySupplierOnlyId(userInfo.getUid(), supplier.getOnlyID());
                logger.info("getCustomerListPage totalAmount:" + totalAmount);
                Double alreadyPayed1 = supplierService.getSupplierAlreadyPayed1BySupplierOnlyId(userInfo.getUid(), supplier.getOnlyID());
                logger.info("getCustomerListPage alreadyPayed1:" + alreadyPayed1);
                Double alreadyPayed2 = supplierService.getSupplierAlreadyPayed2BySupplierOnlyId(userInfo.getUid(), supplier.getOnlyID());
                logger.info("getCustomerListPage alreadyPayed2:" + alreadyPayed2);
                Double totalDiscount = supplierService.getSupplierDiscountBySupplierOnlyId(userInfo.getUid(), supplier.getOnlyID());
                Double purchaseNum = supplierService.getSupplierPurchaseNumBySupplierOnlyId(userInfo.getUid(), supplier.getOnlyID());
                Double stockNum = supplierService.getSupplierStockNumBySupplierOnlyId(userInfo.getUid(), supplier.getOnlyID());
                result.put("totalAmount", totalAmount);//总进货金额
                result.put("sumAmount", totalAmount);//累计进货金额
                result.put("totalDiscount", totalDiscount);//总商家优惠
                result.put("purchaseNum", purchaseNum);//总商品数量
                result.put("stockNum", stockNum);//剩余库存
                result.put("alreadyPayed", alreadyPayed1 + alreadyPayed2);//已付款
                result.put("needPay", totalAmount - alreadyPayed1 - alreadyPayed2 - totalDiscount);//欠款
                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("/wxapi/findPurchaseRecord")
    @ApiOperation(value = "根据id查询供应商购买记录", notes = "根据id查询供应商购买记录")
    public Map<String, Object> findPurchaseRecord(@ApiParam(required = true, value = "供应商id") @RequestParam String id,
                                                  HttpServletRequest request) {
        logger.info("supplier findPurchaseRecord {}", id);
        Map<String, Object> result = new HashMap<>();
        try {
            Supplier supplier = supplierService.findById(Integer.valueOf(id));
            if (null != supplier) {
                UserInfo userInfo = getUserInfoByToken(request);
                supplier.setUserName(userInfo.getWechatName());
                Map<String, Object> param = new HashMap<>();
                param.put("EQ_supplier.id", id);
                param.put("EQ_uid", userInfo.getUid());
                List<GoodsBatch> goodsBatches = goodsBatchService.findList(param);
                if (null != goodsBatches && goodsBatches.size() > 0) {
                    for (GoodsBatch goodsBatch : goodsBatches) {
                        goodsBatch.setUserName(userInfo.getWechatName());
                    }
                }
                result.put("message", "查询成功");
                result.put("code", ResultTool.SuccessCode);
                result.put("data", goodsBatches);
            } 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> wxdeleteSupplier(@ApiParam(required = true, value = "供应商id") @RequestBody String jsonId) {
        Integer id = JsonTool.parseJsonIdStr(jsonId);
        if (id < 0) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "id参数错误");
        }
        Supplier supplier = supplierService.findById(id);
        if (null == supplier) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "供应商不存在");
        }
        supplier.setIsDelete(1);
        supplierService.saveSupplier(supplier);

        return ResultTool.genSuccessResult("删除成功");
    }
}
