package com.sifang.modules.supply.stock.controller;

import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.constant.TraderConstants;
import com.sifang.modules.customer.excel.FileExportUtil;
import com.sifang.modules.platform.service.AddressService;
import com.sifang.modules.platform.utils.AddressUtils;
import com.sifang.modules.q7link.utils.Q7DataUtil;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmTrader;
import com.sifang.modules.sunshine.SystemSetting.service.TraderService;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.supply.setting.service.CrmSupplyWarehouseSettingService;
import com.sifang.modules.supply.stock.dao.MaterialStockDao;
import com.sifang.modules.supply.stock.dao.SupplyMaterialDao;
import com.sifang.modules.supply.stock.entity.MaterialWarehouseStocks;
import com.sifang.modules.supply.stock.entity.SupplyMaterial;
import com.sifang.modules.supply.stock.excel.MaterialStockExcel;
import com.sifang.modules.supply.stock.request.AddStockReq;
import com.sifang.modules.supply.stock.request.AddStockVo;
import com.sifang.modules.supply.stock.request.MaterialStockSaveReq;
import com.sifang.modules.supply.stock.service.MaterialStockService;
import com.sifang.modules.supply.stock.utils.MaterialUtils;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.entity.Ascription;
import com.sifang.modules.sys.entity.Operator;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.web.BaseExceptionController;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author hongzq
 */
@Controller
@RequestMapping(value = "${adminPath}/material/")
public class StockManageController extends BaseExceptionController {

    @Autowired
    MaterialStockService materialStockService;
    @Autowired
    TraderService traderService;
    @Autowired
    CrmSupplyWarehouseSettingService crmSupplyWarehouseSettingService;
    @Autowired
    MaterialStockDao materialStockDao;
    @Autowired
    private AddressService addressService;
    @Autowired
    SupplyMaterialDao supplyMaterialDao;
    /**
     * 代理商库存页面
     */
    @RequestMapping(value = "stockList")
    public String stockList(HttpServletRequest request, Model model){

        User user = UserUtils.getUser();
        model.addAttribute("userType", user.getUserType());
        List<Record> pros = addressService.getProvinces();
        model.addAttribute("province", pros);
        MaterialUtils.returnModelMaterial(model,"2",user.getTopTraderId());
        if (StringUtils.endsWithAny(user.getUserType(), "1", "4")) {
            //供应链
            List<Record> traderList = traderService.getAllTopTrader();
            model.addAttribute("traderList", traderList);
//            List<Record> supplyList = crmSupplyWarehouseSettingService.getSupplyList();
//            model.addAttribute("supplyList",supplyList);
        }else {
            //供应商和代理商
            Ascription ascription = CrmUtils.getAscription();
            List<Record> warehouseList;
            if (Objects.equals(TraderConstants.TYPE_TWO, user.getTraderType())) {
                warehouseList = MaterialUtils.findWarehouseBySecondTrader(user.getTraderId());
            } else {
                warehouseList = MaterialUtils.findMaterialWarehouseByAscriptionId(ascription.getAscriptionId());
            }
            model.addAttribute("ascriptionId", ascription.getAscriptionId());
            model.addAttribute("wares", warehouseList);
        }
        return "modules/supply/material/traderStockList";
    }



    /**
     * 平台库存页面
     */
    @RequestMapping(value = "stockList2")
    public String stockList2(HttpServletRequest request, Model model){
        User user = UserUtils.getUser();
        model.addAttribute("userType", user.getUserType());
        MaterialUtils.returnModelMaterial(model,"",user.getTopTraderId());
        model.addAttribute("wares", MaterialUtils.getPlateWarehouse2());
//        if (StringUtils.endsWithAny(user.getUserType(), "1", "4")) {
            //供应链
//            List<Record> traderList = traderService.getAllTopTrader();
//            model.addAttribute("traderList", traderList);
            List<Record> supplyList = crmSupplyWarehouseSettingService.getSupplyList();
            model.addAttribute("supplyList",supplyList);
//        }else {
//            //供应商和代理商
//            Ascription ascription = CrmUtils.getAscription();
//            List<Record> warehouseList;
//            if (Objects.equals(TraderConstants.TYPE_TWO, user.getTraderType())) {
//                warehouseList = MaterialUtils.findWarehouseBySecondTrader(user.getTraderId());
//            } else {
//                warehouseList = MaterialUtils.findMaterialWarehouseByAscriptionId(ascription.getAscriptionId());
//            }
//            model.addAttribute("ascriptionId", ascription.getAscriptionId());
//            model.addAttribute("wares", warehouseList);
//        }
        return "modules/supply/material/stockList";
    }

