package com.ruoyi.web.base.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.base.domain.ProcureQuotation;
import com.ruoyi.web.base.domain.ProcureQuotationGoods;
import com.ruoyi.web.base.service.IProcureQuotationGoodsService;
import com.ruoyi.web.base.service.IProcureQuotationService;
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.Map;

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

/**
 * ERP H5 端采购报价单接口；复用 {@link ProcureQuotationController} 的 buildWrapper、attachGoods、persistGoods。
 */
@RestController
@Api(tags = "H5采购报价单")
@RequestMapping("/h5/procure-quotation")
public class H5ProcureQuotationController {

    @Autowired
    private ProcureQuotationController procureQuotationController;
    @Autowired
    private IProcureQuotationService procureQuotationService;
    @Autowired
    private IProcureQuotationGoodsService goodsService;
    @Autowired
    private TokenService tokenService;

    @ApiOperation("H5采购报价单分页")
    @GetMapping("/page")
    public AjaxResult page(@RequestParam("pageNum") Integer pageNum,
                           @RequestParam("pageSize") Integer pageSize,
                           ProcureQuotation query,
                           HttpServletRequest request) {
        String orgId = tokenService.getLoginOrgId(request);
        String username = getUsername();
        if (query == null) {
            query = new ProcureQuotation();
        }
        QueryWrapper<ProcureQuotation> wrapper = new QueryWrapper<ProcureQuotation>().eq("org_id", orgId);
        wrapper.eq("source", 2).eq("create_by", username);
        Page<ProcureQuotation> pageObj = procureQuotationService.page(new Page<>(pageNum, pageSize), wrapper);
        for (ProcureQuotation row : pageObj.getRecords()) {
            procureQuotationController.attachGoods(row);
        }
        return success(pageObj);
    }

    @ApiOperation("H5采购报价单新增")
    @PostMapping("/add")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult add(@RequestBody ProcureQuotation procureQuotation, HttpServletRequest request) throws Exception {
        String loginOrgId = tokenService.getLoginOrgId(request);
        if (procureQuotationService.count(new QueryWrapper<ProcureQuotation>().eq("org_id", loginOrgId).eq("quotation_num", procureQuotation.getQuotationNum())) > 0) {
            throw new Exception("该编号已存在");
        }
        String username = getUsername();
        Date now = new Date();
        procureQuotation.setOrgId(loginOrgId);
        procureQuotation.setSource(2);
        procureQuotation.setAuditStatus(0);
        procureQuotation.setCreateBy(username);
        procureQuotation.setCreateTime(now);
        procureQuotation.setUpdateBy(null);
        procureQuotation.setUpdateTime(null);
        procureQuotationController.persistGoods(procureQuotation, loginOrgId, username, false);
        return success(procureQuotationService.save(procureQuotation));
    }

    @ApiOperation("H5采购报价单修改")
    @PostMapping("/edit")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult edit(@RequestBody ProcureQuotation procureQuotation, HttpServletRequest request) throws Exception {
        if (procureQuotation.getId() == null) {
            throw new Exception("id不能为空");
        }
        ProcureQuotation old = procureQuotationService.getById(procureQuotation.getId());
        if (old == null || !tokenService.getLoginOrgId(request).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("只能修改本人创建的报价单");
        }
        String loginOrgId = tokenService.getLoginOrgId(request);
        if (procureQuotationService.count(new QueryWrapper<ProcureQuotation>().ne("id", procureQuotation.getId()).eq("org_id", loginOrgId).eq("quotation_num", procureQuotation.getQuotationNum())) > 0) {
            throw new Exception("该编号已存在");
        }
        Date now = new Date();
        String me = getUsername();
        procureQuotation.setOrgId(loginOrgId);
        procureQuotation.setSource(2);
        procureQuotation.setAuditStatus(0);
        procureQuotation.setCreateBy(me);
        procureQuotation.setCreateTime(now);
        procureQuotation.setUpdateBy(me);
        procureQuotation.setUpdateTime(now);
        procureQuotationController.persistGoods(procureQuotation, loginOrgId, me, true);
        return success(procureQuotationService.updateById(procureQuotation));
    }

    @ApiOperation("H5采购报价单删除")
    @PostMapping("/delete")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult delete(@RequestBody Map<String, String> paramsMap) throws Exception {
        String ids = paramsMap.get("ids");
        if (StringUtils.isBlank(ids)) {
            throw new Exception("ids不能为空");
        }
        String me = getUsername();
        for (String s : ids.split(",")) {
            if (StringUtils.isBlank(s)) {
                continue;
            }
            ProcureQuotation q = procureQuotationService.getById(s.trim());
            if (q == null) {
                continue;
            }
            int src = q.getSource() == null ? 1 : q.getSource();
            if (src != 2) {
                throw new Exception("非H5来源采购报价单不能在此删除");
            }
            if (!StringUtils.equals(me, q.getCreateBy())) {
                throw new Exception("只能删除本人创建的报价单");
            }
            if (q.getAuditStatus() != null && q.getAuditStatus() == 1) {
                throw new Exception("已审核的报价单不能删除");
            }
            goodsService.remove(new QueryWrapper<ProcureQuotationGoods>().eq("quotation_num", q.getQuotationNum()));
            procureQuotationService.removeById(s.trim());
        }
        return success();
    }

    @ApiOperation("H5采购报价单详情")
    @PostMapping("/listById")
    public AjaxResult listById(@ApiParam("详情参数: id") @RequestBody Map<String, String> paramsMap, HttpServletRequest request) throws Exception {
        String id = paramsMap.get("id");
        ProcureQuotation byId = procureQuotationService.getById(id);
        if (byId == null) {
            return success(null);
        }
        String orgId = tokenService.getLoginOrgId(request);
        if (!orgId.equals(byId.getOrgId())) {
            throw new Exception("报价单不存在");
        }
        int src = byId.getSource() == null ? 1 : byId.getSource();
        if (src != 2) {
            throw new Exception("非H5来源采购报价单不能在此查看");
        }
        if (!StringUtils.equals(getUsername(), byId.getCreateBy())) {
            throw new Exception("只能查看本人创建的报价单");
        }
        procureQuotationController.attachGoods(byId);
        return success(byId);
    }
}
