package com.ruoyi.web.base.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
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.IProcureQuotationService;
import com.ruoyi.web.base.service.IProcureQuotationGoodsService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

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;
import static com.ruoyi.web.base.util.NumUtils.generateString;
import static com.ruoyi.web.base.util.NumUtils.substringToInt;

/**
 * 供应商报价单（采购报价单）前端控制器
 */
@RestController
@RequestMapping("/procure-quotation")
public class ProcureQuotationController {
    @Autowired
    private IProcureQuotationService procureQuotationService;
    @Autowired
    private IProcureQuotationGoodsService goodsService;
    @Autowired
    private TokenService tokenService;

    @ApiOperation("供应商报价单添加")
    @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.setCreateBy(username);
        procureQuotation.setCreateTime(now);
        procureQuotation.setSource(1);
        procureQuotation.setAuditStatus(1);
        persistGoods(procureQuotation, loginOrgId, username, false);
        return success(procureQuotationService.save(procureQuotation));
    }

    @ApiOperation("供应商报价单修改")
    @PostMapping("/edit")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult edit(@RequestBody ProcureQuotation procureQuotation, HttpServletRequest request) throws Exception {
        if (procureQuotation.getId() == null) {
            throw new Exception("id不能为空");
        }
        String loginOrgId = tokenService.getLoginOrgId(request);
        ProcureQuotation old = procureQuotationService.getById(procureQuotation.getId());
        if (old == null || !loginOrgId.equals(old.getOrgId())) {
            throw new Exception("报价单不存在");
        }
        if (procureQuotationService.count(new QueryWrapper<ProcureQuotation>().ne("id", procureQuotation.getId()).eq("org_id", loginOrgId).eq("quotation_num", procureQuotation.getQuotationNum())) > 0) {
            throw new Exception("该编号已存在");
        }

        String username = getUsername();
        procureQuotation.setOrgId(loginOrgId);
        int oldSrc = old.getSource() == null ? 1 : old.getSource();
        boolean h5Pending = oldSrc == 2 && (old.getAuditStatus() == null || old.getAuditStatus() == 0);
        if (h5Pending) {
            procureQuotation.setAuditStatus(0);
            procureQuotation.setSource(2);
            procureQuotation.setCreateBy(old.getCreateBy());
            procureQuotation.setCreateTime(old.getCreateTime());
        } else {
            if (old.getAuditStatus() != null && old.getAuditStatus() == 1) {
                throw new Exception("已审核的报价单不能修改，请先反审核");
            }
            procureQuotation.setAuditStatus(1);
            if (procureQuotation.getSource() == null) {
                procureQuotation.setSource(old.getSource() != null ? old.getSource() : 1);
            }
            procureQuotation.setCreateBy(old.getCreateBy());
            procureQuotation.setCreateTime(old.getCreateTime());
        }
        procureQuotation.setUpdateBy(username);
        procureQuotation.setUpdateTime(new Date());
        persistGoods(procureQuotation, loginOrgId, username, true);
        return success(procureQuotationService.updateById(procureQuotation));
    }

    @ApiOperation("供应商报价单审核")
    @PostMapping("/audit")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult audit(@RequestBody Map<String, String> params) throws Exception {
        String id = params.get("id");
        if (StringUtils.isBlank(id)) {
            throw new Exception("id不能为空");
        }
        ProcureQuotation q = procureQuotationService.getById(id);
        if (q == null) {
            throw new Exception("报价单不存在");
        }
        int src = q.getSource() == null ? 1 : q.getSource();
        if (src == 2 && q.getAuditStatus() != null && q.getAuditStatus() != 0) {
            throw new Exception("仅待审核的H5采购报价单可审核");
        }
        if (src != 2) {
            throw new Exception("仅H5来源采购报价单需在此审核");
        }
        q.setAuditStatus(1);
        q.setUpdateBy(getUsername());
        q.setUpdateTime(new Date());
        return success(procureQuotationService.updateById(q));
    }

    @ApiOperation("供应商报价单删除")
    @PostMapping("/delete")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult delete(@RequestBody Map<String, String> paramsMap) {
        String ids = paramsMap.get("ids");
        for (String s : ids.split(",")) {
            if (StringUtils.isBlank(s)) {
                continue;
            }
            ProcureQuotation q = procureQuotationService.getById(s.trim());
            if (q == null) {
                continue;
            }
            goodsService.remove(new QueryWrapper<ProcureQuotationGoods>().eq("quotation_num", q.getQuotationNum()));
            procureQuotationService.removeById(s.trim());
        }
        return success();
    }

    @ApiOperation("供应商报价单列表")
    @PostMapping("/list")
    public AjaxResult listAll(HttpServletRequest request) {
        String orgId = tokenService.getLoginOrgId(request);
        List<ProcureQuotation> org_id = procureQuotationService.list(new QueryWrapper<ProcureQuotation>().eq("org_id", orgId));
        for (ProcureQuotation procureQuotation : org_id) {
            attachGoods(procureQuotation);
        }
        return success(org_id);
    }

    @ApiOperation("供应商报价单分页")
    @GetMapping("/page")
    public AjaxResult page(@RequestParam("pageNum") Integer pageNum,
                           @RequestParam("pageSize") Integer pageSize,
                           ProcureQuotation query,
                           HttpServletRequest request) {
        String orgId = tokenService.getLoginOrgId(request);
        if (query == null) {
            query = new ProcureQuotation();
        }
        Page<ProcureQuotation> org_id = procureQuotationService.page(new Page<>(pageNum, pageSize), buildWrapper(query, orgId));
        for (ProcureQuotation procureQuotation : org_id.getRecords()) {
            attachGoods(procureQuotation);
        }
        return success(org_id);
    }

    @ApiOperation("供应商报价单详情")
    @PostMapping("/listById")
    public AjaxResult listById(@RequestBody Map<String, String> paramsMap) {
        String id = paramsMap.get("id");
        ProcureQuotation byId = procureQuotationService.getById(id);
        if (byId == null) {
            return success(null);
        }
        attachGoods(byId);
        return success(byId);
    }

    @ApiOperation("获取最新报价单编号")
    @PostMapping("/getQuotaNum")
    public AjaxResult getQuotaNum(HttpServletRequest request) throws Exception {
        String loginOrgId = tokenService.getLoginOrgId(request);

        ProcureQuotation one = procureQuotationService.getOne(new QueryWrapper<ProcureQuotation>().eq("org_id", loginOrgId).orderByDesc("id").last("limit 1"));
        if (ObjectUtils.isEmpty(one)) {

            return success(generateString("bj", 1));
        }
        String quotationNum = one.getQuotationNum();

        return success(generateString("bj", substringToInt(quotationNum)));

    }

    QueryWrapper<ProcureQuotation> buildWrapper(ProcureQuotation query, String orgId) {
        QueryWrapper<ProcureQuotation> w = new QueryWrapper<ProcureQuotation>().eq("org_id", orgId);
        if (query == null) {
            w.eq("audit_status", 1);
            w.orderByDesc("id");
            return w;
        }
        if (query.getAuditStatus() != null) {
            w.eq("audit_status", query.getAuditStatus());
        } else {
            w.eq("audit_status", 1);
        }
        if (query.getSource() != null && (query.getSource() == 1 || query.getSource() == 2)) {
            w.eq("source", query.getSource());
        }
        w.orderByDesc("id");
        return w;
    }

    void attachGoods(ProcureQuotation row) {
        if (row == null || StringUtils.isBlank(row.getQuotationNum())) {
            return;
        }
        row.setGoods(goodsService.list(new QueryWrapper<ProcureQuotationGoods>().eq("quotation_num", row.getQuotationNum())));
    }

    /**
     * @param removeExisting true：先按 quotation_num 删除旧明细再插入（修改）；false：仅追加（新增）
     */
    void persistGoods(ProcureQuotation procureQuotation, String loginOrgId, String username, boolean removeExisting) throws Exception {
        List<ProcureQuotationGoods> goods = procureQuotation.getGoods();
        if (goods == null || goods.isEmpty()) {
            throw new Exception("货品明细不能为空");
        }
        if (removeExisting) {
            goodsService.remove(new QueryWrapper<ProcureQuotationGoods>().eq("quotation_num", procureQuotation.getQuotationNum()));
        }
        Date now = new Date();
        for (ProcureQuotationGoods good : goods) {
            good.setId(null);
            good.setOrgId(loginOrgId);
            good.setCreateBy(username);
            good.setCreateTime(now);
            good.setQuotationNum(procureQuotation.getQuotationNum());
            goodsService.save(good);
        }
    }
}
