package com.ruoyi.web.controller.api;

import com.alibaba.fastjson.JSON;
import com.google.gson.JsonObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.ApiResult;
import com.ruoyi.common.utils.JPushUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.mall.domain.*;
import com.ruoyi.mall.service.IDemandReportService;
import com.ruoyi.mall.service.IMallExpeditingGoodsService;
import com.ruoyi.mall.service.IMallGoodsGoodsService;
import com.ruoyi.mall.service.IMallMemberUserService;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 【请填写功能名称】Controller
 *
 * @author ruoyi
 * @date 2025-01-14
 */
@RestController
@RequestMapping("/api/mall/report")
public class DemandReportController extends BaseController {
    @Autowired
    private IMallGoodsGoodsService mallGoodsGoodsService;
    @Autowired
    private IDemandReportService demandReportService;
    @Resource
    private IMallMemberUserService memberUserService;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private JPushUtils jPushUtils;
    @Autowired
    private IMallExpeditingGoodsService mallExpeditingGoodsService;
    /**
     * 查询【请填写功能名称】列表
     */
    @GetMapping("/list")
    public TableDataInfo list(DemandReport demandReport) {
        startPage();
        List<DemandReport> list = demandReportService.selectDemandReportList(demandReport);
        return getDataTable(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DemandReport demandReport) throws IOException {
        List<DemandReport> list = demandReportService.selectDemandReportList(demandReport);
        ExcelUtil<DemandReport> util = new ExcelUtil<DemandReport>(DemandReport.class);
        util.exportExcel(response, list, "【请填写功能名称】数据");
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
    @GetMapping(value = "/{id}")
    public DemandReport getInfo(@PathVariable("id") Long id) {
        return demandReportService.selectDemandReportById(id);
    }

    /**
     * 新增【请填写功能名称】
     */
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping
    public ApiResult add(@RequestBody DemandReportDto demandReport) {
        if(demandReport.getDemand().isEmpty()){
            return ApiResult.error("需填写需求量");
        }
        if(demandReport.getProductTitle().isEmpty()){
            return ApiResult.error("需填写商品名称");
        }

        return ApiResult.ok().put("data",demandReportService.insertDemandReport(demandReport));
    }

    /**
     * 修改【请填写功能名称】
     */
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DemandReport demandReport) {
        return toAjax(demandReportService.updateDemandReport(demandReport));
    }

    /**
     * 删除【请填写功能名称】
     */
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(demandReportService.deleteDemandReportByIds(ids));
    }

    @ResponseBody
    @RequestMapping("/expeditinggoods")
    public Object expeditinggoods(@RequestBody Map<String, Long> params) {
        //创建order Model
        MallOrderOrder orderOrder = new MallOrderOrder();
        MallMemberUser memberUser = memberUserService.selectMallMemberUserById(Long.valueOf(params.get("userId").toString()));
        Long goodsid = params.get("goodsId");
        MallGoodsGoods mallGoodsGoods = mallGoodsGoodsService.selectMallGoodsGoodsById(goodsid);
        orderOrder.setSalesmanId(memberUser.getSalesmanId());
        Map<String, String> orderInfoParams = new HashMap<>();
        orderInfoParams.put("goodsName", mallGoodsGoods.getGoodsName().toString());
        orderInfoParams.put("goodsBrand", mallGoodsGoods.getGoodsBrand().toString());
        String orderInfo = JSON.toJSONString(orderInfoParams);
        // 极光推送
        // roleId：1-超级管理员，12-仓库管理员，13-财务，10-分公司管理员，11-业务员
        Map<String, Object> newParams = new HashMap<>();
        newParams.put("roleId", 1);
        String[] userName = sysUserMapper.selectUserNameByParams(newParams);
        MallExpeditingGoods mallExpeditingGoods = new MallExpeditingGoods();
        mallExpeditingGoods.setGoodName(mallGoodsGoods.getGoodsName().toString());
        mallExpeditingGoods.setUserId((params.get("userId").toString()));
        mallExpeditingGoods.setUserName(memberUser.getName());
        mallExpeditingGoods.setUserPhone(memberUser.getPhone());
        mallExpeditingGoods.setGoodPrice(mallGoodsGoods.getGoodsBrand().toString());
        if (orderOrder.getSalesmanId() != null) {
            // roleId：1-超级管理员，12-仓库管理员，13-财务，10-分公司管理员，11-业务员
            Map<String, Object> salesmanParams = new HashMap<>();// 新增催货通知-业务员查看推送
            salesmanParams.put("roleId", 11);
            salesmanParams.put("salesmanId", orderOrder.getSalesmanId());
            String[] salesmanName = sysUserMapper.selectUserNameByParams(salesmanParams);
            if (salesmanName.length > 0) {
                System.out.println("新增催货通知-业务员查看推送");
                try {
                    String url = "intent:#Intent;action=cn.jiguang.myaction;component=com.qdw.qianlengnet/com.qdw.qianlengnet.activity.OrderDetailsActivity;";
                    JsonObject jsonObject = new JsonObject();
                    jsonObject.addProperty("url", url);
                    jPushUtils.jPush(salesmanName, orderOrder.getReceiverName() + orderOrder.getReceiverPhone() + "催货，请及时查看", "线上订单-业务员查看", orderInfo, orderInfoParams, jsonObject);
                } catch (Exception e) {
                    System.out.println("新增催货通知-业务员查看推送异常");
                }
            }
        }
        return ApiResult.ok("催货成功");
    }
}
