package com.fs.live.controller;

import cn.hutool.core.util.StrUtil;
import com.fs.common.annotation.Log;
import com.fs.common.config.LoginContextManager;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.ParseUtils;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.company.param.CompanyStoreOrderMoneyLogsListParam;
import com.fs.company.service.ICompanyMoneyLogsService;
import com.fs.company.vo.CompanyStoreOrderMoneyLogsVO;
import com.fs.core.security.LoginUser;
import com.fs.core.web.service.TokenService;
import com.fs.crm.domain.CrmCustomer;
import com.fs.crm.service.ICrmCustomerService;
import com.fs.erp.domain.ErpDeliverys;
import com.fs.erp.domain.ErpOrderQuery;
import com.fs.erp.dto.ErpOrderQueryRequert;
import com.fs.erp.dto.ErpOrderQueryResponse;
import com.fs.erp.service.IErpOrderService;
import com.fs.erp.utils.ErpContextHolder;
import com.fs.express.FsStoreDeliversService;
import com.fs.live.domain.LiveOrder;
import com.fs.live.domain.LiveOrderItem;
import com.fs.live.domain.LiveOrderLogs;
import com.fs.live.domain.LiveOrderPayment;
import com.fs.live.enums.LiveOrderCancleReason;
import com.fs.live.service.ILiveOrderItemService;
import com.fs.live.service.ILiveOrderLogsService;
import com.fs.live.service.ILiveOrderPaymentService;
import com.fs.live.service.ILiveOrderService;
import com.fs.live.vo.LiveGoodsVo;
import com.fs.live.vo.LiveOrderPaymentVo;
import com.fs.live.vo.LiveOrderQueryVO;
import com.fs.live.vo.LiveOrderVo;
import com.fs.store.domain.FsStoreDelivers;
import com.fs.store.domain.FsStoreOrder;
import com.fs.store.domain.FsStoreOrderStatus;
import com.fs.store.domain.FsUser;
import com.fs.store.mapper.FsStoreDeliversMapper;
import com.fs.store.mapper.FsStoreProductMapper;
import com.fs.store.mapper.FsWarehousesMapper;
import com.fs.store.param.*;
import com.fs.store.service.IFsExpressService;
import com.fs.store.service.IFsUserService;
import com.fs.task.LiveTask;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.http.util.Asserts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

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


/**`
 * 订单Controller
 *
 * @author fs
 * @date 2025-07-08
 */
@RestController
@RequestMapping("/live/liveOrder")
public class LiveOrderController extends BaseController
{
    @Autowired
    private ILiveOrderService liveOrderService;
    @Autowired
    private ICrmCustomerService crmCustomerService;
    @Autowired
    private IFsUserService userService;
    @Autowired
    private ILiveOrderItemService orderItemService;
    @Autowired
    private ILiveOrderLogsService orderLogsService;
    @Autowired
    private ILiveOrderPaymentService orderPaymentService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IFsExpressService expressService;
    @Autowired
    private FsWarehousesMapper fsWarehousesMapper;
    @Autowired
    IErpOrderService erpOrderService;
    @Autowired
    private LiveTask liveTask;

    /**
     * 查询订单列表
     */
    @PreAuthorize("@ss.hasPermi('live:liveOrder:list')")
    @GetMapping("/list")
    public TableDataInfo list(LiveOrderQueryVO liveOrder)
    {
        startPage();
        List<LiveOrder> list = liveOrderService.selectLiveOrderList(liveOrder);
        for (LiveOrder vo : list){
            vo.setUserPhone(ParseUtils.parsePhone(vo.getUserPhone()));
            vo.setUserAddress(ParseUtils.parseAddress(vo.getUserAddress()));
        }
        return getDataTable(list);
    }



    /**
     * 导出订单列表
     */
    @PreAuthorize("@ss.hasPermi('live:liveOrder:export')")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(LiveOrderQueryVO liveOrder)
    {
        List<LiveOrder> list = liveOrderService.selectLiveOrderListExport(liveOrder);

        for (LiveOrder order : list) {
            if(StringUtils.isNotNull(order.getUserPhone())){
                order.setUserPhone(ParseUtils.parsePhone(order.getUserPhone()));
            }
            if(StringUtils.isNotNull(order.getUserAddress())){
                order.setUserAddress(ParseUtils.parseAddress(order.getUserAddress()));
            }
        }
        ExcelUtil<LiveOrder> util = new ExcelUtil<LiveOrder>(LiveOrder.class);
        return util.exportExcel(list, "订单数据");
    }

