package com.fs.company.controller.store;

import cn.hutool.core.util.StrUtil;
import com.fs.common.annotation.DataScope;
import com.fs.common.annotation.Log;
import com.fs.common.annotation.RepeatSubmit;
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.StringUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.crm.service.ICrmCustomerService;
import com.fs.erp.dto.ErpOrderQueryRequert;
import com.fs.erp.dto.ErpOrderQueryResponse;
import com.fs.erp.service.IErpOrderService;
import com.fs.framework.security.LoginUser;
import com.fs.framework.security.SecurityUtils;
import com.fs.his.domain.*;
import com.fs.his.dto.ExpressInfoDTO;
import com.fs.his.enums.ShipperCodeEnum;
import com.fs.his.param.FsFollowMsgParam;
import com.fs.his.param.FsStoreOrderBindCustomerParam;
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.IFsStoreOrderService;
import com.fs.his.utils.PhoneUtil;
import com.fs.his.vo.FsStoreOrderListVO;
import com.fs.his.vo.FsStoreOrderVO;
import com.fs.his.vo.FsStoreProductDeliverExcelVO;
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.Date;
import java.util.List;

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

/**
 * 订单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
    private IFsExportTaskService exportTaskService;
    @Autowired
    ICrmCustomerService crmCustomerService;
    /**
     * 查询订单列表
     */
    @GetMapping("/list")
    @PreAuthorize("@ss.hasPermi('his:storeOrder:list')")
    @DataScope(deptAlias = "cu",userAlias = "cu")
    public TableDataInfo list(FsStoreOrderParam fsStoreOrder)
    {
        startPage();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        fsStoreOrder.setCompanyId(loginUser.getCompany().getCompanyId());
        if(fsStoreOrder.getUserPhoneMk()!=null&&fsStoreOrder.getUserPhoneMk()!=""){
            fsStoreOrder.setUserPhone(encryptPhone(fsStoreOrder.getUserPhoneMk()));
        }
        List<FsStoreOrderListVO> list = fsStoreOrderService.selectFsStoreOrderListVO(fsStoreOrder);
        return getDataTable(list);
    }

    @GetMapping("/myList")
    @PreAuthorize("@ss.hasPermi('his:storeOrder:myList')")
    public TableDataInfo myList(FsStoreOrderParam fsStoreOrder)
    {
        startPage();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        fsStoreOrder.setCompanyId(loginUser.getCompany().getCompanyId());
        fsStoreOrder.setCompanyUserId(loginUser.getUser().getUserId());
        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)
    @DataScope(deptAlias = "cu",userAlias = "cu")
    @GetMapping("/export")
    public AjaxResult export(FsStoreOrderParam param)
    {

        LoginUser loginUser = SecurityUtils.getLoginUser();
        param.setCompanyId(loginUser.getCompany().getCompanyId());
        Long userId = loginUser.getUser().getUserId();
        Integer exportType1 = exportTaskService.isExportType2(userId);
        if (exportType1>0){
            return AjaxResult.error("你已经有正在导出的任务");
        }
        logger.info("导出订单:"+ userId);
        if (fsStoreOrderService.isEntityNull(param)){
            return AjaxResult.error("请筛选数据导出");
        }
        Long count =fsStoreOrderService.selectFsStoreOrderListVOByExportCount(param);
        if (count>30000){
            return AjaxResult.error("导出数据不可超过3w条");
        }
        FsExportTask task=new FsExportTask();
        task.setTaskType(3);
        task.setStatus(0);
        task.setStartTime(new Date());
        task.setRemark("药品订单导出");
        task.setSysType(2);
        task.setCompanyUserId(userId);
        exportTaskService.insertFsExportTask(task);
        param.setTaskId(task.getTaskId());
        exportTaskService.exportStore1Data(param);
        return new AjaxResult(200,"后台正在导出,请等待...任务ID:"+task.getTaskId(),task.getTaskId());


    }
    /**
     * 导出订单列表
     */
    @PreAuthorize("@ss.hasPermi('his:storeOrder:myExport')")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @GetMapping("/myExport")
    public AjaxResult myExport(FsStoreOrderParam param)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        param.setCompanyId(loginUser.getCompany().getCompanyId());
        param.setCompanyUserId(loginUser.getUser().getUserId());
        logger.info("导出订单:"+ loginUser.getUser().getUserId());
        if (fsStoreOrderService.isEntityNull(param)){
            return AjaxResult.error("请筛选数据导出");
        }

        Long userId = loginUser.getUser().getUserId();
        Integer exportType1 = exportTaskService.isExportType2(userId);
        if (exportType1>0){
            return AjaxResult.error("你已经有正在导出的任务");
        }
        if(param.getUserPhoneMk()!=null&&param.getUserPhoneMk()!=""){
            param.setUserPhone(encryptPhone(param.getUserPhoneMk()));
        }
        Long count =fsStoreOrderService.selectFsStoreOrderListVOByExportCount(param);
        if (count>30000){
            return AjaxResult.error("导出数据不可超过3w条");
        }
        FsExportTask task=new FsExportTask();
        task.setTaskType(3);
        task.setStatus(0);
        task.setStartTime(new Date());
        task.setRemark("药品订单导出");
        task.setSysType(2);
        task.setCompanyUserId(userId);
        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)
    @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,SecurityUtils.getLoginUser().getCompany().getCompanyId());
        return AjaxResult.success(message);
    }

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

    @GetMapping(value = "/{orderId}")
    public AjaxResult getInfo(@PathVariable("orderId") Long orderId)
    {
        FsStoreOrderVO order = fsStoreOrderService.selectFsStoreOrderByOrderIdVO(orderId);
        if (order.getPhone()!=null ){
            if (order.getPhone().length()>11){
                order.setPhone(PhoneUtil.decryptPhoneMk(order.getPhone()));
            }else {
                order.setPhone(order.getPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
            }

        }
        if (order.getUserPhone()!=null){
            if (order.getUserPhone().length()>11){
                order.setUserPhone(PhoneUtil.decryptPhoneMk(order.getUserPhone()));
            }else {
                order.setUserPhone(order.getUserPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
            }


        }
        if (order.getUserAddress()!=null){
            order.setUserAddress(order.getUserAddress().substring(0, order.getUserAddress().length() / 2) + "********");

        }
        return AjaxResult.success(order);
    }

    @GetMapping(value = "/query/{orderId}")
    @PreAuthorize("@ss.hasPermi('store:storeOrder:queryAddress')")
    public R getAddress(@PathVariable("orderId") Long orderId)
    {
        FsStoreOrderVO order = fsStoreOrderService.selectFsStoreOrderByOrderIdVO(orderId);
        String address = order.getUserAddress();
        return R.ok().put("address",address);
    }

    @GetMapping(value = "/queryPhone/{orderId}")
    @PreAuthorize("@ss.hasPermi('store:storeOrder:queryPhone')")
    @Log(title = "查看电话", businessType = BusinessType.GRANT)
    public R getPhone(@PathVariable("orderId") Long orderId)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser.getUser().getUserType().equals("00")){
            FsStoreOrderVO order = fsStoreOrderService.selectFsStoreOrderByOrderIdVO(orderId);
            if (order.getUserPhone().length()>11){

                return R.ok().put("userPhone",PhoneUtil.decryptPhone(order.getUserPhone()));
            }else {
                return R.ok().put("userPhone",order.getUserPhone());
            }


        }
        return R.error("无权查看");
    }

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

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

    /**
     * 发货
     */
    @PreAuthorize("@ss.hasPermi('his:storeOrder:sendGoods')")
    @PutMapping("/sendGoods")
    public AjaxResult sendGoods(@RequestBody FsStoreOrder fsStoreOrder)
    {
        return toAjax(fsStoreOrderService.sendGoods(fsStoreOrder));
    }

    @PutMapping("/bindCustomer")
    public R bindCustomer(@RequestBody FsStoreOrderBindCustomerParam param)
    {
        if(param.getCustomerIds().length>1){
            return R.error("只能关联一个客户");
        }
        for(Long customerId:param.getCustomerIds()){
            FsStoreOrder order=new FsStoreOrder();
            order.setOrderId(param.getOrderId());
            order.setCustomerId(customerId);
            fsStoreOrderService.updateFsStoreOrder(order);
            //更新CRM客户订单数
            crmCustomerService.updateBuyCount(customerId);
        }
        return R.ok();
    }


    /**
     * 推送到智慧药房
     */
    @PreAuthorize("@ss.hasPermi('his:storeOrder:sendGoods')")
    @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)
    {
        FsStoreOrder order = fsStoreOrderService.selectFsStoreOrderByOrderId(fsStoreOrder.getOrderId());
        if (order.getPayType()==3 && order.getStatus()>2){
            return  AjaxResult.error("货到付款订单，不支持申请售后");
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        fsStoreOrder.setCompanyId(loginUser.getCompany().getCompanyId());
        fsStoreOrder.setOperator(loginUser.getUser().getNickName());
        return toAjax(fsStoreOrderService.afterSales(fsStoreOrder));
    }

    /**
     * 确认收货
     */
    @PreAuthorize("@ss.hasPermi('his:storeOrder:good')")
    @PutMapping("/getGoods")
    @RepeatSubmit
    public AjaxResult getGoods(@RequestBody FsStoreOrder fsStoreOrder)
    {
        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<FsStoreOrderVO> list = fsStoreOrderService.selectFsStoreOrderCusListVO(param);
        if (list != null) {
            for (FsStoreOrderVO vo : list) {
                if(vo.getPhone()!=null){
                    vo.setPhone(vo.getPhone().replaceAll("(\\d{3})\\d*(\\d{1})", "$1****$2"));

                }
                if (vo.getUserPhone()!=null){
                    vo.setUserPhone(vo.getUserPhone().replaceAll("(\\d{3})\\d*(\\d{1})", "$1****$2"));
                }


            }
        }
        return getDataTable(list);
    }

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

    @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);
    }
    @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("/userOrderList")
    public TableDataInfo userOrderList(FsStoreOrderParam fsStoreOrder)
    {
        startPage();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        fsStoreOrder.setCompanyUserId(loginUser.getUser().getUserId());
        fsStoreOrder.setCompanyId(loginUser.getCompany().getCompanyId());
        List<FsStoreOrderListVO> list = fsStoreOrderService.selectFsStoreOrderListVO(fsStoreOrder);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('store:storeOrder:msgList')")
    @GetMapping("/msgList")
    public TableDataInfo msgList(FsFollowMsgParam fsFollowMsgParam)
    {
        startPage();
        List<FsInquiryOrderMsg> list = fsStoreOrderService.selectFsInquiryOrderMsgByStoreOrderId(fsFollowMsgParam);
        return getDataTable(list);
    }


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

}
