package com.fs.company.controller.live;

import cn.hutool.core.util.StrUtil;
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.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.framework.security.LoginUser;
import com.fs.framework.security.SecurityUtils;
import com.fs.crm.domain.CrmCustomer;
import com.fs.crm.service.ICrmCustomerService;
import com.fs.framework.service.TokenService;
import com.fs.his.domain.FsUser;
import com.fs.his.param.FsStoreOrderBindCustomerParam;
import com.fs.his.service.IFsExpressService;
import com.fs.his.service.IFsUserService;
import com.fs.hisStore.dto.ExpressInfoDTO;
import com.fs.hisStore.enums.ShipperCodeEnum;
import com.fs.hisStore.param.FsStoreOrderExpressParam;
import com.fs.hisStore.service.IFsExpressScrmService;
import com.fs.live.domain.*;
import com.fs.live.enums.LiveOrderCancleReason;
import com.fs.live.param.LiveOrderExpressParam;
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.LiveOrderTimeVo;
import com.fs.live.vo.LiveOrderVoZm;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import static com.fs.his.utils.PhoneUtil.decryptPhone;


/**
 * 订单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 IFsExpressService expressService;
//
//    @Autowired
//    private ConfigUtil configUtil;

//    @Autowired
//    @Qualifier("wdtErpOrderServiceImpl")
//    private IErpOrderService wdtOrderService;

    /**
     * 获取订单详细信息
     */
    @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);

        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);
    }

    /**
     * 查询订单列表
     */
    @PreAuthorize("@ss.hasPermi('live:liveOrder:list')")
    @GetMapping("/listZm")
    public TableDataInfo listZm(LiveOrder liveOrder)
    {
        startPage();
        liveOrder.setCompanyId(SecurityUtils.getLoginUser().getUser().getCompanyId());
        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()));
            vo.setCost(BigDecimal.ZERO);
            vo.setCostPrice(BigDecimal.ZERO);
        }
        return getDataTable(list);
    }

    /**
     * 导出订单列表
     */
    @PreAuthorize("@ss.hasPermi('live:liveOrder:export')")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @GetMapping("/exportZm")
    public AjaxResult exportZm(LiveOrder liveOrder)
    {
        liveOrder.setCompanyId(SecurityUtils.getLoginUser().getUser().getCompanyId());
        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()));
            vo.setCost(BigDecimal.ZERO);
            vo.setCostPrice(BigDecimal.ZERO);
        }
        ExcelUtil<LiveOrderVoZm> util = new ExcelUtil<LiveOrderVoZm>(LiveOrderVoZm.class);
        return util.exportExcel(list, "订单数据");
    }


//    @Log(title = "订单凭证上传", businessType = BusinessType.UPDATE)
////    @PreAuthorize("@ss.hasPermi('live:liveOrder:uploadCredentials')")
//    @PostMapping("/uploadCredentials")
//    public R UploadCredentials(@RequestBody LiveOrder order)
//    {
////        String[] imageUrls = order.getCredentials().split(",");
//        if (order.getCertificates() == null ){
//            return R.error("请选择图片上传");
//        }
//        liveOrderService.uploadCredentials(order);
//        return R.ok();
//    }

    @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)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        if (loginUser.getUser().getUserType().equals("00")){
            LiveOrder order = liveOrderService.selectLiveOrderByOrderId(String.valueOf(id));
            String userPhone = order.getUserPhone();
            return R.ok().put("userPhone",userPhone);
        }
        return R.error("无权查看");
    }

    /**
     * 根据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);
//        return R.ok();
    }

    /**
     * 推送到智慧药房
     */
    @Log(title = "推药房", businessType = BusinessType.INSERT)
    @PreAuthorize("@ss.hasPermi('his:storeOrder:sendHisGoods')")
    @PutMapping("/tuiOrder")
    public AjaxResult tuiOrder(@RequestBody LiveOrder liveOrder)
    {
        return toAjax(liveOrderService.tuiOrder(liveOrder.getOrderId()));
    }

    /**
     * 查询订单列表
     */
    @PreAuthorize("@ss.hasPermi('live:liveOrder:list')")
    @GetMapping("/list")
    public TableDataInfo list(LiveOrder liveOrder)
    {
        startPage();
        Long companyId = SecurityUtils.getLoginUser().getCompany().getCompanyId();
        liveOrder.setCompanyId(companyId);
        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: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)
    {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        liveOrder.setUserId(String.valueOf(userId));
        return liveOrderService.createLiveOrder(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:express')")
    @GetMapping(value = "/getExpress/{id}")
    public R getExpress(@PathVariable("id") String id)
    {
        return liveOrderService.syncExpress(Long.valueOf(id));
    }

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

    /**
     * 取消订单确认
     * */

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

//    @Log(title = "同步管易物流单号", businessType = BusinessType.UPDATE)
//    @PreAuthorize("@ss.hasPermi('live:liveOrder:updateErpOrder')")
//    @PostMapping("/updateErpOrder")
//    public R updateErpOrder( @RequestBody LiveOrder param) {
//        LiveOrder order = liveOrderService.selectLiveOrderByOrderId(String.valueOf(param.getOrderId()));
//        ErpOrderQueryRequert request = new ErpOrderQueryRequert();
//        IErpOrderService erpOrderService = getErpService();
//        request.setCode(order.getExtendOrderId());
//        ErpOrderQueryResponse response = erpOrderService.getOrder(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("未查询到快递信息");
//    }
//    private IErpOrderService getErpService() {
//        FsSysConfig sysConfig = configUtil.getSysConfig();
//        Integer erpOpen = sysConfig.getErpOpen();
//        if (erpOpen != null && erpOpen == 1){
//            //判断erp类型
//            Integer erpType = sysConfig.getErpType();
//            if (erpType != null){
//                IErpOrderService erpOrderService = null;
//                if (erpType == 1){
//                    //管易
//                    erpOrderService =  gyOrderService;
//                } else if (erpType == 2){
//                    //旺店通
//                    erpOrderService =  wdtOrderService;
//                }
//                return erpOrderService;
//
//
//            }
//        }
//        return null;
//    }

    /**
     * 查询订单商品列表
     */

    @GetMapping("/ltemlist/{orderId}")
    public TableDataInfo ltemlist(@PathVariable("orderId") String orderId)
    {
        List<LiveGoodsVo> list = liveOrderService.selectLiveOrderItemList(orderId);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('live:liveOrder:bindCustomer')")
    @PostMapping("/bindCustomer")
    public R bindCustomer(@RequestBody FsStoreOrderBindCustomerParam param)
    {
        if(param.getCustomerIds().length>1){
            return R.error("只能关联一个客户");
        }
        for(Long customerId:param.getCustomerIds()){
            LiveOrder order=new LiveOrder();
            order.setOrderId(param.getOrderId());
            order.setCustomerId(customerId);
            liveOrderService.updateLiveOrder(order);
            //更新CRM客户订单数
            crmCustomerService.updateBuyCount(customerId);
        }
        return R.ok("操作成功");

    }


}
