package com.ruoyi.web.sales.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.web.sales.domain.SalesOrder;
import com.ruoyi.web.sales.domain.SalesOrderGoods;
import com.ruoyi.web.sales.service.ISalesOrderGoodsService;
import com.ruoyi.web.sales.service.ISalesOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.ruoyi.common.core.domain.AjaxResult.success;
import static com.ruoyi.common.utils.SecurityUtils.getUsername;

/**
 * ERP H5 端销售订单接口；校验与明细持久化复用 {@link SalesOrderController} 包内方法。
 */
@RestController
@Api(tags = "H5销售订单")
@RequestMapping("/h5/sales-order")
public class H5SalesOrderController {

    @Autowired
    private SalesOrderController salesOrderController;
    @Autowired
    private ISalesOrderService salesOrderService;
    @Autowired
    private ISalesOrderGoodsService salesOrderGoodsService;
    @Autowired
    private TokenService tokenService;

    @ApiOperation("H5销售订单分页")
    @GetMapping("/page")
    public AjaxResult page(@RequestParam("pageNum") Integer pageNum,
                           @RequestParam("pageSize") Integer pageSize,
                           SalesOrder query,
                           HttpServletRequest request) {
        String orgId = tokenService.getLoginOrgId(request);
        String username = getUsername();
        if (query == null) {
            query = new SalesOrder();
        }
        QueryWrapper<SalesOrder> wrapper = new QueryWrapper<SalesOrder>()
                .eq("org_id", orgId)
                .eq("del_flag", "0");
        wrapper.eq("source", 2).eq("create_by", username);
        Page<SalesOrder> pageObj = salesOrderService.page(new Page<>(pageNum, pageSize), wrapper);
        for (SalesOrder row : pageObj.getRecords()) {
            salesOrderController.enrichSalesOrderDisplay(row, orgId);
        }
        return success(pageObj);
    }

    @ApiOperation("H5销售订单新增")
    @PostMapping("/add")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult add(@RequestBody SalesOrder order, HttpServletRequest request) throws Exception {
        String orgId = tokenService.getLoginOrgId(request);
        String username = getUsername();
        if (StringUtils.isBlank(order.getOrderNum())) {
            order.setOrderNum(salesOrderController.generateSalesOrderNum(orgId));
        }
        salesOrderController.validateBeforeSave(order, orgId, true);
        salesOrderController.fillCustomerAndMarketInfo(order, orgId);
        salesOrderController.recalcGoodsSubTotalsAndOrderTotal(order);
        order.setOrgId(orgId);
        order.setDelFlag("0");
        order.setAuditStatus(0);
        order.setSource(2);
        order.setId(null);
        order.setCreateBy(username);
        order.setCreateTime(new Date());
        order.setUpdateBy(null);
        order.setUpdateTime(null);
        salesOrderService.save(order);
        salesOrderController.saveGoods(order, orgId, username);
        return success();
    }

    @ApiOperation("H5销售订单修改")
    @PostMapping("/edit")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult edit(@RequestBody SalesOrder order, HttpServletRequest request) throws Exception {
        if (order.getId() == null) {
            throw new Exception("id不能为空");
        }
        SalesOrder old = salesOrderService.getById(order.getId());
        if (old == null || !"0".equals(old.getDelFlag())) {
            throw new Exception("销售订单不存在");
        }
        String orgId = tokenService.getLoginOrgId(request);
        if (!orgId.equals(old.getOrgId())) {
            throw new Exception("销售订单不存在");
        }
        int oldSrc = old.getSource() == null ? 1 : old.getSource();
        if (oldSrc != 2) {
            throw new Exception("非H5来源销售订单不能在此修改");
        }
        if (old.getAuditStatus() != null && old.getAuditStatus() == 1) {
            throw new Exception("已审核的销售订单不能修改");
        }
        if (!StringUtils.equals(getUsername(), old.getCreateBy())) {
            throw new Exception("只能修改本人创建的订单");
        }
        salesOrderController.validateBeforeSave(order, orgId, false);
        salesOrderController.fillCustomerAndMarketInfo(order, orgId);
        salesOrderController.recalcGoodsSubTotalsAndOrderTotal(order);
        order.setOrgId(orgId);
        order.setAuditStatus(0);
        order.setSource(2);
        Date now = new Date();
        order.setCreateBy(getUsername());
        order.setCreateTime(now);
        order.setUpdateBy(getUsername());
        order.setUpdateTime(now);
        salesOrderService.updateById(order);
        String oldOrderNum = StringUtils.isNotBlank(old.getOrderNum()) ? old.getOrderNum().trim() : null;
        salesOrderController.deleteSalesOrderGoodsByOrderNum(orgId, oldOrderNum);
        salesOrderController.saveGoods(order, orgId, getUsername());
        return success();
    }

    @ApiOperation("H5销售订单删除")
    @PostMapping("/delete")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult delete(@RequestBody Map<String, String> params) throws Exception {
        String ids = params.get("ids");
        if (StringUtils.isBlank(ids)) {
            throw new Exception("ids不能为空");
        }
        String me = getUsername();
        for (String id : ids.split(",")) {
            if (StringUtils.isBlank(id)) {
                continue;
            }
            SalesOrder order = salesOrderService.getById(id.trim());
            if (order == null || !"0".equals(order.getDelFlag())) {
                continue;
            }
            int src = order.getSource() == null ? 1 : order.getSource();
            if (src != 2) {
                throw new Exception("非H5来源销售订单不能在此删除");
            }
            if (!StringUtils.equals(me, order.getCreateBy())) {
                throw new Exception("只能删除本人创建的订单");
            }
            if (order.getAuditStatus() != null && order.getAuditStatus() == 1) {
                throw new Exception("已审核的销售订单不能删除");
            }
            String orgId = order.getOrgId();
            String orderNum = order.getOrderNum();
            salesOrderController.deleteSalesOrderGoodsByOrderNum(orgId, orderNum);
            SalesOrder up = new SalesOrder();
            up.setId(order.getId());
            up.setDelFlag("2");
            up.setUpdateBy(me);
            up.setUpdateTime(new Date());
            salesOrderService.updateById(up);
        }
        return success();
    }

    @ApiOperation("H5销售订单详情")
    @PostMapping("/listById")
    public AjaxResult listById(@ApiParam("详情参数: id") @RequestBody Map<String, String> params, HttpServletRequest request) throws Exception {
        String id = params.get("id");
        SalesOrder order = salesOrderService.getById(id);
        if (order == null || !"0".equals(order.getDelFlag())) {
            return success(null);
        }
        String orgId = tokenService.getLoginOrgId(request);
        if (!orgId.equals(order.getOrgId())) {
            throw new Exception("销售订单不存在");
        }
        int src = order.getSource() == null ? 1 : order.getSource();
        if (src != 2) {
            throw new Exception("非H5来源销售订单不能在此查看");
        }
        if (!StringUtils.equals(getUsername(), order.getCreateBy())) {
            throw new Exception("只能查看本人创建的订单");
        }
        List<SalesOrderGoods> goods = salesOrderGoodsService.list(new QueryWrapper<SalesOrderGoods>()
                .eq("org_id", orgId)
                .eq("order_num", order.getOrderNum())
                .eq("del_flag", "0"));
        salesOrderController.enrichGoodsFromMaterial(goods, orgId);
        order.setGoods(goods);
        salesOrderController.enrichSalesOrderDisplay(order, orgId);
        return success(order);
    }
}
