package com.fs.store.controller.store;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.fs.common.BeanCopyUtils;
import com.fs.common.core.domain.R;
import com.fs.common.utils.ParseUtils;
import com.fs.common.utils.StringUtils;
import com.fs.erp.dto.ErpOrderQueryRequert;
import com.fs.erp.dto.ErpOrderQueryResponse;
import com.fs.erp.service.IErpOrderService;
import com.fs.his.dto.ExpressInfoDTO;
import com.fs.his.dto.FsProdItemDTO;
import com.fs.his.enums.ShipperCodeEnum;
import com.fs.his.mapper.FsStoreOrderItemMapper;
import com.fs.his.param.FsStoreOrderListSParam;
import com.fs.his.param.FsStoreOrderParam;
import com.fs.his.param.FsStoreOrderSalesParam;
import com.fs.his.service.IFsExpressService;
import com.fs.his.vo.*;
import com.fs.store.utils.UserUtil;
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.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.his.domain.FsStoreOrder;
import com.fs.his.domain.FsStoreOrderItem;
import com.fs.his.domain.FsStoreOrderLogs;
import com.fs.his.service.IFsStoreOrderService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 订单Controller
 *
 * @author fs
 * @date 2023-06-13
 */
@RestController
@RequestMapping("/store/storeOrder")
public class FsStoreOrderController extends BaseController
{
    @Autowired
    private IFsStoreOrderService fsStoreOrderService;
    @Autowired
    private IFsExpressService expressService;

    @Autowired
    IErpOrderService erpOrderService;
    @Autowired
    FsStoreOrderItemMapper fsStoreOrderItemMapper;
    /**
     * 查询订单列表
     */

    @GetMapping("/list")
    public TableDataInfo list(FsStoreOrderParam fsStoreOrder)
    {
        fsStoreOrder.setStoreId(UserUtil.getLoginUserStoreID());
        startPage();
        List<FsStoreOrderListVO> list = fsStoreOrderService.selectFsStoreOrderListVO(fsStoreOrder);
        return getDataTable(list);
    }

    /**
     * 导出订单列表
     */

    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(FsStoreOrderParam fsStoreOrder)
    {

        fsStoreOrder.setStoreId(UserUtil.getLoginUserStoreID());
        List<FsStoreOrderExcelVO> list = fsStoreOrderService.selectFsStoreOrderExcelListSVO(fsStoreOrder);
        for (FsStoreOrderExcelVO fsStoreOrderVO : list) {

            String productName="";
            String barCode="";
            String itemJson = fsStoreOrderVO.getItemJson();
            List<FsStoreOrderItem> items = JSON.parseArray(itemJson, FsStoreOrderItem.class);
            for (FsStoreOrderItem item : items) {
                String jsonInfo = item.getJsonInfo();
                FsProdItemDTO fsProdItemDTO = JSON.parseObject(jsonInfo, FsProdItemDTO.class);
                productName+=fsProdItemDTO.getProductName()+"*"+fsProdItemDTO.getNum()+";";
                barCode+=fsProdItemDTO.getBarCode()+"*"+fsProdItemDTO.getNum()+";";
            }

            fsStoreOrderVO.setProductName(productName);
            fsStoreOrderVO.setBarCode(barCode);
        }
        List<FsStoreOrderStoreExcelVO> fsStoreOrderStoreExcelVOS = BeanCopyUtils.copyList(list, FsStoreOrderStoreExcelVO.class);
        ExcelUtil<FsStoreOrderStoreExcelVO> util = new ExcelUtil<FsStoreOrderStoreExcelVO>(FsStoreOrderStoreExcelVO.class);
        return util.exportExcel(fsStoreOrderStoreExcelVOS, "订单数据");
    }

    /**
     * 导出订单列表
     */

    @GetMapping("/importTemplate")
    public AjaxResult sendExport()
    {
        Long loginUserStoreID = UserUtil.getLoginUserStoreID();
        if (loginUserStoreID==30||loginUserStoreID==31&&loginUserStoreID==33){
            return AjaxResult.error("此店铺不可导出订单");
        }
        ExcelUtil<FsStoreProductDeliverExcelVO> util = new ExcelUtil<>(FsStoreProductDeliverExcelVO.class);
        return util.importTemplateExcel("订单");
    }

    @Log(title = "导入运单号", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<FsStoreProductDeliverExcelVO> util = new ExcelUtil<>(FsStoreProductDeliverExcelVO.class);
        List<FsStoreProductDeliverExcelVO> list = util.importExcel(file.getInputStream());
        String message = fsStoreOrderService.importSroreOrder(list,UserUtil.getLoginUserStoreID(),null);
        return AjaxResult.success(message);
    }

    /**
     * 获取订单详细信息
     */

    @GetMapping(value = "/{orderId}")
    public AjaxResult getInfo(@PathVariable("orderId") Long orderId)
    {
        FsStoreOrder fsStoreOrder = fsStoreOrderService.selectFsStoreOrderByOrderId(orderId);
        fsStoreOrder.setUserAddress(ParseUtils.parseAddress(fsStoreOrder.getUserAddress()));
        fsStoreOrder.setUserPhone(ParseUtils.parsePhone(fsStoreOrder.getUserPhone()));
        return AjaxResult.success(fsStoreOrder);
    }