    /**
     * 获取订单详细信息
     */
    @PreAuthorize("@ss.hasPermi('live:liveOrder:query')")
    @GetMapping(value = "/info/{orderId}")
    public AjaxResult getInfo(@PathVariable("orderId") String orderId)
    {
        LiveOrder liveOrder = liveOrderService.selectLiveOrderByOrderId(orderId);
        liveOrder.setUserPhone(ParseUtils.parsePhone(liveOrder.getUserPhone()));
        liveOrder.setUserAddress(ParseUtils.parseAddress(liveOrder.getUserAddress()));
        return AjaxResult.success(liveOrder);
    }


    /**
     * 新增订单
     */
    @PreAuthorize("@ss.hasPermi('live:liveOrder:add')")
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping("/create")
    public R add(@RequestBody LiveOrder liveOrder)
    {
        return R.ok().put("data", liveOrderService.insertLiveOrder(liveOrder));
    }

    /**
     * 修改订单
     */
    @PreAuthorize("@ss.hasPermi('live:liveOrder:edit')")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping("/update")
    public AjaxResult edit(@RequestBody LiveOrder liveOrder)
    {
        return toAjax(liveOrderService.updateLiveOrder(liveOrder));
    }

    /**
     * 支付订单
     * */
    @PreAuthorize("@ss.hasPermi('live:liveOrder:pay')")
    @PostMapping(value = "/pay")
    public void pay(LiveOrder liveOrder)
    {
       liveOrderService.handlePay(liveOrder);
    }

    /**
     * 取消订单确认
     * */
    @PreAuthorize("@ss.hasPermi('live:liveOrder:edit')")
    @GetMapping(value = "/cancelConfirm/{orderId}")
    public R cancelConfirm(@PathVariable String orderId)
    {
        LiveOrder byId = liveOrderService.getById(orderId);
        List<Map<String, String>> allCodeDescMap = LiveOrderCancleReason.getAllCodeDescMap();
        return R.ok().put("reason",allCodeDescMap).put("data",byId);
    }

    /**
     * 按照时间粒度返回订单
     * */
    @GetMapping(value = "/getLiveOrderTimeGranularity")
    public R getLiveOrderTimeGranularity(LiveOrderVo liveOrder){
        return liveOrderService.getLiveOrderTimeGranularity(liveOrder);
    }


