package com.fs.live.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.fs.common.annotation.Log;
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.domain.model.LoginUser;
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.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.framework.web.service.TokenService;
import com.fs.his.domain.FsDfAccount;
import com.fs.his.domain.FsStoreOrderDf;
import com.fs.his.domain.FsUser;
import com.fs.his.enums.FsStoreOrderLogEnum;
import com.fs.his.service.IFsDfAccountService;
import com.fs.his.service.IFsExpressService;
import com.fs.his.service.IFsUserService;
import com.fs.his.utils.ConfigUtil;
import com.fs.hisStore.config.FsErpConfig;
import com.fs.hisStore.dto.StoreOrderExpressExportDTO;
import com.fs.hisStore.param.*;
import com.fs.hisStore.service.IFsExpressScrmService;
import com.fs.hisStore.task.ExpressTask;
import com.fs.hisStore.task.LiveTask;
import com.fs.hisStore.vo.FsStoreOrderItemExportZMVO;
import com.fs.hisStore.vo.FsStoreOrderVO;
import com.fs.live.domain.*;
import com.fs.live.dto.LiveOrderCustomerExportDTO;
import com.fs.live.dto.LiveOrderDeliveryNoteDTO;
import com.fs.live.dto.LiveOrderExpressExportDTO;
import com.fs.live.param.LiveOrderParam;
import com.fs.live.vo.LiveOrderDeliveryNoteExportVO;
import com.fs.live.enums.LiveOrderCancleReason;
import com.fs.live.param.LiveOrderScrmSetErpPhoneParam;
import com.fs.live.service.*;
import com.fs.live.vo.*;
import com.fs.qw.utils.RSAUtils;
import com.fs.store.domain.FsStoreDelivers;
import com.fs.system.domain.SysConfig;
import com.fs.system.mapper.SysConfigMapper;
import io.swagger.annotations.ApiOperation;
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 org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**`
 * 订单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 IFsExpressScrmService expressService;
//    @Autowired
//    private FsWarehousesMapper fsWarehousesMapper;
    @Autowired
    IErpOrderService erpOrderService;



    @Autowired
    private IFsDfAccountService fsDfAccountService;

    @Autowired
    SysConfigMapper sysConfigMapper;

    @Autowired
    private ILiveOrderDfService liveOrderDfService;

    @Autowired
    private LiveTask liveTask;
    @Autowired
    @Qualifier("erpOrderServiceImpl")
    private IErpOrderService gyOrderService;

    @Autowired
    @Qualifier("wdtErpOrderServiceImpl")
    private IErpOrderService wdtOrderService;
    @Autowired
    @Qualifier("hzOMSErpOrderServiceImpl")
    private IErpOrderService hzOMSErpOrderService;
    @Autowired
    @Qualifier("dfOrderServiceImpl")
    private IErpOrderService dfOrderService;
    @Autowired
    @Qualifier("k9OrderScrmServiceImpl")
    private IErpOrderService k9OrderService;
    @Autowired
    @Qualifier("JSTErpOrderServiceImpl")
    private IErpOrderService jSTOrderService;
    @Autowired
    private ConfigUtil configUtil;




    @GetMapping("/importTemplate")
    public AjaxResult importTemplate() {
        ExcelUtil<LiveOrderExpressExportDTO> util = new ExcelUtil<LiveOrderExpressExportDTO>(LiveOrderExpressExportDTO.class);
        return util.importTemplateExcel("物流回单数据");
    }

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


    /**
     * 导出订单列表
     */
    @PreAuthorize("@ss.hasPermi('live:liveOrder:export')")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(LiveOrder liveOrder)
    {
        List<LiveOrder> list = liveOrderService.selectLiveOrderList(liveOrder);
        ExcelUtil<LiveOrder> util = new ExcelUtil<LiveOrder>(LiveOrder.class);
        return util.exportExcel(list, "订单数据");
    }

    /**
     * 查询订单列表
     */
    @PreAuthorize("@ss.hasPermi('live:liveOrder:list')")
    @GetMapping("/listZm")
    public TableDataInfo listZm(LiveOrder liveOrder)
    {
        startPage();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        List<LiveOrderVoZm> list = liveOrderService.selectLiveOrderListZm(liveOrder);
        for (LiveOrderVoZm vo : list){
            vo.setUserPhone(ParseUtils.parsePhone(vo.getUserPhone()));
            vo.setCompanyUserPhone(ParseUtils.parsePhone(vo.getCompanyUserPhone()));
            vo.setUserBindPhone(ParseUtils.parsePhone(vo.getUserBindPhone()));
            vo.setUserAddress(ParseUtils.parseAddress(vo.getUserAddress()));

            // 财务独特字段
            if (loginUser.getPermissions().contains("live:liveOrder:finance") || loginUser.getPermissions().contains("*:*:*")) {
                vo.setCostPrice(vo.getCostPrice());
                vo.setFPrice(vo.getCostPrice().multiply(BigDecimal.valueOf(Long.parseLong(vo.getTotalNum()))));
            } else {
                vo.setCostPrice(BigDecimal.ZERO);
                vo.setFPrice(BigDecimal.ZERO);
                vo.setPayDelivery(BigDecimal.ZERO);
                vo.setBarCode("");
                vo.setCateName("");
                vo.setBankTransactionId("");
            }
            vo.setCost(vo.getCostPrice());

        }
        return getDataTable(list);
    }

    /**
     * 导出订单列表
     */
    @PreAuthorize("@ss.hasPermi('live:liveOrder:export')")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @GetMapping("/exportZm")
    public AjaxResult exportZm(LiveOrder liveOrder)
    {
        List<LiveOrderVoZm> list = liveOrderService.selectLiveOrderListZm(liveOrder);
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        for (LiveOrderVoZm vo : list){
            vo.setUserPhone(ParseUtils.parsePhone(vo.getUserPhone()));
            vo.setCompanyUserPhone(ParseUtils.parsePhone(vo.getCompanyUserPhone()));
            vo.setUserBindPhone(ParseUtils.parsePhone(vo.getUserBindPhone()));
            vo.setUserAddress(ParseUtils.parseAddress(vo.getUserAddress()));
            // 财务独特字段
            if (loginUser.getPermissions().contains("live:liveOrder:finance") || loginUser.getPermissions().contains("*:*:*")) {
                vo.setCostPrice(vo.getCost());
                vo.setFPrice(vo.getCostPrice().multiply(BigDecimal.valueOf(Long.parseLong(vo.getTotalNum()))));
            } else {
                vo.setCostPrice(BigDecimal.ZERO);
                vo.setFPrice(BigDecimal.ZERO);
                vo.setBankTransactionId("");
            }
            vo.setCost(vo.getCostPrice());
        }
        ExcelUtil<LiveOrderVoZm> util = new ExcelUtil<LiveOrderVoZm>(LiveOrderVoZm.class);
        return util.exportExcel(list, "订单数据");
    }

    /**
     * 导出订单列表
     */
    @PreAuthorize("@ss.hasPermi('live:liveOrder:export')")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @GetMapping("/exportZmNew")
    public AjaxResult exportZmNew(LiveOrder liveOrder){
        List<FsStoreOrderItemExportZMVO> list = liveOrderService.selectLiveOrderListZmNew(liveOrder);
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        for (FsStoreOrderItemExportZMVO vo : list){
            vo.setUserPhone(ParseUtils.parsePhone(vo.getUserPhone()));
//            vo.setCompanyUserPhone(ParseUtils.parsePhone(vo.getCompanyUserPhone()));
//            vo.setUserBindPhone(ParseUtils.parsePhone(vo.getUserBindPhone()));
            vo.setUserAddress(ParseUtils.parseAddress(vo.getUserAddress()));
            // 财务独特字段
            if (loginUser.getPermissions().contains("live:liveOrder:finance") || loginUser.getPermissions().contains("*:*:*")) {
//                vo.setCostPrice(vo.getCost());
                vo.setFPrice(vo.getCost().multiply(BigDecimal.valueOf(vo.getNum())));
            } else {
                vo.setCost(BigDecimal.ZERO);
                vo.setFPrice(BigDecimal.ZERO);
                vo.setBankTransactionId("");
            }
//            vo.setCost(vo.getCostPrice());
        }
        ExcelUtil<FsStoreOrderItemExportZMVO> util = new ExcelUtil<FsStoreOrderItemExportZMVO>(FsStoreOrderItemExportZMVO.class);
        return util.exportExcel(list, "订单数据");
    }
    /**
     * 获取订单详细信息
     */
    @PreAuthorize("@ss.hasPermi('live:liveOrder:query')")
    @GetMapping(value = "/info/{orderId}")
    public AjaxResult getInfo(@PathVariable("orderId") String orderId)
    {
        return AjaxResult.success(liveOrderService.selectLiveOrderByOrderId(orderId));
    }


    /**
     * 新增订单
     */
    @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(LiveOrderTimeVo 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);
    }


    @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","123");
    }

    @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) {
        IErpOrderService erpOrderService = getErpService();
        ErpOrderQueryRequert request = new ErpOrderQueryRequert();
        request.setCode(extendOrderId);
        ErpOrderQueryResponse response = erpOrderService.getLiveOrder(request);
        return R.ok().put("data",response);
    }
    private IErpOrderService getErpService(){
        //判断是否开启erp
        IErpOrderService erpOrderService = null;
        FsErpConfig erpConfig = configUtil.getErpConfig();
        Integer erpOpen = erpConfig.getErpOpen();
        if (erpOpen != null && erpOpen == 1) {
            //判断erp类型
            Integer erpType = erpConfig.getErpType();
            if (erpType != null) {
                if (erpType == 1){
                    //管易
                    erpOrderService =  gyOrderService;
                } else if (erpType == 2){
                    //旺店通
                    erpOrderService =  wdtOrderService;
                } else if (erpType == 3){
                    //
                    erpOrderService =  hzOMSErpOrderService;
                } else if (erpType == 4){
                    //代服
                    erpOrderService =  dfOrderService;
                }else if(erpType == 5){
                    erpOrderService=jSTOrderService;
                }else if(erpType == 6){
                    erpOrderService=k9OrderService;
                }
            }
        }
        return erpOrderService;
    }

    @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);
        if (orderPaymentService.selectByBussinessId(order.getOrderId()) != null) {
            liveOrderService.createOmsOrder(order.getOrderId());
            return R.ok();
        }
        return R.error("订单未支付！");

    }

    @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("未查询到快递信息");
    }

    /**
     * 删除订单
     */
    @PreAuthorize("@ss.hasPermi('live:liveOrder:remove')")
    @Log(title = "订单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(liveOrderService.deleteLiveOrderByIds(ids));
    }

    /**
     * 获取erp账户
     */
    @GetMapping("/getErpAccount")
    public R getErpAccount()
    {
        List<FsDfAccount> erpAccounts = fsDfAccountService.selectFsDfAccountList(null);
        List<String> list = erpAccounts.stream().map(FsDfAccount::getLoginAccount).collect(Collectors.toList());
        return R.ok().put("data", list);
    }

    /**
     * 查询erp默认手机号
     * @return
     */
    @GetMapping(value = "/queryErpPhone")
    public AjaxResult queryErpPhone()
    {
        SysConfig sysConfig = sysConfigMapper.selectConfigByConfigKey("erp.phone");
        List<String> list = new ArrayList<>();
        if(sysConfig!=null){
            String configValue = sysConfig.getConfigValue();
            if(StringUtils.isNotEmpty(configValue)){
                list = JSON.parseArray(configValue, String.class);
            }
        }
        return AjaxResult.success(list);
    }

    /**
     * 设置erp默认手机号
     * @param phoneList
     * @return
     */
    @PostMapping(value = "/saveErpPhone")
    public AjaxResult saveErpPhone(@RequestBody List<String> phoneList)
    {
        //去重
        phoneList = phoneList.stream().distinct().collect(Collectors.toList());
        SysConfig sysConfig = sysConfigMapper.selectConfigByConfigKey("erp.phone");
        sysConfig.setConfigValue(JSON.toJSONString(phoneList));
        return AjaxResult.success(sysConfigMapper.updateConfig(sysConfig));
    }

    /**
     * 批量设置erp手机号
     */
    @PreAuthorize("@ss.hasPermi('live:liveOrder:createErpOrder')")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PostMapping("/editErpPhone")
    public AjaxResult editErpPhone(@RequestBody LiveOrderScrmSetErpPhoneParam param)
    {
        param.setOpeName(getLoginUser().getUser().getNickName());
        List<String> erpPhone = param.getErpPhone();
        if (erpPhone == null || erpPhone.isEmpty()) {
            return AjaxResult.error("请选择手机号");
        }
        return toAjax(liveOrderService.batchUpdateErpByOrderIds(param));
    }

    @Log(title = "手动推管易", businessType = BusinessType.INSERT)
    @ApiOperation("批量创建ERP订单")
    @PreAuthorize("@ss.hasPermi('his:storeOrder:createErpOrder')")
    @PostMapping(value = "/batchCreateErpOrder")
    public R batchCreateErpOrder(@RequestBody LiveOrderScrmSetErpPhoneParam param)
    {
        String nickName = getLoginUser().getUser().getNickName();
        String loginAccount = param.getLoginAccount();
        if (StringUtils.isBlank(loginAccount)){
            return R.error("未选择推送erp账户");
        }
        LiveOrderDf df = getDFInfo(loginAccount);
        if (df.getLoginAccount() == null){
            return R.error("未查询到所选erp账户");
        }
        List<Long> orderIds = param.getOrderIds();
        if (orderIds  == null || orderIds.isEmpty()) {
            if(!StringUtils.isEmpty(param.getCreateTimeRange())){
                param.setCreateTimeList(param.getCreateTimeRange().split("--"));
            }
            if(!StringUtils.isEmpty(param.getPayTimeRange())){
                param.setPayTimeList(param.getPayTimeRange().split("--"));
            }
            if(!StringUtils.isEmpty(param.getDeliveryImportTimeRange())){
                param.setDeliveryImportTimeList(param.getDeliveryImportTimeRange().split("--"));
            }
            if(!StringUtils.isEmpty(param.getDeliverySendTimeRange())){
                param.setDeliverySendTimeList(param.getDeliverySendTimeRange().split("--"));
            }
            param.setNotHealth(1);
            List<LiveOrderVO> list = liveOrderService.selectLiveOrderListVO(param);
            orderIds = list.stream().map(LiveOrderVO::getId).collect(Collectors.toList());
        }
        if (orderIds.isEmpty()){
            return R.ok();
        }
        orderIds.forEach(orderId->{
            try {
                df.setOrderId(orderId);
                LiveOrderDf temp = liveOrderDfService.selectLiveOrderDfByOrderId(df.getOrderId());
                if (temp == null){
                    df.setParcelQuantity(param.getParcelQuantity()); //设置包裹数量
                    liveOrderDfService.insertLiveOrderDf(df);
                    orderLogsService.create(orderId, FsStoreOrderLogEnum.SET_PUSH_ACCOUNT.getValue(),
                            nickName + " " +FsStoreOrderLogEnum.SET_PUSH_ACCOUNT.getDesc() + ":" + df.getLoginAccount());
                }
                if (orderPaymentService.selectByBussinessId(orderId) != null) {
                    liveOrderService.createOmsOrder(orderId);
                    orderLogsService.create(orderId, FsStoreOrderLogEnum.PUSH_ORDER_ERP.getValue(),
                            nickName + " " +FsStoreOrderLogEnum.PUSH_ORDER_ERP.getDesc() + ":" + df.getLoginAccount());
                }
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }

        });
        return R.ok();
    }

    @ApiOperation("批量设置订单账户")
    @PreAuthorize("@ss.hasPermi('his:storeOrder:createErpOrder')")
    @PostMapping(value = "/batchSetErpOrder")
    public R batchSetErpOrder(@RequestBody LiveOrderScrmSetErpPhoneParam param)
    {
        String nickName = getLoginUser().getUser().getNickName();
        String loginAccount = param.getLoginAccount();
        if (StringUtils.isBlank(loginAccount)){
            return R.error("未选择erp账户");
        }
        LiveOrderDf df = getDFInfo(loginAccount);
        if (df.getLoginAccount() == null){
            return R.error("未查询到所选erp账户");
        }
        List<Long> orderIds = param.getOrderIds();
        if (orderIds  == null || orderIds.isEmpty()) {
            if(!StringUtils.isEmpty(param.getCreateTimeRange())){
                param.setCreateTimeList(param.getCreateTimeRange().split("--"));
            }
            if(!StringUtils.isEmpty(param.getPayTimeRange())){
                param.setPayTimeList(param.getPayTimeRange().split("--"));
            }
            if(!StringUtils.isEmpty(param.getDeliveryImportTimeRange())){
                param.setDeliveryImportTimeList(param.getDeliveryImportTimeRange().split("--"));
            }
            if(!StringUtils.isEmpty(param.getDeliverySendTimeRange())){
                param.setDeliverySendTimeList(param.getDeliverySendTimeRange().split("--"));
            }
            param.setNotHealth(1);
            List<LiveOrderVO> list = liveOrderService.selectLiveOrderListVO(param);
            orderIds = list.stream().map(LiveOrderVO::getId).collect(Collectors.toList());
        }
        if (orderIds.isEmpty()){
            return R.ok();
        }
        orderIds.forEach(orderId->{
            df.setOrderId(orderId);
            LiveOrderDf temp = liveOrderDfService.selectLiveOrderDfByOrderId(df.getOrderId());
            df.setParcelQuantity(param.getParcelQuantity());
            if (temp != null){
                df.setUpdateTime(new Date());
                liveOrderDfService.updateLiveOrderDf(df);
            } else {
                liveOrderDfService.insertLiveOrderDf(df);
            }
            orderLogsService.create(orderId, FsStoreOrderLogEnum.SET_PUSH_ACCOUNT.getValue(),
                    nickName + " " +FsStoreOrderLogEnum.SET_PUSH_ACCOUNT.getDesc() + ":" + df.getLoginAccount());
        });
        return R.ok();
    }

    private LiveOrderDf getDFInfo(String loginAccount) {
        //查询订单账户 判断是否存在该订单账户
        List<FsDfAccount> erpAccounts = fsDfAccountService.selectFsDfAccountList(null);
        LiveOrderDf df = new LiveOrderDf();
        for (FsDfAccount erpAccount : erpAccounts) {
            if (loginAccount.equals(erpAccount.getLoginAccount())){
                //添加df记录
                df.setAppKey(erpAccount.getDfAppKey());
                df.setAppSecret(erpAccount.getDfAppsecret());
                df.setLoginAccount(loginAccount);
                df.setMonthlyCard(erpAccount.getMonthlyCard());
                df.setExpressProductCode(erpAccount.getExpressProductCode());
                df.setStatus(0);
                break;
            }
        }
        return df;
    }



}
