package com.fs.his.controller;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.hutool.core.util.StrUtil;
import com.fs.common.core.domain.R;
import com.fs.common.core.domain.model.LoginUser;
import com.fs.common.utils.ParseUtils;
import com.fs.common.utils.SecurityUtils;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.StringUtils;
import com.fs.company.param.CompanyStoreOrderMoneyLogsListParam;
import com.fs.company.service.ICompanyMoneyLogsService;
import com.fs.company.vo.CompanyStoreOrderMoneyLogsVO;
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.*;
import com.fs.his.dto.ExpressInfoDTO;
import com.fs.his.dto.StoreOrderExpressExportDTO;
import com.fs.his.enums.ShipperCodeEnum;
import com.fs.his.param.FsFollowMsgParam;
import com.fs.his.param.FsStoreOrderParam;
import com.fs.his.param.FsStoreOrderSalesParam;
import com.fs.his.service.IFsExportTaskService;
import com.fs.his.service.IFsExpressService;
import com.fs.his.service.IFsStoreService;
import com.fs.his.vo.*;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.enums.BusinessType;
import com.fs.his.service.IFsStoreOrderService;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

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

/**
 * 订单Controller
 *
 * @author fs
 * @date 2023-06-13
 */
@RestController
@RequestMapping("/his/storeOrder")
public class FsStoreOrderController extends BaseController
{
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IFsStoreOrderService fsStoreOrderService;
    @Autowired
    private IFsExpressService expressService;
    @Autowired
    private ICompanyMoneyLogsService moneyLogsService;
    @Autowired
    private IFsStoreService fsStoreService;
    @Autowired
    private IFsExportTaskService exportTaskService;
    /**
     * 查询订单列表
     */
    @GetMapping("/list")
    public TableDataInfo list(FsStoreOrderParam fsStoreOrder)
    {
        startPage();
        if (fsStoreOrder.getUserPhoneMk()!=null&&fsStoreOrder.getUserPhoneMk()!=""){
            fsStoreOrder.setUserPhone(encryptPhone(fsStoreOrder.getUserPhoneMk()));
        }
        List<FsStoreOrderListVO> list = fsStoreOrderService.selectFsStoreOrderListVO(fsStoreOrder);
        return getDataTable(list);
    }

    /**
     * 导出订单列表
     */
    @PreAuthorize("@ss.hasPermi('his:storeOrder:export')")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(FsStoreOrderParam fsStoreOrder)
    {
        Integer exportType1 = exportTaskService.isExportType1(SecurityUtils.getUserId());
        if (exportType1>0){
            return AjaxResult.error("你已经有正在导出的任务");
        }
        if (fsStoreOrderService.isEntityNull(fsStoreOrder)){
            return AjaxResult.error("请筛选数据导出");
        }
        logger.info("tc>\n【订单导出】：{}", SecurityUtils.getUserId());
        Long count = fsStoreOrderService.selectFsStoreOrderExcelListVOCount(fsStoreOrder);
        if (count>30000){
            return AjaxResult.error("导出数据不可超过3w条");
        }
        FsExportTask task=new FsExportTask();
        task.setTaskType(4);
        task.setStatus(0);
        task.setStartTime(new Date());
        task.setRemark("药品订单财务导出");
        task.setSysType(1);
        task.setUserId(SecurityUtils.getUserId());
        exportTaskService.insertFsExportTask(task);
        fsStoreOrder.setTaskId(task.getTaskId());
        exportTaskService.exportStoreData(fsStoreOrder);
        return new AjaxResult(200,"后台正在导出,请等待...任务ID:"+task.getTaskId(),task.getTaskId());


    }