    @Log(title = "同步物流", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/syncExpress/{id}")
    public R syncExpress(@PathVariable("id") Long id) {
        return liveOrderService.syncExpress(id);
    }


    /**
     * 查询订单商品列表
     */
    @PreAuthorize("@ss.hasPermi('live:liveOrder:query')")
    @GetMapping("/ltemlist/{orderId}")
    public TableDataInfo ltemlist(@PathVariable("orderId") String orderId)
    {
        List<LiveGoodsVo> list = liveOrderService.selectLiveOrderItemList(orderId);
        return getDataTable(list);
    }

    @GetMapping("/test")
    public R test()
    {
        liveTask.updateExpress();
        return R.ok();
    }
    @PreAuthorize("@ss.hasPermi('live:liveOrder:refundOrderMoney')")
    @Log(title = "退款", businessType = BusinessType.UPDATE)
//    @PreAuthorize("@ss.hasPermi('live:liveOrder:refundOrderMoney')")
    @PostMapping("/refundOrderMoney")
    public synchronized R refundOrderMoney(@Validated @RequestBody FsStoreOrderRefundParam param, HttpServletRequest request) {
        return liveOrderService.refundOrderMoney(param.getOrderId());
    }

    /**
     * 获取订单详细信息
     */
    @PreAuthorize("@ss.hasPermi('live:liveOrder:query')")
    @GetMapping(value = "/{id}")
    public R getInfo(@PathVariable("id") Long id)
    {
        LiveOrder order=liveOrderService.selectLiveOrderByOrderId(String.valueOf(id));
        order.setUserPhone(ParseUtils.parsePhone(order.getUserPhone()));
        order.setUserAddress(ParseUtils.parseAddress(order.getUserAddress()));
        FsUser user=userService.selectFsUserById(Long.valueOf(order.getUserId()));
        user.setPhone(ParseUtils.parsePhone(user.getPhone()));
        List<LiveOrderItem> items=orderItemService.selectCheckedByOrderId(id);
        FsStoreOrderStatus statusMap=new FsStoreOrderStatus();

        List<LiveOrderLogs> logs=orderLogsService.selectLiveOrderLogsByOrderId(id);
        List<LiveOrderPayment> payments=orderPaymentService.selectLiveOrderPaymentByOrderId(id);

        CrmCustomer customer=null;
        if(order.getCustomerId()!=null&&order.getCustomerId()>0){
            customer=crmCustomerService.selectCrmCustomerById(order.getCustomerId());
        }
        return R.ok().put("order", order).put("items", items).put("logs",logs).put("user",user).put("customer",customer).put("payments",payments) ;
    }

    @PreAuthorize("@ss.hasPermi('live:liveOrder:query')")
    @GetMapping(value = "/payments/{id}")
    public R getOrderPayments(@PathVariable("id") Long id){
        List<LiveOrderPayment> payments=orderPaymentService.selectLiveOrderPaymentByOrderId(id);
        return R.ok().put("payments",payments);
    }
    @Autowired
    private FsStoreDeliversMapper fsStoreDeliversMapper;
    @GetMapping(value = "/express/{id}")
    public R getExpress(@PathVariable("id") Long id){
        List<FsStoreDelivers> data = fsStoreDeliversMapper.findByOrderIdWithType(id, 1);
        return R.ok().put("data",data);
    }

    @Autowired
    private ICompanyMoneyLogsService moneyLogsService;

    @GetMapping(value = "/tuiMoneyLogs")
    public R tuiMoneyLogs(@RequestParam("orderId") String orderId){
        LiveOrder liveOrder = liveOrderService.selectLiveOrderByOrderId(orderId);
        List<CompanyStoreOrderMoneyLogsVO> tuiMoneyLogs=new ArrayList<>();
        if(liveOrder.getCompanyId()!=null){
            CompanyStoreOrderMoneyLogsListParam moneyLogsMap=new CompanyStoreOrderMoneyLogsListParam();
            moneyLogsMap.setCompanyId(liveOrder.getCompanyId());
            moneyLogsMap.setBusinessId(liveOrder.getOrderId().toString());
            moneyLogsMap.setType(1);
            tuiMoneyLogs=moneyLogsService.selectCompanyStoreOrderMoneyLogsList(moneyLogsMap);
        }
        return R.ok().put("data",tuiMoneyLogs);
    }

    @PreAuthorize("@ss.hasPermi('live:liveOrder:query')")
    @GetMapping(value = "/logs/{id}")
    public R getOrderLogs(@PathVariable("id") Long id){
        List<LiveOrderLogs> logs=orderLogsService.selectLiveOrderLogsByOrderId(id);
        return R.ok().put("logs",logs);
    }

    @GetMapping(value = "/queryAddress/{id}")
    @PreAuthorize("@ss.hasPermi('live:liveOrder:queryAddress')")
    public R getAddress(@PathVariable("id") Long id)
    {
        LiveOrder order = liveOrderService.selectLiveOrderByOrderId(String.valueOf(id));
        String address = order.getUserAddress();
        return R.ok().put("address",address);
    }
    @GetMapping(value = "/queryPhone/{id}")
    @PreAuthorize("@ss.hasPermi('live:liveOrder:queryPhone')")
    @Log(title = "查看电话", businessType = BusinessType.GRANT)
    public R getPhone(@PathVariable("id") Long id)
    {
        LiveOrder order = liveOrderService.selectLiveOrderByOrderId(String.valueOf(id));
        String userPhone = order.getUserPhone();
        return R.ok().put("userPhone",userPhone);
    }

    /**
     * 根据orderId查询
     */
    @PreAuthorize("@ss.hasPermi('live:liveOrder:query')")
    @GetMapping("/getByOrderId/{orderId}")
    public R getByOrderId(@PathVariable Long orderId) {
        LiveOrder liveOrder = liveOrderService.selectLiveOrderByOrderId(String.valueOf(orderId));
        return R.ok().put("data",liveOrder);
    }

    @ApiOperation("物流查询")
    @PostMapping("/getExpressByDeliverId")
    public R getExpressByDeliverId(@Validated @RequestBody FsStoreOrderExpressParam param, HttpServletRequest request){
        return expressService.getLiveExpressByDeliverId(param);
    }

    @PreAuthorize("@ss.hasPermi('live:liveOrder:auditPayRemain')")
    @PostMapping("/auditPayRemain")
    public R auditPayRemain(@Validated @RequestBody FsStoreOrderAuditPayRemainParam param, HttpServletRequest request) {
        return liveOrderService.auditPayRemain(param.getOrderId());
    }

    @Log(title = "分佣", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('live:liveOrder:addTuiMoney')")
    @PostMapping("/addTuiMoney")
    public R addTuiMoney(@Validated @RequestBody FsStoreOrderAddTuiMoneyParam param, HttpServletRequest request) {
        return liveOrderService.addTuiMoney(param);
    }

    @Log(title = "同步物流", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('live:liveOrder:syncExpress')")
    @PostMapping("/syncExpress")
    public R syncExpress(@Validated @RequestBody FsStoreOrderExpressEditParam param, HttpServletRequest request) {
        return liveOrderService.syncExpress(param.getOrderId());
    }

    @PreAuthorize("@ss.hasPermi('live:liveOrder:updateExpress')")
    @PostMapping("/updateExpress")
    public R updateExpress(@Validated @RequestBody FsStoreOrderExpressEditParam param, HttpServletRequest request) {
        return liveOrderService.updateExpress(param.getOrderId());
    }

    @PreAuthorize("@ss.hasPermi('live:liveOrder:getEroOrder')")
    @GetMapping("/getEroOrder")
    public R getEroOrder(@RequestParam("extendOrderId") String extendOrderId) {
        ErpOrderQueryRequert request = new ErpOrderQueryRequert();
        request.setCode(extendOrderId);
        if(StringUtils.isEmpty(extendOrderId)) return R.error("物流订单ID为空！");

        LiveOrder order = liveOrderService.selectLiveOrderByExtendId(extendOrderId);

        // 根据仓库code找erp
        if(com.fs.common.utils.StringUtils.isNotBlank(order.getStoreHouseCode())){
            String erp = fsWarehousesMapper.selectErpByCode(order.getStoreHouseCode());
            ErpContextHolder.setErpType(erp);
        }

        ErpOrderQueryResponse response = erpOrderService.getOrderLive(request);

        if(CollectionUtils.isNotEmpty(response.getOrders())){
            ErpOrderQuery erpOrderQuery = response.getOrders().get(0);
            if(!LoginContextManager.hasPermission("live:liveOrder:queryAddress")){
                erpOrderQuery.setReceiver_address(ParseUtils.parseAddress(erpOrderQuery.getReceiver_address()));
            }
            if(!LoginContextManager.hasPermission("live:liveOrder:queryPhone")){
                erpOrderQuery.setReceiver_mobile(ParseUtils.parsePhone(erpOrderQuery.getReceiver_mobile()));
                erpOrderQuery.setReceiver_phone(ParseUtils.parsePhone(erpOrderQuery.getReceiver_phone()));
            }
        }
        return R.ok().put("data",response);
    }

    @Log(title = "冻结、解冻佣金", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('live:liveOrder:editTuiMoney')")
    @PostMapping("/editTuiMoney")
    public R editTuiMoney(@Validated @RequestBody FsStoreOrderEditTuiMoneyParam param, HttpServletRequest request) {
        return liveOrderService.editTuiMoney(param.getOrderId());
    }

    @Log(title = "确认订单", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('live:liveOrder:finishOrder')")
    @PostMapping("/finishOrder")
    public R finishOrder(@Validated @RequestBody FsStoreOrderFinishParam param, HttpServletRequest request) {
        return liveOrderService.finishOrder(param.getOrderId());
    }

    /**
     * 修改物流
     * @param deliveryDTO
     * @return AjaxResult
     */
    @Log(title = "修改物流", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('live:liveOrder:editDeliveryId')")
    @PutMapping("/editDeliveryId")
    public AjaxResult editDeliveryId(@RequestBody FsStoreDelivers deliveryDTO) {
        liveOrderService.editLiveOrderDeliveryId(deliveryDTO);
        return AjaxResult.success();
    }


    @Log(title = "手动推管易", businessType = BusinessType.INSERT)
    @ApiOperation("创建ERP订单")
    @PreAuthorize("@ss.hasPermi('live:liveOrder:createErpOrder')")
    @GetMapping("/createErpOrder")
    public R createErpOrder(@RequestParam("orderCode") String orderCode) throws Exception
    {
        logger.info("手动推管易 订单号: {}",orderCode);
        LiveOrder order=liveOrderService.selectOrderIdByOrderCode(orderCode);
        liveOrderService.createOmsOrder(order.getOrderId());
        return R.ok();
    }

    @Log(title = "同步管易物流单号", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('live:liveOrder:updateErpOrder')")
    @PostMapping("/updateErpOrder")
    public R updateErpOrder(@Validated @RequestBody FsStoreOrderExpressEditParam param) {
        LiveOrder order = liveOrderService.selectLiveOrderByOrderId(String.valueOf(param.getOrderId()));
        ErpOrderQueryRequert request = new ErpOrderQueryRequert();
        request.setCode(order.getExtendOrderId());

        // 根据仓库code找erp
        if(com.fs.common.utils.StringUtils.isNotBlank(order.getStoreHouseCode())){
            String erp = fsWarehousesMapper.selectErpByCode(order.getStoreHouseCode());
            ErpContextHolder.setErpType(erp);
        }

        ErpOrderQueryResponse response = erpOrderService.getOrderLive(request);
        if(response.getOrders()!=null&&response.getOrders().size()>0){
            for(ErpOrderQuery orderQuery : response.getOrders()){
                if(orderQuery.getDeliverys()!=null&&orderQuery.getDeliverys().size()>0){
                    for(ErpDeliverys delivery:orderQuery.getDeliverys()){
                        if(delivery.getDelivery()&& StringUtils.isNotEmpty(delivery.getMail_no())){
                            //更新商订单状态
                            liveOrderService.updateDeliveryOrder(param.getOrderId(), delivery.getMail_no(),delivery.getExpress_code(),delivery.getExpress_name());
                            return R.ok();
                        }
                    }

                }
            }
        }
        return R.error("未查询到快递信息");
    }



}