    /**
     * 新增订单
     */

    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FsStoreOrder fsStoreOrder)
    {
        return toAjax(fsStoreOrderService.insertFsStoreOrder(fsStoreOrder));
    }

    /**
     * 修改订单
     */

    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FsStoreOrder fsStoreOrder)
    {
        return toAjax(fsStoreOrderService.updateFsStoreOrder(fsStoreOrder));
    }

    /**
     * 删除订单
     */

    @Log(title = "订单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{orderIds}")
    public AjaxResult remove(@PathVariable String[] orderIds)
    {
        return toAjax(fsStoreOrderService.deleteFsStoreOrderByOrderIds(orderIds));
    }

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

    @GetMapping("/ltemlist/{orderId}")
    public TableDataInfo ltemlist(@PathVariable("orderId") String orderId)
    {
        List<FsStoreOrderItem> list = fsStoreOrderService.selectFsStoreOrderItemList(orderId);
        return getDataTable(list);
    }
    /**
     * 查询订单log列表
     */
    @GetMapping("/logList/{orderId}")
    public TableDataInfo logList(@PathVariable("orderId") String orderId)
    {
        List<FsStoreOrderLogs> list = fsStoreOrderService.selectFsStoreOrderLogsList(orderId);
        return getDataTable(list);
    }
    /**
     * 获取处方详细信息
     */

    @GetMapping("/Prescribe/{prescribeId}")
    public AjaxResult getPrescribeInfo(@PathVariable("prescribeId") Long prescribeId)
    {
        return AjaxResult.success(fsStoreOrderService.selectFsPrescribeByPrescribeIdVO(prescribeId));
    }

    /**
     * 获取订单支付信息详情
     */

    @GetMapping("/payment/{orderId}")
    public AjaxResult getPayInfo(@PathVariable("orderId") Long orderId)
    {
        return AjaxResult.success(fsStoreOrderService.selectFsStorePaymentByOrderId(orderId));
    }
    /**
     * 发货
     */

    @PutMapping("/sendGoods")
    public AjaxResult sendGoods(@RequestBody FsStoreOrder fsStoreOrder)
    {
        return toAjax(fsStoreOrderService.sendGoods(fsStoreOrder));
    }


    /**
     * 确认收货
     */

    @PutMapping("/getGoods")
    public AjaxResult getGoods(@RequestBody FsStoreOrder fsStoreOrder)
    {
        return toAjax(fsStoreOrderService.getGoods(fsStoreOrder.getOrderId()));
    }

    /**
     * 改价
     */

    @PutMapping("/updateMoney")
    public AjaxResult updateMoney(@RequestBody FsStoreOrder fsStoreOrder)
    {
        return toAjax(fsStoreOrderService.updateMoney(fsStoreOrder));
    }



    @PutMapping("/tuiOrder")
    public AjaxResult tuiOrder(@RequestBody FsStoreOrder fsStoreOrder)
    {
        return toAjax(fsStoreOrderService.tuiOrder(fsStoreOrder.getOrderId()));
    }


    @PutMapping("/afterSales")
    public AjaxResult afterSales(@RequestBody FsStoreOrderSalesParam fsStoreOrder)
    {
        return toAjax(fsStoreOrderService.afterSales(fsStoreOrder));
    }

    @GetMapping("/getCustomerOrderList")
    public TableDataInfo getCustomerOrderList(FsStoreOrderParam param) {
        startPage();

        List<FsStoreOrderListVO> list = fsStoreOrderService.selectFsStoreOrderListVO(param);
        return getDataTable(list);
    }

    @Log(title = "手动推管易", businessType = BusinessType.INSERT)
    @ApiOperation("创建ERP订单")
    @GetMapping(value = "/createErpOrder/{id}")
    public R createErpOrder(@PathVariable("id") Long id) throws Exception
    {
        FsStoreOrder order=fsStoreOrderService.selectFsStoreOrderByOrderId(id);
        fsStoreOrderService.createOmsOrder(order.getOrderId());
        return R.ok();
    }


    @GetMapping("/getEroOrder/{extendOrderId}")
    public R getEroOrder(@PathVariable("extendOrderId") String extendOrderId) {
        ErpOrderQueryRequert request = new ErpOrderQueryRequert();
        request.setCode(extendOrderId);
        ErpOrderQueryResponse response = erpOrderService.getOrder(request);
        return R.ok().put("data",response);
    }
    @Log(title = "同步物流", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/syncExpress/{id}")
    public R syncExpress(@PathVariable("id") Long id) {
        return fsStoreOrderService.syncExpress(id);
    }

    @GetMapping("/updateExpress/{id}")
    public R updateExpress(@PathVariable("id") Long id) {
        return fsStoreOrderService.updateExpress(id);
    }



    @GetMapping(value = "/getExpress/{id}")
    public R getExpress(@PathVariable("id") Long id)
    {
        FsStoreOrder order=fsStoreOrderService.selectFsStoreOrderByOrderId(id);
        ExpressInfoDTO expressInfoDTO=null;
        if(StringUtils.isNotEmpty(order.getDeliverySn())){
            String lastFourNumber = "";
            if (order.getDeliverySn().equals(ShipperCodeEnum.SF.getValue())) {
                lastFourNumber = order.getUserPhone();
                if (lastFourNumber.length() == 11) {
                    lastFourNumber = StrUtil.sub(lastFourNumber, lastFourNumber.length(), -4);
                }
            }
            expressInfoDTO=expressService.getExpressInfo(order.getOrderCode(),order.getDeliveryCode(),order.getDeliverySn(),lastFourNumber);
        }
        return R.ok().put("data",expressInfoDTO);
    }
}