    /**inOrOutRecord
     * 平台库存管理列表
     */
    @ResponseBody
    @RequestMapping(value = "ajaxForStockList2")
    public Object ajaxForStockList2(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        LayuiPage<Record> page = new LayuiPage<>(request);
        materialStockService.stockListPage(page, map);
        return page.renderJson();
    }

    /**
     * 代理商库存
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "ajaxForStockList")
    public Object ajaxForStockList(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        LayuiPage<Record> page = new LayuiPage<>(request);
        materialStockService.stockListPageForTrader(page, map);
        return page.renderJson();
    }

    /**
     * 库存管理编辑页面
     */
    @RequestMapping(value = "editMaterialStock")
    public String editMaterialStock(String id, Model model){
        Record stockInfo = materialStockService.findStockInfoById(id);
        model.addAttribute("stockInfo",stockInfo);
        model.addAttribute("id", id);
        return "modules/supply/material/editMaterialStock";
    }

    /**
     * 库存管理编辑页面保存
     */
    @ResponseBody
    @RequestMapping(value = "saveMaterialStockInfo")
    public Result<Void> saveMaterialStockInfo(@Valid MaterialStockSaveReq req){
        materialStockService.saveMaterialStockInfo(req);
        return Result.ok();
    }

    /**
     * 根据仓库和物料查找冻结库存订单
     */
    @RequestMapping("/frozeStockDetail")
    public String frozeStockDetail(String id, Model model){
        MaterialWarehouseStocks stockInfo = materialStockService.getById(id);
        List<Record> recordList = materialStockService.frozeStockDetail(stockInfo.getMaterialId(), stockInfo.getWarehouseId());
        model.addAttribute("recordList", recordList);
        return "modules/supply/material/frozeStockDetail";
    }
    /**
     * 根据物料id和仓库id查询库存信息
     */
    @ResponseBody
    @RequestMapping("/getStockByWarehouse")
    public BigDecimal getStockByWarehouse(String outWarehouseId,String materialId){
        MaterialWarehouseStocks result = materialStockDao.findByWarehouse(materialId, outWarehouseId);
        if (result == null){
            return BigDecimal.ZERO;
        }else {
            return result.getWarning();
        }
    }