    /**
     * 导出订单列表
     */
    @PreAuthorize("@ss.hasPermi('store:storeOrder:export')")
    @Log(title = "导出订单", businessType = BusinessType.EXPORT)
    @GetMapping("/orderExport")
    public AjaxResult orderExport(FsStoreOrderParam param) {
        Integer exportType1 = exportTaskService.isExportType1(SecurityUtils.getUserId());
        if (exportType1>0){
            return AjaxResult.error("你已经有正在导出的任务");
        }
        if (fsStoreOrderService.isEntityNull(param)){
            return AjaxResult.error("请筛选数据导出");
        }
        logger.info("tc>\n【咨询报告】：{}", SecurityUtils.getUserId());
        Long count = fsStoreOrderService.selectFsStoreOrderListVOByExportCount(param);
        if (count>30000){
            return AjaxResult.error("导出数据不可超过3w条");
        }
        logger.info("tc>\n【订单导出】：{}", SecurityUtils.getUserId());

        FsExportTask task=new FsExportTask();
        task.setTaskType(3);
        task.setStatus(0);
        task.setStartTime(new Date());
        task.setRemark("药品订单导出");
        task.setSysType(1);
        task.setUserId(SecurityUtils.getUserId());
        exportTaskService.insertFsExportTask(task);
        param.setTaskId(task.getTaskId());
        exportTaskService.exportStore1Data(param);

        return new AjaxResult(200,"后台正在导出,请等待...任务ID:"+task.getTaskId(),task.getTaskId());


    }

    @GetMapping("/importTemplate")
    public AjaxResult sendExport()
    {
        ExcelUtil<FsStoreProductDeliverExcelVO> util = new ExcelUtil<>(FsStoreProductDeliverExcelVO.class);
        return util.importTemplateExcel("导入运单号");
    }

