package com.ff.weijinxiao.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
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 net.sf.json.JSONArray;
import net.sf.json.JSONObject;
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/goodsbatch")
@Api(value = "商品进货批次controller", tags = {"商品进货批次接口"})
public class GoodsBatchController {

    private Logger logger = LoggerFactory.getLogger(GoodsBatchController.class);
    @Resource
    private GoodsBatchService goodsBatchService;

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private GoodsService goodsService;

    @Resource
    private AccountBookService accountBookService;


    @PostMapping("/update")
    @ApiOperation(value = "更新商品进货批次信息", notes = "更新商品进货批次信息")
    public Map<String, Object> updateGoodsBatch(@RequestBody GoodsBatch goodsBatch, HttpServletRequest request) {
        try {
            goodsBatchService.saveGoodsBatch(goodsBatch);
            return ResultTool.genSuccessResult("修改成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "修改失败:" + e.getMessage());
        }
    }

    @PostMapping("/create")
    @ApiOperation(value = "创建商品进货批次信息", notes = "创建商品进货批次信息")
    public Map<String, Object> saveGoodsBatch(@RequestBody GoodsBatch goodsBatch, HttpServletRequest request) {
        try {
            goodsBatchService.saveGoodsBatch(goodsBatch);
            return ResultTool.genSuccessResult("创建成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "创建失败:" + e.getMessage());
        }
    }


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

        return result;
    }


    @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("/wxapi/create")
    @ApiOperation(value = "进货接口--添加库存", notes = "进货接口--添加库存")
    public Map<String, Object> createGoodsBatch(@RequestBody GoodsBatch goodsBatch, HttpServletRequest request) {
        logger.info("createGoodsBatch: {}", goodsBatch);
        try {
            UserInfo userInfo = getUserInfoByToken(request);
            if (null == userInfo) {
                return ResultTool.genFailResult(ResultTool.ErrorCode_1, "操作失败，未注册有效账号");
            }
            //查询goods+uid是否存在，如果存在则更新商品，如果不存在，则创建商品
/*            Goods goods = goodsBatch.getGoods();
            if (null == goods) {
                return ResultTool.genFailResult(ResultTool.ErrorCode_1, "商品基本信息不可以为空");
            }
            if (null != goods.getUid()) {
                Goods check = goodsService.findByNameAndUid(goods.getName(), userInfo.getUid());
                if (null != check) {
                    goods.setId(check.getId());//更新商品
                }
            } else {
                goods.setUid(userInfo.getUid());
            }
            goods.setOnlyID(RandomUtil.genOnlyId());
            goodsService.saveGoods(goods);//新建、更新 商品*/
            AccountBook accountBook = accountBookService.getDefaultAccountBook(userInfo);
            goodsBatch.setAccountBook(accountBook);//设置默认账本
            //goodsBatch.setSubmitDate(DateUtil.date());进货日期前端传过来
            goodsBatch.setUid(userInfo.getUid());
            goodsBatch.setOnlyID(RandomUtil.genOnlyId());
            goodsBatch.setStockNumber(goodsBatch.getPurchaseNumber());
            goodsBatchService.saveGoodsBatch(goodsBatch);
            return ResultTool.genSuccessResult("创建成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "创建失败:" + e.getMessage());
        }
    }

    @PostMapping("/wxapi/update")
    @ApiOperation(value = "编辑商品库存", notes = "编辑商品库存")
    public Map<String, Object> wxupdateGoodsBatch(@RequestBody GoodsBatch goodsBatch, HttpServletRequest request) {
        logger.info("wxupdateGoodsBatch: {}", goodsBatch);
        try {
            UserInfo userInfo = getUserInfoByToken(request);
            if (null == userInfo) {
                return ResultTool.genFailResult(ResultTool.ErrorCode_1, "获取失败，未注册有效账号");
            }
            //查询goods+uid是否存在，如果存在则更新商品，如果不存在，则创建商品
            Goods goods = goodsService.findById(goodsBatch.getGoods().getId());
            if (null == goods) {
                return ResultTool.genFailResult(ResultTool.ErrorCode_2, "修改失败:商品不可以为空");
            }
/*            Goods check = goodsService.findByNameAndUid(goods.getName(), userInfo.getUid());
            if (null != check) {
                goods.setId(check.getId());//更新商品
            }
            goodsService.saveGoods(goods);//新建、更新 商品*/
            goodsBatchService.saveGoodsBatch(goodsBatch);
            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 name,
                                          @ApiParam(required = false, value = "条形码") @RequestParam(required = false) String goodsBarcode,
                                          HttpServletRequest request) {

        Map<String, Object> result = new HashMap<>();
        UserInfo userInfo = getUserInfoByToken(request);
        if (null == userInfo) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "获取失败，未注册有效账号");
        }
        Map<String, Object> param = new HashMap<>();
        param.put("GT_id", 0);
        param.put("EQ_isDelete", 0);
        if (null != name && name.length() > 0) {
            param.put("LIKE_goods.name", name);
        }
        if (StringUtils.isNotBlank(goodsBarcode)) {
            param.put("EQ_goodsBarcode", goodsBarcode);
        }
        //param.put("EQ_uid", userInfo.getUid());
        param.put("EQ_accountBook.id", userInfo.getAccountBookId());
        List<GoodsBatch> list = goodsBatchService.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("/wxapi/listbygroup")
    @ApiOperation(value = "按照商品分组搜索商品批次", notes = "按照商品分组搜索商品批次")
    public Map<String, Object> wxfindListByGoodsGroup(@ApiParam(required = false, value = "商品名称/条码") @RequestParam(required = false) String name,
                                                      @ApiParam(required = false, value = "库存状态 1=有库存 0=无库存 -1=临缺商品") @RequestParam(required = false) Integer stockStatus,
                                                      @ApiParam(required = false, value = "进货人uid") @RequestParam(required = false) String uid,
                                                      @ApiParam(required = false, value = "商品分类id") @RequestParam(required = false) Integer goodsCategoryId,
                                                      HttpServletRequest request) {
        logger.info("goodsBatch listbygroup {}", request.getHeader("token"));
        Map<String, Object> result = new HashMap<>();
        UserInfo userInfo = getUserInfoByToken(request);
        if (null == userInfo) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "获取失败，未注册有效账号");
        }
        Map<String, Object> param = new HashMap<>();
        param.put("GT_id", 0);
        param.put("EQ_isDelete", 0);
        if (StringUtils.isNotBlank(name)) {
            param.put("LIKE_name", name);
        }
        if (null != goodsCategoryId) {
            param.put("EQ_goodsCategory.id", goodsCategoryId);
        }
        //param.put("EQ_uid", userInfo.getUid());
        param.put("EQ_accountBook.id", userInfo.getAccountBookId());
        logger.info("goodsBatch listbygroup {}", userInfo.getAccountBookId());
        List<Goods> list = goodsService.findList(param);
        if (null != list && list.size() > 0) {
            List<Object> data = new ArrayList<>();
            Double totalStockAmount = 0.0;
            Double totalMoney = 0.0;
            for (Goods goods : list) {
                Map<String, Object> map = new HashMap<>();
                Map<String, Object> param1 = new HashMap<>();
                param1.put("GT_id", 0);
                param1.put("EQ_isDelete", 0);
                param1.put("EQ_goods.onlyID", goods.getOnlyID());
/*                if (StringUtils.isNotBlank(name)) {
                    param1.put("LIKE_goodsBarcode", name);
                }*/
                if (null != stockStatus) {
                    if (stockStatus == 1) {
                        param1.put("GT_stockNumber", 0);
                    } else if (stockStatus == 0) {
                        param1.put("EQ_stockNumber", 0);
                    } else if (stockStatus == -1) {
                        param1.put("LT_stockNumber", 0);
                    }
                }
                if (StrUtil.isNotBlank(uid)) {
                    param1.put("EQ_uid", uid);
                }
                goods.setUserName(userInfoService.findByUid(goods.getUid()).getWechatName());
                List<GoodsBatch> list1 = goodsBatchService.findList(param1);
                List<Object> list2 = new ArrayList<>();
                Double goodsStockAmount = 0.0;
                if (null != list1 && list1.size() > 0) {
                    for (GoodsBatch goodsBatch : list1) {
                        Map<String, Object> goodsBatchMap = new HashMap<>();
                        if (null != goodsBatch.getUid()) {
                            goodsBatch.setUserName(userInfoService.findByUid(goodsBatch.getUid()).getWechatName());
                        }
                        Double stockNumber = goodsBatch.getStockNumber();
                        goodsBatchMap.put("goodsBatch", goodsBatch);
                        goodsBatchMap.put("stockAmount", stockNumber);
                        list2.add(goodsBatchMap);
                        if (null != stockNumber) {
                            totalStockAmount += stockNumber;
                            goodsStockAmount += stockNumber;
                            totalMoney += stockNumber * goodsBatch.getPurchasePrice();
                        }

                    }
                }
                map.put("goods", goods);//商品信息
                map.put("goodsStockAmount", goodsStockAmount);//商品库存
                map.put("goodsBatchList", list2);//批次信息 = 商品批次 + 批次库存信息
                data.add(map);
            }
            result.put("data", data);
            result.put("total", list.size());//商品种类
            result.put("stockAmount", totalStockAmount);//库存总数
            result.put("totalMoney", totalMoney);//总占用金
            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) {
        logger.info("goodsBatch findbyid {}", id);
        Map<String, Object> result = new HashMap<>();
        try {
            GoodsBatch goodsBatch = goodsBatchService.findById(Integer.valueOf(id));
            if (null != goodsBatch) {
                result.put("data", goodsBatch);
                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/deletebatch")
    @ApiOperation(value = "批量删除商品进货批次信息", notes = "批量删除商品进货批次信息")
    public Map<String, Object> wxdeleteGoodsBatchs(@ApiParam(required = true, value = "商品进货批次ids 格式: {\"ids\":[{id:456},{id:789}...]}") @RequestBody String jsonIds) {
        JSONObject json = JSONObject.fromObject(jsonIds);
        JSONArray jsonArray = json.getJSONArray("ids");
        if (null != jsonArray && jsonArray.size() > 0) {
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject ob = jsonArray.getJSONObject(i);
                Integer id = ob.getInt("id");
                GoodsBatch goodsBatch = goodsBatchService.findById(id);
                if (null != goodsBatch) { ;
                    goodsBatchService.deleteById(id);
                }
            }
        }
        return ResultTool.genSuccessResult("批量删除成功");
    }
}