    /**
     * 导出excel
     */
    @RequestMapping(value = "exportExcel")
    public void exportExcel(HttpServletRequest request, HttpServletResponse response){
        Map<String, String> map = getParams(request);
        List<Record> records = materialStockService.getStockListForTrader(map);
        List<MaterialStockExcel> list = new ArrayList<>();
        for (Record record : records) {
            MaterialStockExcel excel = new MaterialStockExcel();
            excel.setCode(record.getStr("code"));
            excel.setQqCode(record.getStr("qq_code"));
            excel.setMaterialName(record.getStr("materialName"));
            excel.setMaterialType(record.getStr("typeName"));
            excel.setMaterialSpec(record.getStr("material_specs"));
            excel.setMaterialUnit(record.getStr("unitName"));
            excel.setMaterialBrand(record.getStr("material_brand"));
            excel.setWarehouseName(record.getStr("warehouseName"));
            excel.setYfhTotalCapacity(record.getBigDecimal("yfhTotalCapacity").stripTrailingZeros().toPlainString());
            excel.setYkYfhAmount(record.getBigDecimal("yk_yfh_amount").stripTrailingZeros().toPlainString());
            excel.setTotal1(record.getBigDecimal("yfhTotalCapacity").add(record.getBigDecimal("yk_yfh_amount")).stripTrailingZeros().toPlainString());
            excel.setYazTotalCapacity(record.getBigDecimal("yazTotalCapacity").stripTrailingZeros().toPlainString());
            excel.setYkYazAmount(record.getBigDecimal("yk_yaz_amount").stripTrailingZeros().toPlainString());
            excel.setTotal2(record.getBigDecimal("yazTotalCapacity").add(record.getBigDecimal("yk_yaz_amount")).stripTrailingZeros().toPlainString());
            excel.setYfdTotalCapacity(record.getBigDecimal("yfdTotalCapacity").stripTrailingZeros().toPlainString());
            excel.setYkYfdAmount(record.getBigDecimal("yk_yfd_amount").stripTrailingZeros().toPlainString());
            excel.setTotal3(record.getBigDecimal("yfdTotalCapacity").add(record.getBigDecimal("yk_yfd_amount")).stripTrailingZeros().toPlainString());
            excel.setYtfTotalCapacity(record.getBigDecimal("ytfTotalCapacity").stripTrailingZeros().toPlainString());
            excel.setAzwfdTotalCapacity(record.getBigDecimal("azwfdTotalCapacity").stripTrailingZeros().toPlainString());
            excel.setAzwtfTotalCapacity(record.getBigDecimal("azwtfTotalCapacity").stripTrailingZeros().toPlainString());
            excel.setYkThAmount(record.getBigDecimal("yk_th_amount").stripTrailingZeros().toPlainString());
            excel.setYkMdAmount(record.getBigDecimal("yk_md_amount").stripTrailingZeros().toPlainString());
            excel.setWarning(record.getBigDecimal("warning").stripTrailingZeros().toPlainString());
            BigDecimal price1 = record.getBigDecimal("price1");
            BigDecimal price2 = record.getBigDecimal("price2");
            BigDecimal price3 = record.getBigDecimal("price3");
            BigDecimal price4 = record.getBigDecimal("price4");
            BigDecimal totalPrice = price1.add(price2).add(price3).add(price4);
            excel.setTotalPrice(totalPrice.stripTrailingZeros().toPlainString());
            excel.setWaitDeliverNum(record.getBigDecimal("waitDeliverNum").stripTrailingZeros().toPlainString());
            excel.setWaitSignCount(record.getBigDecimal("waitSignCount").stripTrailingZeros().toPlainString());
            excel.setNumOne(record.getBigDecimal("num1").stripTrailingZeros().toPlainString());
            excel.setPriceOne(price1.stripTrailingZeros().toPlainString());
            excel.setNumTwo(record.getBigDecimal("num2").stripTrailingZeros().toPlainString());
            excel.setPriceTwo(price2.stripTrailingZeros().toPlainString());
            excel.setNumThree(record.getBigDecimal("num3").stripTrailingZeros().toPlainString());
            excel.setPriceThree(price3.stripTrailingZeros().toPlainString());
            excel.setNumFour(record.getBigDecimal("num4").stripTrailingZeros().toPlainString());
            excel.setPriceFour(price4.stripTrailingZeros().toPlainString());
            list.add(excel);
        }
        FileExportUtil.exportMaterialStockExcel(list, response, DateUtils.getDate("yyyy-MM-dd"));
    }
    @ResponseBody
    @RequestMapping(value = "editAmount")
    public Result editAmount(HttpServletRequest request){
        String id=request.getParameter("id");
        String type=request.getParameter("type");
        String amount = request.getParameter("amount");
        materialStockDao.editAmount(id, type, amount);
        return  Result.ok();
    }
    /**
     * 新增代理商库存页面
     */
    @RequestMapping("/addStockPage")
    public String addStockPage(Model model) {
        User user = UserUtils.getUser();
        //代理商列表
        List<Record> traderList = traderService.getTopTrader();
        model.addAttribute("traderList", traderList);
        return "modules/supply/material/addStockPage";
    }
    /**
     * 根据代理商id获取仓库
     */
    @ResponseBody
    @RequestMapping(value = "getWarehouseByTraderId")
    public Object getCitysByProId(HttpServletRequest request) {
        String traderId = request.getParameter("traderId");
        List<Record> list = MaterialUtils.findMaterialWarehouseByAscriptionId(traderId);
        return list;
    }
    //选择物料页面
    @RequestMapping("/selectMaterialCodePage")
    public String selectMaterialCodePage(Model model) {
        return "modules/supply/material/selectMaterialCodePage";
    }
    /**
     * 获取物料编码
     */
    @ResponseBody
    @RequestMapping("getMaterialCodeList")
    public Object getChangeBarCodeList(String materialCode){
        if (StringUtil.isBlank(materialCode)) {
            return Result.fail("编码不能为空");
        }
        List list = supplyMaterialDao.getMaterialCodeList(materialCode);
        return JsonKit.toJson(list);
    }
    /**
     * 根据物料编码获取物料信息
     */
    @ResponseBody
    @RequestMapping("selectNumber")
    public Result selectNumber(String materialCode) {
        if (StringUtil.isBlank(materialCode)) {
            return Result.fail("编码不能为空");
        }
        String[] codeList = materialCode.split(",");
        List<Record> list = new ArrayList<>();
        for (String code : codeList) {
            Record record = supplyMaterialDao.findMaterialByCode(code);
            list.add(record);
        }
//        Map<String,Object> resultMap=new HashMap<>();
//        resultMap.put("material",list);
        return Result.success(list);
    }
    @ResponseBody
    @RequestMapping("addStock")
    public Result addStock(@Validated @RequestBody AddStockVo req) {
        try {
            User user = UserUtils.getUser();
            Operator operator = Operator.of(user);
            return materialStockService.addStock(req,operator);
        } catch (IllegalArgumentException ex) {
            return Result.fail(ex.getMessage());
        } catch (Exception ex) {
           ex.printStackTrace();
           return Result.fail("系统内部错误，操作失败！");
        }
    }
}