    @Log(title = "导入", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('store:storeOrder:importExpress')")
    @PostMapping("/importExpress")
    public AjaxResult importExpress(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<StoreOrderExpressExportDTO> util = new ExcelUtil<>(StoreOrderExpressExportDTO.class);
        List<StoreOrderExpressExportDTO> list = util.importExcel(file.getInputStream());
        String message = fsStoreOrderService.importExpress(list);
        return AjaxResult.success(message);
    }


    @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,null,null);
        return AjaxResult.success(message);
    }

    @GetMapping("/importExpressTemplate")
    public AjaxResult importExpressTemplate() {
        ExcelUtil<StoreOrderExpressExportDTO> util = new ExcelUtil<StoreOrderExpressExportDTO>(StoreOrderExpressExportDTO.class);
        return util.importTemplateExcel("物流回单数据");
    }
    /**
     * 获取订单详细信息
     */
    @Autowired
    IErpOrderService erpOrderService;
    @GetMapping(value = "/{orderId}")
    public R getInfo(@PathVariable("orderId") Long orderId) throws ParseException {
        FsStoreOrderVO order = fsStoreOrderService.selectFsStoreOrderByOrderIdVO(orderId);
        if (order.getPhone() != null && order.getPhone().length() > 11) {
            order.setPhone(decryptPhoneMk(order.getPhone()));
        } else {
            if (order.getPhone()!=null) {
                order.setPhone(order.getPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
            }
        }
        if (order.getUserPhone()!=null&&order.getUserPhone().length()>11){
            order.setUserPhone(decryptPhoneMk(order.getUserPhone()));
        }else {
            if (order.getUserPhone()!=null){
                order.setUserPhone(order.getUserPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
            }

        }

        List<CompanyStoreOrderMoneyLogsVO> tuiMoneyLogs=new ArrayList<>();
        if(order.getCompanyId()!=null){
            CompanyStoreOrderMoneyLogsListParam moneyLogsMap=new CompanyStoreOrderMoneyLogsListParam();
            moneyLogsMap.setCompanyId(order.getCompanyId());
            moneyLogsMap.setBusinessId(order.getOrderId());
            tuiMoneyLogs=moneyLogsService.selectCompanyStoreOrderMoneyLogsList(moneyLogsMap);
        }
        return R.ok().put("data",order).put("tuiMoneyLogs",tuiMoneyLogs);
    }

    @GetMapping(value = "/queryPhone/{orderId}")
    @Log(title = "查看电话", businessType = BusinessType.GRANT)
    @PreAuthorize("@ss.hasPermi('his:storeOrder:queryPhone')")
    public R getPhone(@PathVariable("orderId") Long orderId)
    {
        FsStoreOrderVO order = fsStoreOrderService.selectFsStoreOrderByOrderIdVO(orderId);
        String userPhone = order.getUserPhone();

        if (userPhone!=null&&userPhone.length()>11){
            userPhone=decryptPhone(userPhone);
        }
        return R.ok().put("userPhone",userPhone);
    }

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

    @GetMapping("/payment/{orderId}")
    public AjaxResult getPayInfo(@PathVariable("orderId") Long orderId)
    {
        return AjaxResult.success(fsStoreOrderService.selectFsStorePaymentByOrderId(orderId));
    }
    /**
     * 获取处方详细信息
     */

    @GetMapping("/Prescribe/{prescribeId}")
    public AjaxResult getPrescribeInfo(@PathVariable("prescribeId") Long prescribeId)
    {

        return AjaxResult.success(fsStoreOrderService.selectFsPrescribeByPrescribeIdVO(prescribeId));
    }

    /**
     * 新增订单
     */
    @PreAuthorize("@ss.hasPermi('his:storeOrder:add')")
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FsStoreOrder fsStoreOrder)
    {
        return toAjax(fsStoreOrderService.insertFsStoreOrder(fsStoreOrder));
    }

    /**
     * 修改订单
     */
    @PreAuthorize("@ss.hasPermi('his:storeOrder:edit')")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FsStoreOrder fsStoreOrder)
    {
        return toAjax(fsStoreOrderService.updateFsStoreOrder(fsStoreOrder));
    }

    @PreAuthorize("@ss.hasPermi('his:storeOrder:updateDelivery')")
    @Log(title = "修改物流", businessType = BusinessType.UPDATE)
    @PutMapping("/updateDelivery")
    public AjaxResult updateDelivery(@RequestBody FsStoreOrder fsStoreOrder)
    {

        FsStoreOrder  storeOrder = fsStoreOrderService.selectFsStoreOrderByOrderId(fsStoreOrder.getOrderId());
        if (storeOrder!=null){
            FsStore store = fsStoreService.selectFsStoreByStoreId(storeOrder.getStoreId());
            //订阅物流回调
            String lastFourNumber = "";
            if (fsStoreOrder.getDeliveryCode().equals(ShipperCodeEnum.SF.getValue())) {
                if (store!=null&&store.getSendPhone()!=null){
                    lastFourNumber = store.getSendPhone();
                }else {
                    lastFourNumber = storeOrder.getUserPhone();
                }
                if (lastFourNumber.length() == 11) {
                    lastFourNumber = StrUtil.sub(lastFourNumber, lastFourNumber.length(), -4);
                }
            }
            expressService.subscribeEspress(storeOrder.getOrderCode(),fsStoreOrder.getDeliveryCode(),fsStoreOrder.getDeliverySn(),lastFourNumber);
        }
        FsStoreOrder order = new FsStoreOrder();
        order.setDeliverySn(fsStoreOrder.getDeliverySn());
        order.setDeliveryCode(fsStoreOrder.getDeliveryCode());
        order.setOrderId(fsStoreOrder.getOrderId());
        return toAjax(fsStoreOrderService.updateFsStoreOrder(fsStoreOrder));
    }

    @Log(title = "同步管易物流单号", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('store:storeOrder:updateErpOrder')")
    @PostMapping("/updateErpOrder")
    public R updateErpOrder( @RequestBody FsStoreOrder param) {
        FsStoreOrder order = fsStoreOrderService.selectFsStoreOrderByOrderId(param.getOrderId());
        ErpOrderQueryRequert request = new ErpOrderQueryRequert();
        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())){
                            //更新商订单状态
                            fsStoreOrderService.updateDeliveryOrder(param.getOrderId(), delivery.getMail_no(),delivery.getExpress_code(),delivery.getExpress_name());
                            return R.ok();
                        }
                    }

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

    /**
     * 删除订单
     */
    @PreAuthorize("@ss.hasPermi('his:storeOrder:remove')")
    @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);
    }

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

    @Log(title = "申请售后", businessType = BusinessType.INSERT)
    @PreAuthorize("@ss.hasPermi('his:storeOrder:afterSales')")
    @PutMapping("/afterSales")
    public AjaxResult afterSales(@RequestBody FsStoreOrderSalesParam fsStoreOrder)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        fsStoreOrder.setOperator(loginUser.getUser().getNickName());
        return toAjax(fsStoreOrderService.afterSales(fsStoreOrder));
    }

    /**
     * 确认收货
     */
    @Log(title = "确认收货", businessType = BusinessType.INSERT)
    @PreAuthorize("@ss.hasPermi('his:storeOrder:good')")
    @PutMapping("/getGoods")
    public AjaxResult getGoods(@RequestBody FsStoreOrder fsStoreOrder)
    {
        logger.info("总后台手动确认收货："+fsStoreOrder.getOrderId());
        return toAjax(fsStoreOrderService.getGoods(fsStoreOrder.getOrderId()));
    }

    /**
     * 改价
     */
    @PreAuthorize("@ss.hasPermi('his:storeOrder:price')")
    @PutMapping("/updateMoney")
    public AjaxResult updateMoney(@RequestBody FsStoreOrder fsStoreOrder)
    {
        return toAjax(fsStoreOrderService.updateMoney(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订单")
    @PreAuthorize("@ss.hasPermi('his:storeOrder:createErpOrder')")
    @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();
    }

    @Log(title = "冻结/解冻", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('his:storeOrder:editTuiMoney')")
    @GetMapping(value = "/editTuiMoney/{id}")
    public R editTuiMoney(@PathVariable("id") Long id) throws Exception
    {
        return fsStoreOrderService.editTuiMoney(id);
    }

    @Log(title = "成本退还", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('his:storeOrder:returnCost')")
    @GetMapping(value = "/returnCost/{orderId}")
    public R returnCost(@PathVariable("orderId") Long orderId) throws Exception
    {
        return fsStoreOrderService.returnCost(orderId);
    }


    @PreAuthorize("@ss.hasPermi('his:storeOrder:getEroOrder')")
    @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)
    @PreAuthorize("@ss.hasPermi('his:storeOrder:syncExpress')")
    @GetMapping(value = "/syncExpress/{id}")
    public R syncExpress(@PathVariable("id") Long id) {
        return fsStoreOrderService.syncExpress(id);
    }

    @PreAuthorize("@ss.hasPermi('his:storeOrder:sendMsg')")
    @GetMapping(value = "/sendMsg/{orderId}")
    public AjaxResult sendMsg(@PathVariable("orderId") Long orderId)
    {
        return AjaxResult.success(fsStoreOrderService.sendStartMsg(orderId));
    }

    @PreAuthorize("@ss.hasPermi('his:storeOrder:updateExpress')")
    @GetMapping("/updateExpress/{id}")
    public R updateExpress(@PathVariable("id") Long id) {
        return fsStoreOrderService.updateExpress(id);
    }


    @PreAuthorize("@ss.hasPermi('his:storeOrder:express')")
    @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.getDeliveryCode().equals(ShipperCodeEnum.SF.getValue())) {

                lastFourNumber = order.getUserPhone();
                if (lastFourNumber.length() == 11) {
                    lastFourNumber = StrUtil.sub(lastFourNumber, lastFourNumber.length(), -4);
                }else if (lastFourNumber.length()>11){
                    String jm = decryptPhone(lastFourNumber);
                    lastFourNumber = StrUtil.sub(jm, jm.length(), -4);
                }
            }
            expressInfoDTO=expressService.getExpressInfo(order.getOrderCode(),order.getDeliveryCode(),order.getDeliverySn(),lastFourNumber);

            if((expressInfoDTO.getStateEx()!=null&&expressInfoDTO.getStateEx().equals("0"))&&(expressInfoDTO.getState()!=null&&expressInfoDTO.getState().equals("0"))){
                lastFourNumber = "19923690275";
                if (order.getDeliveryCode().equals(ShipperCodeEnum.SF.getValue())) {
                    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);
    }
    @PreAuthorize("@ss.hasPermi('his:storeOrder:msgList')")
    @GetMapping("/msgList")
    public TableDataInfo msgList(FsFollowMsgParam fsFollowMsgParam)
    {
        startPage();
        List<FsInquiryOrderMsg> list = fsStoreOrderService.selectFsInquiryOrderMsgByStoreOrderId(fsFollowMsgParam);
        return getDataTable(list);
    }


    @PreAuthorize("@ss.hasPermi('his:storeOrder:follow')")
    @GetMapping(value = "/follow/{followId}")
    public AjaxResult getFollow(@PathVariable("followId") Long followId)
    {
        return AjaxResult.success(fsStoreOrderService.selectFsFollowVOByFollowId(followId));
    }


}
