商城测试版v8_1

This commit is contained in:
czm 2022-07-30 17:11:42 +08:00
parent e2b0b0c52b
commit 09e34ecabe
39 changed files with 3360 additions and 3274 deletions

View File

@ -1,9 +1,14 @@
const path = require('path') const path = require('path')
const childProcess = require('child_process'); const childProcess = require('child_process')
const versions = childProcess.execSync('git rev-parse --abbrev-ref HEAD', { 'encoding': 'utf8' }) != "HEAD\n" ? childProcess.execSync('git rev-parse --abbrev-ref HEAD', { 'encoding': 'utf8' }) : childProcess.execSync('git describe --tags --abbrev=0', { 'encoding': 'utf8' }) const versions =
const CURRENT_GITHASH = childProcess.execSync('git rev-parse --short HEAD', { 'encoding': 'utf8' }) childProcess.execSync('git rev-parse --abbrev-ref HEAD', { encoding: 'utf8' }) != 'HEAD\n'
const CURRENT_VERSION = `Version: ${JSON.stringify(process.env.CODE_BRANCH || versions)} ${CURRENT_GITHASH} ${new Date().toLocaleString()}`.replace(/\"|\\n/g, ''); ? childProcess.execSync('git rev-parse --abbrev-ref HEAD', { encoding: 'utf8' })
: childProcess.execSync('git describe --tags --abbrev=0', { encoding: 'utf8' })
const CURRENT_GITHASH = childProcess.execSync('git rev-parse --short HEAD', { encoding: 'utf8' })
const CURRENT_VERSION = `Version: ${JSON.stringify(process.env.CODE_BRANCH || versions)} ${CURRENT_GITHASH} ${new Date().toLocaleString()}`.replace(
/\"|\\n/g,
'',
)
const config = { const config = {
projectName: 'EShop', projectName: 'EShop',
@ -12,7 +17,7 @@ const config = {
deviceRatio: { deviceRatio: {
640: 2.34 / 2, 640: 2.34 / 2,
750: 1, 750: 1,
828: 1.81 / 2 828: 1.81 / 2,
}, },
sourceRoot: 'src', sourceRoot: 'src',
outputRoot: 'dist', outputRoot: 'dist',
@ -20,37 +25,33 @@ const config = {
defineConstants: { defineConstants: {
CURRENT_VERSION: JSON.stringify(CURRENT_VERSION), CURRENT_VERSION: JSON.stringify(CURRENT_VERSION),
CURRENT_GITHASH: JSON.stringify(CURRENT_GITHASH), CURRENT_GITHASH: JSON.stringify(CURRENT_GITHASH),
CURRENT_ENV: JSON.stringify(process.env.NODE_ENV) CURRENT_ENV: JSON.stringify(process.env.NODE_ENV),
}, },
copy: { copy: {
patterns: [ patterns: [],
], options: {},
options: {
}
}, },
framework: 'react', framework: 'react',
mini: { mini: {
postcss: { postcss: {
pxtransform: { pxtransform: {
enable: true, enable: true,
config: { config: {},
}
}, },
url: { url: {
enable: true, enable: true,
config: { config: {
limit: 1024 // 设定转换尺寸上限 limit: 1024, // 设定转换尺寸上限
} },
}, },
cssModules: { cssModules: {
enable: true, // 默认为 false如需使用 css modules 功能,则设为 true enable: true, // 默认为 false如需使用 css modules 功能,则设为 true
config: { config: {
namingPattern: 'module', // 转换模式,取值为 global/module namingPattern: 'module', // 转换模式,取值为 global/module
generateScopedName: '[name]__[local]___[hash:base64:5]' generateScopedName: '[name]__[local]___[hash:base64:5]',
} },
} },
} },
}, },
h5: { h5: {
publicPath: '/', publicPath: '/',
@ -58,23 +59,25 @@ const config = {
postcss: { postcss: {
autoprefixer: { autoprefixer: {
enable: true, enable: true,
config: { config: {},
}
}, },
cssModules: { cssModules: {
enable: false, // 默认为 false如需使用 css modules 功能,则设为 true enable: false, // 默认为 false如需使用 css modules 功能,则设为 true
config: { config: {
namingPattern: 'module', // 转换模式,取值为 global/module namingPattern: 'module', // 转换模式,取值为 global/module
generateScopedName: '[name]__[local]___[hash:base64:5]' generateScopedName: '[name]__[local]___[hash:base64:5]',
} },
} },
} },
} },
} }
module.exports = function (merge) { module.exports = function (merge) {
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
return merge({}, config, require('./dev')) return merge({}, config, require('./dev'))
} }
if (process.env.NODE_ENV === 'pre') {
return merge({}, config, require('./pre'))
}
return merge({}, config, require('./prod')) return merge({}, config, require('./prod'))
} }

51
config/pre.js Normal file
View File

@ -0,0 +1,51 @@
const path = require('path')
module.exports = {
env: {
NODE_ENV: '"pre"',
},
outputRoot: 'pre_dis',
defineConstants: {},
mini: {
optimizeMainPackage: {
enable: true,
},
webpackChain: (chain, webpack) => {
chain.merge({
plugin: {
install: {
plugin: require('terser-webpack-plugin'),
args: [
{
terserOptions: {
// compress: true, // 默认使用terser压缩
compress: {
drop_console: true, // 去掉打印
}, // 默认使用terser压缩
// mangle: false,
keep_classnames: true, // 不改变class名称
keep_fnames: true, // 不改变函数名称
},
},
],
},
},
})
},
},
h5: {
/**
* 如果h5端编译后体积过大可以使用webpack-bundle-analyzer插件对打包体积进行分析
* 参考代码如下
* webpackChain (chain) {
* chain.plugin('analyzer')
* .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin, [])
* }
*/
},
alias: {
'@': path.resolve(__dirname, '..', 'src'),
},
sass: {
resource: path.resolve(__dirname, '..', 'src/styles/common.scss'),
},
}

View File

@ -1,20 +1,20 @@
const path = require('path') const path = require('path')
module.exports = { module.exports = {
env: { env: {
NODE_ENV: '"production"' NODE_ENV: '"production"',
},
defineConstants: {
}, },
defineConstants: {},
mini: { mini: {
optimizeMainPackage: { optimizeMainPackage: {
enable: true enable: true,
}, },
webpackChain: (chain, webpack) => { webpackChain: (chain, webpack) => {
chain.merge({ chain.merge({
plugin: { plugin: {
install: { install: {
plugin: require('terser-webpack-plugin'), plugin: require('terser-webpack-plugin'),
args: [{ args: [
{
terserOptions: { terserOptions: {
// compress: true, // 默认使用terser压缩 // compress: true, // 默认使用terser压缩
compress: { compress: {
@ -22,14 +22,14 @@ module.exports = {
}, // 默认使用terser压缩 }, // 默认使用terser压缩
// mangle: false, // mangle: false,
keep_classnames: true, // 不改变class名称 keep_classnames: true, // 不改变class名称
keep_fnames: true // 不改变函数名称 keep_fnames: true, // 不改变函数名称
} },
}] },
} ],
} },
},
}) })
} },
}, },
h5: { h5: {
/** /**
@ -45,6 +45,6 @@ module.exports = {
'@': path.resolve(__dirname, '..', 'src'), '@': path.resolve(__dirname, '..', 'src'),
}, },
sass: { sass: {
resource: path.resolve(__dirname, '..', 'src/styles/common.scss') resource: path.resolve(__dirname, '..', 'src/styles/common.scss'),
} },
} }

View File

@ -1,13 +1,13 @@
import { useRequest } from "@/use/useHttp" import { useRequest } from '@/use/useHttp'
/** /**
* *
* @returns * @returns
*/ */
export const addressListApi = () => { export const addressListApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/address/list`, url: `/v1/mall/address/list`,
method: "get", method: 'get',
}) })
} }
@ -15,10 +15,10 @@ import { useRequest } from "@/use/useHttp"
* *
* @returns * @returns
*/ */
export const addressAddApi = () => { export const addressAddApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/address`, url: `/v1/mall/address`,
method: "post", method: 'post',
}) })
} }
@ -26,10 +26,10 @@ import { useRequest } from "@/use/useHttp"
* *
* @returns * @returns
*/ */
export const addressDetailApi = () => { export const addressDetailApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/address`, url: `/v1/mall/address`,
method: "get", method: 'get',
}) })
} }
@ -37,10 +37,10 @@ import { useRequest } from "@/use/useHttp"
* *
* @returns * @returns
*/ */
export const addressEditApi = () => { export const addressEditApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/address`, url: `/v1/mall/address`,
method: "put", method: 'put',
}) })
} }
@ -48,9 +48,9 @@ import { useRequest } from "@/use/useHttp"
* *
* @returns * @returns
*/ */
export const addressDeleteApi = () => { export const addressDeleteApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/address`, url: `/v1/mall/address`,
method: "delete", method: 'delete',
}) })
} }

View File

@ -1,12 +1,12 @@
import { useRequest } from "@/use/useHttp" import { useRequest } from '@/use/useHttp'
/** /**
* *
* @returns * @returns
*/ */
export const GetBannerList = () => { export const GetBannerList = () => {
return useRequest({ return useRequest({
url: `/v1/mall/carouselBanner/list`, url: `/v1/mall/carouselBanner/list`,
method: "get", method: 'get',
}) })
} }

View File

@ -1,13 +1,12 @@
import { useRequest } from "@/use/useHttp" import { useRequest } from '@/use/useHttp'
/** /**
* cdn / * cdn /
* @returns * @returns
*/ */
export const GetSignApi = () => { export const GetSignApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/cdn/token`, url: `/v1/mall/cdn/token`,
method: "get" method: 'get',
}) })
} }

View File

@ -1,13 +1,13 @@
import { useRequest } from "@/use/useHttp" import { useRequest } from '@/use/useHttp'
/** /**
* *
* @returns * @returns
*/ */
export const companyDetailApi = () => { export const companyDetailApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/company/info`, url: `/v1/mall/company/info`,
method: "get", method: 'get',
}) })
} }
@ -15,9 +15,9 @@ import { useRequest } from "@/use/useHttp"
* *
* @returns * @returns
*/ */
export const companyUpdateApi = () => { export const companyUpdateApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/company/info`, url: `/v1/mall/company/info`,
method: "put", method: 'put',
}) })
} }

View File

@ -1,13 +1,13 @@
import { useRequest } from "@/use/useHttp" import { useRequest } from '@/use/useHttp'
/** /**
* *
* @returns * @returns
*/ */
export const creditInfoApi = () => { export const creditInfoApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/credit`, url: `/v1/mall/credit`,
method: "get", method: 'get',
}) })
} }
@ -15,9 +15,9 @@ import { useRequest } from "@/use/useHttp"
* *
* @returns * @returns
*/ */
export const creditListApi = () => { export const creditListApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/credit/list`, url: `/v1/mall/credit/list`,
method: "get", method: 'get',
}) })
} }

View File

@ -1,13 +1,13 @@
import { useRequest } from "@/use/useHttp" import { useRequest } from '@/use/useHttp'
/** /**
* *
* @returns * @returns
*/ */
export const depositInfoApi = () => { export const depositInfoApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/rechargeApplication`, url: `/v1/mall/rechargeApplication`,
method: "get", method: 'get',
}) })
} }
@ -15,10 +15,10 @@ import { useRequest } from "@/use/useHttp"
* *
* @returns * @returns
*/ */
export const depositListApi = () => { export const depositListApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/rechargeApplication/list`, url: `/v1/mall/rechargeApplication/list`,
method: "get", method: 'get',
}) })
} }
@ -26,9 +26,9 @@ import { useRequest } from "@/use/useHttp"
* *
* @returns * @returns
*/ */
export const depositDetailApi = () => { export const depositDetailApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/rechargeApplication/order`, url: `/v1/mall/rechargeApplication/order`,
method: "get", method: 'get',
}) })
} }

View File

@ -1,91 +1,89 @@
import { useRequest } from "@/use/useHttp" import { useRequest } from '@/use/useHttp'
/** /**
* *
* @returns * @returns
*/ */
export const FavoriteListApi = () => { export const FavoriteListApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/favorite/list`, url: `/v1/mall/favorite/list`,
method: "get", method: 'get',
}) })
} }
/** /**
* *
* @returns * @returns
*/ */
export const CreateFavoriteApi = () => { export const CreateFavoriteApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/favorite`, url: `/v1/mall/favorite`,
method: "post", method: 'post',
}) })
} }
/** /**
* *
* @returns * @returns
*/ */
export const DelFavoriteApi = () => { export const DelFavoriteApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/favorite`, url: `/v1/mall/favorite`,
method: "delete", method: 'delete',
}) })
} }
/** /**
* *
* @returns * @returns
*/ */
export const UpdateFavoriteApi = () => { export const UpdateFavoriteApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/favorite`, url: `/v1/mall/favorite`,
method: "put", method: 'put',
}) })
} }
/** /**
* *
* @returns * @returns
*/ */
export const AddFavoriteApi = () => { export const AddFavoriteApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/favorite/product`, url: `/v1/mall/favorite/product`,
method: "post", method: 'post',
}) })
} }
/** /**
* *
* @returns * @returns
*/ */
export const DelFavoriteProductApi = () => { export const DelFavoriteProductApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/favorite/product`, url: `/v1/mall/favorite/product`,
method: "delete", method: 'delete',
}) })
} }
/** /**
* *
* @returns * @returns
*/ */
export const DetailFavoriteProductApi = () => { export const DetailFavoriteProductApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/favorite`, url: `/v1/mall/favorite`,
method: "get", method: 'get',
}) })
} }
/** /**
* *
* @returns * @returns
*/ */
export const MoveFavoriteProductApi = () => { export const MoveFavoriteProductApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/favorite/product`, url: `/v1/mall/favorite/product`,
method: "put", method: 'put',
}) })
} }

View File

@ -1,12 +1,12 @@
import { useRequest } from "@/use/useHttp" import { useRequest } from '@/use/useHttp'
/** /**
* *
* @returns * @returns
*/ */
export const LoginApi = () => { export const LoginApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/login`, url: `/v1/mall/login`,
method: "post", method: 'post',
}) })
} }

View File

@ -1,4 +1,4 @@
import { useRequest } from "@/use/useHttp" import { useRequest } from '@/use/useHttp'
/** /**
* *
@ -6,78 +6,77 @@ import { useRequest } from "@/use/useHttp"
export const SaleOrderApi = () => { export const SaleOrderApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/saleOrder`, url: `/v1/mall/saleOrder`,
method: "post", method: 'post',
}) })
} }
/** /**
* *
*/ */
export const SaleOrderPreViewApi = () => { export const SaleOrderPreViewApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/saleOrder/preView`, url: `/v1/mall/saleOrder/preView`,
method: "put", method: 'put',
}) })
} }
/** /**
* *
*/ */
export const GetSaleOrderDetailApi = () => { export const GetSaleOrderDetailApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/saleOrder/detail`, url: `/v1/mall/saleOrder/detail`,
method: "get", method: 'get',
}) })
} }
/** /**
* *
*/ */
export const EditSaleOrderRemarkApi = () => { export const EditSaleOrderRemarkApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/saleOrder/remark`, url: `/v1/mall/saleOrder/remark`,
method: "put", method: 'put',
}) })
} }
/** /**
* *
*/ */
export const EditSaleOrderAddressApi = () => { export const EditSaleOrderAddressApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/saleOrder/address`, url: `/v1/mall/saleOrder/address`,
method: "put", method: 'put',
}) })
} }
/** /**
* *
*/ */
export const EditSaleOrderShipmentModeApi = () => { export const EditSaleOrderShipmentModeApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/saleOrder/shipmentMode`, url: `/v1/mall/saleOrder/shipmentMode`,
method: "put", method: 'put',
}) })
} }
/** /**
* *
*/ */
export const GetOrderStatusListApi = () => { export const GetOrderStatusListApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/enum/sale/order/status`, url: `/v1/mall/enum/sale/order/status`,
method: "get", method: 'get',
}) })
} }
/** /**
* *
*/ */
export const GetOrderListApi = () => { export const GetOrderListApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/saleOrder/list`, url: `/v1/mall/saleOrder/list`,
method: "get", method: 'get',
}) })
} }
@ -87,7 +86,7 @@ export const SaleOrderApi = () => {
export const CancelOrderApi = () => { export const CancelOrderApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/saleOrder/cancel`, url: `/v1/mall/saleOrder/cancel`,
method: "put", method: 'put',
}) })
} }
@ -97,16 +96,16 @@ export const CancelOrderApi = () => {
export const ReceiveOrderApi = () => { export const ReceiveOrderApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/saleOrder/receive`, url: `/v1/mall/saleOrder/receive`,
method: "put", method: 'put',
}) })
} }
/** /**
* *
*/ */
export const OrderStatusListApi = () => { export const OrderStatusListApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/enum/filterSaleOrderStatus`, url: `/v1/mall/enum/filterSaleOrderStatus`,
method: "get", method: 'get',
}) })
} }

View File

@ -1,41 +1,41 @@
import { useRequest } from "@/use/useHttp" import { useRequest } from '@/use/useHttp'
/** /**
* *
*/ */
export const GetOrderPayApi = () => { export const GetOrderPayApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/orderPayment/orderPaymentMethodInfo`, url: `/v1/mall/orderPayment/orderPaymentMethodInfo`,
method: "get", method: 'get',
}) })
} }
/** /**
* *
*/ */
export const SubmitOrderPayApi = () => { export const SubmitOrderPayApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/orderPayment/orderPaymentSubmission`, url: `/v1/mall/orderPayment/orderPaymentSubmission`,
method: "put", method: 'put',
}) })
} }
/** /**
* *
*/ */
export const GetPrepayOrderPayApi = () => { export const GetPrepayOrderPayApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/orderPayment/preCollectOrder/orderPaymentMethodInfo`, url: `/v1/mall/orderPayment/preCollectOrder/orderPaymentMethodInfo`,
method: "get", method: 'get',
}) })
} }
/** /**
* *
*/ */
export const SubmitPrepayOrderPayApi = () => { export const SubmitPrepayOrderPayApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/orderPayment/preCollectOrder/orderPaymentSubmission`, url: `/v1/mall/orderPayment/preCollectOrder/orderPaymentSubmission`,
method: "put", method: 'put',
}) })
} }

View File

@ -1,45 +1,45 @@
import { useRequest } from "@/use/useHttp" import { useRequest } from '@/use/useHttp'
/** /**
* *
* @returns * @returns
*/ */
export const GetShoppingCartApi = () => { export const GetShoppingCartApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/shoppingCart/productColor`, url: `/v1/mall/shoppingCart/productColor`,
method: "get", method: 'get',
}) })
} }
/** /**
* *
* @returns * @returns
*/ */
export const AddShoppingCartApi = () => { export const AddShoppingCartApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/shoppingCart/productColor/list`, url: `/v1/mall/shoppingCart/productColor/list`,
method: "post", method: 'post',
}) })
} }
/** /**
* *
* @returns * @returns
*/ */
export const DelShoppingCartApi = () => { export const DelShoppingCartApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/shoppingCart/productColor`, url: `/v1/mall/shoppingCart/productColor`,
method: "delete", method: 'delete',
}) })
} }
/** /**
* *
* @returns * @returns
*/ */
export const UpdateShoppingCartApi = () => { export const UpdateShoppingCartApi = () => {
return useRequest({ return useRequest({
url: `/v1/mall/shoppingCart/productColor`, url: `/v1/mall/shoppingCart/productColor`,
method: "put", method: 'put',
}) })
} }

View File

@ -21,15 +21,11 @@ export const UPLOAD_CDN_URL = `https://v0.api.upyun.com/`
// cdn // cdn
// export const IMG_CND_Prefix = CURRENT_ENV.includes('development')? "https://test.cdn.zzfzyc.com":"https://cdn.zzfzyc.com" // export const IMG_CND_Prefix = CURRENT_ENV.includes('development')? "https://test.cdn.zzfzyc.com":"https://cdn.zzfzyc.com"
export const IMG_CND_Prefix = CURRENT_ENV.includes('development') export const IMG_CND_Prefix = CURRENT_ENV.includes('development') ? 'https://test.cdn.zzfzyc.com' : 'https://test.cdn.zzfzyc.com'
? 'https://test.cdn.zzfzyc.com'
: 'https://test.cdn.zzfzyc.com'
//在线支付图片baseUrl //在线支付图片baseUrl
// export const CAP_HTML_TO_IMAGE_BASE_URL = CURRENT_ENV.includes('development')? "https://test.zzfzyc.com":"https://www.zzfzyc.com" // export const CAP_HTML_TO_IMAGE_BASE_URL = CURRENT_ENV.includes('development')? "https://test.zzfzyc.com":"https://www.zzfzyc.com"
export const CAP_HTML_TO_IMAGE_BASE_URL = CURRENT_ENV.includes('development') export const CAP_HTML_TO_IMAGE_BASE_URL = CURRENT_ENV.includes('development') ? 'https://test.zzfzyc.com' : 'https://test.zzfzyc.com'
? 'https://test.zzfzyc.com'
: 'https://test.zzfzyc.com'
// 上传图片视频 // 上传图片视频
export const CDN_UPLOAD_IMG = `${UPLOAD_CDN_URL || ''}` export const CDN_UPLOAD_IMG = `${UPLOAD_CDN_URL || ''}`

View File

@ -1,18 +1,16 @@
.labAndImg_main {
.labAndImg_main{
width: 100%; width: 100%;
height: 100%; height: 100%;
.boxColor{ .boxColor {
width: 100%; width: 100%;
height: 100%; height: 100%;
border-radius: 20px; border-radius: 20px;
border:1PX solid #818181; border: 1px solid #818181;
box-sizing: border-box; box-sizing: border-box;
} }
image{ .labAndImg_image {
width: 100%; width: 100%;
height: 100%; height: 100%;
border-radius: 20px; border-radius: 20px !important;
} }
} }

View File

@ -1,37 +1,37 @@
import { formatImgUrl, formatRemoveHashTag } from "@/common/fotmat"; import { formatImgUrl, formatRemoveHashTag } from '@/common/fotmat'
import Preview from "@/pages/details/components/preview"; import Preview from '@/pages/details/components/preview'
import { Image, View } from "@tarojs/components"; import { Image, View } from '@tarojs/components'
import { memo, useCallback, useEffect, useMemo, useState } from "react"; import { memo, useCallback, useEffect, useMemo, useState } from 'react'
import styles from './index.module.scss' import styles from './index.module.scss'
import Taro from "@tarojs/taro"; import Taro from '@tarojs/taro'
import LabAndImgShow from "../LabAndImgShow"; import LabAndImgShow from '../LabAndImgShow'
//该组件宽高为100%需调整外层元素宽高 //该组件宽高为100%需调整外层元素宽高
type Param = { type Param = {
value?: { value?: {
texture_url?: string, //纹理图路径 texture_url?: string //纹理图路径
lab?: {l:number, a:number, b:number}, //lab lab?: { l: number; a: number; b: number } //lab
rgb?: {r:number, g:number, b:number} //rgb rgb?: { r: number; g: number; b: number } //rgb
title?: string title?: string
}, }
showStatus?: true|false, showStatus?: true | false
onClick?: (val: Param['value']) => void onClick?: (val: Param['value']) => void
} }
export default memo(({value, onClick, showStatus = false}:Param) => { export default memo(({ value, onClick, showStatus = false }: Param) => {
const [imgs, setImgs] = useState<string[]>([]) const [imgs, setImgs] = useState<string[]>([])
//lab是否都是0 //lab是否都是0
const rgbStyle = useMemo(() => { const rgbStyle = useMemo(() => {
if(value?.lab&&(value.lab.l||value.lab.a||value.lab.b)) { if (value?.lab && (value.lab.l || value.lab.a || value.lab.b)) {
return {'backgroundColor':`rgb(${value.rgb?.r} ${value.rgb?.g} ${value.rgb?.b})`} return { backgroundColor: `rgb(${value.rgb?.r} ${value.rgb?.g} ${value.rgb?.b})` }
} else { } else {
return null return null
} }
}, [value]) }, [value])
useEffect(() => { useEffect(() => {
if(value?.texture_url) { if (value?.texture_url) {
let res = value.texture_url.split(',').map(item => { let res = value.texture_url.split(',').map((item) => {
return formatImgUrl(item) return formatImgUrl(item)
}) })
setImgs(() => res) setImgs(() => res)
@ -44,19 +44,18 @@ export default memo(({value, onClick, showStatus = false}:Param) => {
}, []) }, [])
const onShowLabAndImg = () => { const onShowLabAndImg = () => {
onClick?.(value) onClick?.(value)
if(!showStatus) return false if (!showStatus) return false
setLabAndImgShow(true) setLabAndImgShow(true)
} }
return ( return (
<> <>
<View className={styles.labAndImg_main} onClick={() => onShowLabAndImg()}> <View className={styles.labAndImg_main} onClick={() => onShowLabAndImg()}>
{imgs?.length > 0&&<Image mode="aspectFill" src={imgs[0]}></Image>} {imgs?.length > 0 && <Image mode='aspectFill' src={imgs[0]} className={styles.labAndImg_image}></Image>}
{(!imgs?.length&&rgbStyle)&&<View className={styles.boxColor} style={{...rgbStyle}}></View>} {!imgs?.length && rgbStyle && <View className={styles.boxColor} style={{ ...rgbStyle }}></View>}
{(!imgs?.length&&!rgbStyle)&&<Image mode="aspectFill" src={formatImgUrl('')}></Image>} {!imgs?.length && !rgbStyle && <Image mode='aspectFill' src={formatImgUrl('')} className={styles.labAndImg_image}></Image>}
</View> </View>
<LabAndImgShow value={value} show={labAndImgShow} onClose={closeLabAndImgShow}/> <LabAndImgShow value={value} show={labAndImgShow} onClose={closeLabAndImgShow} />
</> </>
) )
}) })

View File

@ -1,35 +1,34 @@
import { GetAddressListApi } from "@/api/addressList"; import { GetAddressListApi } from '@/api/addressList'
import { addressListApi } from "@/api/addressManager"; import { addressListApi } from '@/api/addressManager'
import { EditSaleOrderAddressApi, EditSaleOrderShipmentModeApi } from "@/api/order"; import { EditSaleOrderAddressApi, EditSaleOrderShipmentModeApi } from '@/api/order'
import { alert, goLink } from "@/common/common"; import { alert, goLink } from '@/common/common'
import { ORDER_STATUS } from "@/common/enum"; import { ORDER_STATUS } from '@/common/enum'
import { debounce, throttle } from "@/common/util"; import { debounce, throttle } from '@/common/util'
import AddressList from "@/components/AddressList"; import AddressList from '@/components/AddressList'
import Popup from "@/components/popup"; import Popup from '@/components/popup'
import { Text, View } from "@tarojs/components" import { Text, View } from '@tarojs/components'
import classnames from "classnames"; import classnames from 'classnames'
import { forwardRef, memo, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react"; import { forwardRef, memo, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react'
import Taro from "@tarojs/taro"; import Taro from '@tarojs/taro'
import styles from './index.module.scss' import styles from './index.module.scss'
type Param = { type Param = {
onSelect?: (val:any) => void, //选择地址 onSelect?: (val: any) => void //选择地址
disabled?: false|true, //true禁用后只用于展示 disabled?: false | true //true禁用后只用于展示
onChangeShipmentMode?: (val: number) => void, //返回收货方式 onChangeShipmentMode?: (val: number) => void //返回收货方式
onLogistics?: () => void, //查看物流 onLogistics?: () => void //查看物流
status?: 1|2, //1确认订单时使用 2订单流程 status?: 1 | 2 //1确认订单时使用 2订单流程
orderInfo?: { orderInfo?: {
id?: number //订单id id?: number //订单id
shipment_mode?: 1|2, //1自提 2物流 shipment_mode?: 1 | 2 //1自提 2物流
status?: number //订单状态 status?: number //订单状态
province_name: string, province_name: string
city_name: string, city_name: string
district_name: string, district_name: string
address_detail: string, address_detail: string
take_goods_address: string, take_goods_address: string
take_goods_phone: string, take_goods_phone: string
target_user_name: string, target_user_name: string
target_user_phone: string target_user_phone: string
} }
} }
@ -48,12 +47,12 @@ const {
SaleOrderStatusCancel, SaleOrderStatusCancel,
} = ORDER_STATUS } = ORDER_STATUS
export default memo(forwardRef(({onSelect, onChangeShipmentMode, orderInfo, status = 2, disabled = false, onLogistics}: Param, ref) => { export default memo(
forwardRef(({ onSelect, onChangeShipmentMode, orderInfo, status = 2, disabled = false, onLogistics }: Param, ref) => {
const [addressInfo, setAddressInfo] = useState<any>() const [addressInfo, setAddressInfo] = useState<any>()
useEffect(() => { useEffect(() => {
if(orderInfo) { if (orderInfo) {
setReceivingStatus(() => orderInfo.shipment_mode||2) setReceivingStatus(() => orderInfo.shipment_mode || 2)
setAddressInfo(() => orderInfo) setAddressInfo(() => orderInfo)
} }
}, [orderInfo]) }, [orderInfo])
@ -61,33 +60,31 @@ export default memo(forwardRef(({onSelect, onChangeShipmentMode, orderInfo, stat
//打开地址列表 //打开地址列表
const [showAddressList, setShowAddressList] = useState(false) const [showAddressList, setShowAddressList] = useState(false)
const changeShow = () => { const changeShow = () => {
if(receivingStatus == 2 && !logisticsShow && limitEdit()) if (receivingStatus == 2 && !logisticsShow && limitEdit()) setShowAddressList(() => true)
setShowAddressList(() => true)
} }
//把内部方法提供给外部 //把内部方法提供给外部
useImperativeHandle(ref, () => ({ useImperativeHandle(ref, () => ({
changeShow changeShow,
})) }))
//收货方法,1:自提2物流 //收货方法,1:自提2物流
const [receivingStatus, setReceivingStatus] = useState(2) const [receivingStatus, setReceivingStatus] = useState(2)
const {fetchData: shipmentModeFetchData} = EditSaleOrderShipmentModeApi() const { fetchData: shipmentModeFetchData } = EditSaleOrderShipmentModeApi()
const onReceivingStatus = async (value, e) => { const onReceivingStatus = async (value, e) => {
e.stopPropagation() e.stopPropagation()
if(limitEdit()) changeReceivingStatus(value) if (limitEdit()) changeReceivingStatus(value)
} }
//当没有地址时获取地址列表中的第一个数据 //当没有地址时获取地址列表中的第一个数据
const {fetchData: addressListFetchData} = addressListApi() const { fetchData: addressListFetchData } = addressListApi()
const getAddressListOne = async () => { const getAddressListOne = async () => {
if(orderInfo?.address_detail) return true if (orderInfo?.address_detail) return true
let res = await addressListFetchData() let res = await addressListFetchData()
if( res.data.list && res.data.list?.length > 0 ) { if (res.data.list && res.data.list?.length > 0) {
let info = res.data.list[0] let info = res.data.list[0]
await addressFetchData({id: orderInfo?.id, address_id: info.id}) await addressFetchData({ id: orderInfo?.id, address_id: info.id })
setAddressInfo((e) => ({...e, ...info, target_user_name: info.name, target_user_phone: info.phone})) setAddressInfo((e) => ({ ...e, ...info, target_user_name: info.name, target_user_phone: info.phone }))
return true return true
} else { } else {
Taro.showModal({ Taro.showModal({
@ -98,28 +95,26 @@ export default memo(forwardRef(({onSelect, onChangeShipmentMode, orderInfo, stat
} else if (res.cancel) { } else if (res.cancel) {
console.log('用户点击取消') console.log('用户点击取消')
} }
} },
}) })
return false return false
} }
} }
const changeReceivingStatus = debounce(async (value) => { const changeReceivingStatus = debounce(async (value) => {
if(!orderInfo || value == receivingStatus) return false if (!orderInfo || value == receivingStatus) return false
if(status == 1) { if (status == 1) {
onChangeShipmentMode?.(value) onChangeShipmentMode?.(value)
setReceivingStatus(value) setReceivingStatus(value)
return false return false
} }
if(value == 2) { if (value == 2) {
let res = await getAddressListOne() let res = await getAddressListOne()
if(!res) return false if (!res) return false
} }
alert.loading('正在修改') alert.loading('正在修改')
const res = await shipmentModeFetchData({id: orderInfo.id, shipment_mode:value}) const res = await shipmentModeFetchData({ id: orderInfo.id, shipment_mode: value })
if(res.success) { if (res.success) {
alert.success('收货方式修改成功') alert.success('收货方式修改成功')
onChangeShipmentMode?.(value) onChangeShipmentMode?.(value)
setReceivingStatus(() => value) setReceivingStatus(() => value)
@ -130,24 +125,24 @@ export default memo(forwardRef(({onSelect, onChangeShipmentMode, orderInfo, stat
//修改地址 //修改地址
const [addressId, setAddressId] = useState(0) const [addressId, setAddressId] = useState(0)
const {fetchData: addressFetchData} = EditSaleOrderAddressApi() const { fetchData: addressFetchData } = EditSaleOrderAddressApi()
const getAddress = async (value) => { const getAddress = async (value) => {
if(!orderInfo) return false if (!orderInfo) return false
if(status == 1) { if (status == 1) {
setShowAddressList(() => false) setShowAddressList(() => false)
setAddressId(value.id) setAddressId(value.id)
setAddressInfo((e) => ({...e, ...value, target_user_name: value.name, target_user_phone: value.phone})) setAddressInfo((e) => ({ ...e, ...value, target_user_name: value.name, target_user_phone: value.phone }))
onSelect?.(value) onSelect?.(value)
return false return false
} }
alert.loading('正在修改') alert.loading('正在修改')
const res = await addressFetchData({id: orderInfo.id, address_id: value.id}) const res = await addressFetchData({ id: orderInfo.id, address_id: value.id })
if(res.success) { if (res.success) {
alert.success('地址修改成功') alert.success('地址修改成功')
onSelect?.(value) onSelect?.(value)
setShowAddressList(() => false) setShowAddressList(() => false)
setAddressId(value.id) setAddressId(value.id)
setAddressInfo((e) => ({...e, ...value, target_user_name: value.name, target_user_phone: value.phone})) setAddressInfo((e) => ({ ...e, ...value, target_user_name: value.name, target_user_phone: value.phone }))
} else { } else {
alert.none(res.msg) alert.none(res.msg)
} }
@ -155,18 +150,13 @@ export default memo(forwardRef(({onSelect, onChangeShipmentMode, orderInfo, stat
//根据订单状态判断是否可修改 //根据订单状态判断是否可修改
const limitEdit = () => { const limitEdit = () => {
let res = [ let res = [SaleorderstatusWaitingPrePayment.value, SaleOrderStatusBooking.value, SaleOrderStatusArranging.value, SaleOrderStatusArranged.value, SaleOrderStatusWaitingPayment.value].includes(
SaleorderstatusWaitingPrePayment.value, orderInfo?.status as number,
SaleOrderStatusBooking.value, )
SaleOrderStatusArranging.value, if (!res && status != 1) alert.none('该订单状态不能修改地址!')
SaleOrderStatusArranged.value, return status == 1 ? true : res
SaleOrderStatusWaitingPayment.value,
].includes(orderInfo?.status as number)
if(!res && status != 1) alert.none('该订单状态不能修改地址!')
return status == 1? true : res
} }
//根据订单状态判断是否显示物流 //根据订单状态判断是否显示物流
const logisticsShowList = [SaleOrderStatusWaitingReceipt.value, SaleOrderStatusAlreadyReceipt.value, SaleOrderStatusComplete.value, SaleOrderStatusRefund.value] const logisticsShowList = [SaleOrderStatusWaitingReceipt.value, SaleOrderStatusAlreadyReceipt.value, SaleOrderStatusComplete.value, SaleOrderStatusRefund.value]
const logisticsShow = useMemo(() => { const logisticsShow = useMemo(() => {
@ -175,8 +165,8 @@ export default memo(forwardRef(({onSelect, onChangeShipmentMode, orderInfo, stat
//地址格式 //地址格式
const formatAddress = useMemo(() => { const formatAddress = useMemo(() => {
if(receivingStatus == 2) { if (receivingStatus == 2) {
return addressInfo?.address_detail?addressInfo.province_name + addressInfo.city_name + addressInfo.district_name + addressInfo.address_detail:'' return addressInfo?.address_detail ? addressInfo.province_name + addressInfo.city_name + addressInfo.district_name + addressInfo.address_detail : ''
} else { } else {
return addressInfo?.take_goods_address return addressInfo?.take_goods_address
} }
@ -185,36 +175,45 @@ export default memo(forwardRef(({onSelect, onChangeShipmentMode, orderInfo, stat
return ( return (
<View> <View>
<View className={styles.order_address} onClick={() => changeShow()}> <View className={styles.order_address} onClick={() => changeShow()}>
<View className={classnames(styles.order_address_icon, 'iconfont', receivingStatus == 2?'icon-daohang':'icon-fahuo')}></View> <View className={classnames(styles.order_address_icon, 'iconfont', receivingStatus == 2 ? 'icon-daohang' : 'icon-fahuo')}></View>
<View className={styles.order_address_text_con}> <View className={styles.order_address_text_con}>
<View className={styles.order_address_text_title}> <View className={styles.order_address_text_title}>
<Text className={classnames(styles.address_text, styles.address_text_no)}>{formatAddress||'请选择收货地址及信息'}</Text> <Text className={classnames(styles.address_text, styles.address_text_no)}>{formatAddress || '请选择收货地址及信息'}</Text>
{(receivingStatus == 2 && !logisticsShow)&&<Text className={classnames(styles.moreIconfont,'iconfont icon-a-moreback')}></Text>} {receivingStatus == 2 && !logisticsShow && <Text className={classnames(styles.moreIconfont, 'iconfont icon-a-moreback')}></Text>}
</View> </View>
<View className={styles.order_address_text_name}> <View className={styles.order_address_text_name}>
<Text>{receivingStatus == 1?'管理员':addressInfo?.target_user_name}</Text> <Text>{receivingStatus == 1 ? '谭先生' : addressInfo?.target_user_name}</Text>
<Text>{receivingStatus == 1?addressInfo?.take_goods_phone: addressInfo?.target_user_phone}</Text> <Text>{receivingStatus == 1 ? addressInfo?.take_goods_phone : addressInfo?.target_user_phone}</Text>
</View> </View>
</View> </View>
{!logisticsShow&&<View className={styles.updateBtn}> {(!logisticsShow && (
<View className={styles.updateBtn}>
<View className={styles.updateBtn_list}> <View className={styles.updateBtn_list}>
<View className={classnames(styles.updateBtn_item, receivingStatus==1&&styles.updateBtn_item_select)} onClick={(e) => onReceivingStatus(1,e)}></View> <View className={classnames(styles.updateBtn_item, receivingStatus == 1 && styles.updateBtn_item_select)} onClick={(e) => onReceivingStatus(1, e)}>
<View className={classnames(styles.updateBtn_item, receivingStatus==2&&styles.updateBtn_item_select)} onClick={(e) => onReceivingStatus(2,e)}></View>
</View> </View>
<View style={{transform: receivingStatus==1?'translateX(0)':'translateX(100%)'}} className={classnames(styles.updateBtn_select)}></View> <View className={classnames(styles.updateBtn_item, receivingStatus == 2 && styles.updateBtn_item_select)} onClick={(e) => onReceivingStatus(2, e)}>
</View>||
(orderInfo?.status != SaleOrderStatusRefund.value)&&<View className={styles.logisticsBtn} onClick={onLogistics}> </View>
</View>
<View style={{ transform: receivingStatus == 1 ? 'translateX(0)' : 'translateX(100%)' }} className={classnames(styles.updateBtn_select)}></View>
</View>
)) ||
(orderInfo?.status != SaleOrderStatusRefund.value && (
<View className={styles.logisticsBtn} onClick={onLogistics}>
</View>} </View>
))}
</View> </View>
<Popup show={showAddressList} showTitle={false} onClose={() => setShowAddressList(false)}> <Popup show={showAddressList} showTitle={false} onClose={() => setShowAddressList(false)}>
<View className={styles.order_address_list}> <View className={styles.order_address_list}>
<View className={styles.order_address_title}></View> <View className={styles.order_address_title}></View>
<View className={styles.addressList_con}> <View className={styles.addressList_con}>
<AddressList onSelect={getAddress} id={addressId}/> <AddressList onSelect={getAddress} id={addressId} />
</View> </View>
</View> </View>
</Popup> </Popup>
</View> </View>
) )
})) }),
)

View File

@ -1,18 +1,17 @@
.apply_after_sales_con {
.apply_after_sales_con{
padding: 20px; padding: 20px;
.returnSaleInput_item{ .returnSaleInput_item {
display: flex; display: flex;
align-items: center; align-items: center;
padding-bottom: 50px; padding-bottom: 50px;
flex-wrap: wrap; flex-wrap: wrap;
.title{ .title {
font-size: $font_size; font-size: $font_size;
font-weight: 700; font-weight: 700;
width: 119px; width: 119px;
} }
.select{ .select {
flex:1; flex: 1;
height: 60px; height: 60px;
border: 2px solid #e6e6e6; border: 2px solid #e6e6e6;
border-radius: 10px; border-radius: 10px;
@ -23,38 +22,40 @@
padding: 0 20px; padding: 0 20px;
font-size: 26px; font-size: 26px;
color: $color_font_two; color: $color_font_two;
.miconfont{ .miconfont {
font-size: 30px; font-size: 30px;
} }
} .selected {
.upload_image{ color: #000;
flex:1;
} }
} }
.btns_con{ .upload_image {
flex: 1;
}
}
.btns_con {
width: 100%; width: 100%;
bottom:0; bottom: 0;
box-sizing: border-box; box-sizing: border-box;
margin-top: 50px; margin-top: 50px;
.btns_two{ .btns_two {
display: flex; display: flex;
height: 82px; height: 82px;
// border: 1PX solid #007aff; // border: 1PX solid #007aff;
font-size: $font_size_big; font-size: $font_size_big;
border-radius: 40px; border-radius: 40px;
margin-bottom: 20px; margin-bottom: 20px;
.rest_btn{ .rest_btn {
flex:1; flex: 1;
border: 1PX solid #007aff; border: 1px solid #007aff;
border-radius: 40px 0 0 40px; border-radius: 40px 0 0 40px;
text-align: center; text-align: center;
line-height: 82px; line-height: 82px;
color: $color_main; color: $color_main;
background-color: #fff; background-color: #fff;
} }
.verify_btn{ .verify_btn {
flex:1; flex: 1;
border-radius: 0 40px 40px 0; border-radius: 0 40px 40px 0;
background: #007aff; background: #007aff;
text-align: center; text-align: center;

View File

@ -1,42 +1,42 @@
import Popup from "@/components/popup"; import Popup from '@/components/popup'
import TextareaEnhance from "@/components/textareaEnhance"; import TextareaEnhance from '@/components/textareaEnhance'
import { ScrollView, Text, View } from "@tarojs/components"; import { ScrollView, Text, View } from '@tarojs/components'
import { memo, useCallback, useEffect, useRef, useState } from "react"; import { memo, useCallback, useEffect, useRef, useState } from 'react'
import ReasonPopup from "../reasonPopup"; import ReasonPopup from '../reasonPopup'
import styles from './index.module.scss' import styles from './index.module.scss'
import classnames from "classnames"; import classnames from 'classnames'
import { ApplyRefundApi, RefundExplainApi } from "@/api/salesAfterOrder"; import { ApplyRefundApi, RefundExplainApi } from '@/api/salesAfterOrder'
import { alert } from "@/common/common"; import { alert } from '@/common/common'
type Param = { type Param = {
show?: true|false, show?: true | false
onClose?: () => void, onClose?: () => void
orderId?: number orderId?: number
onSuccess?: () => void
} }
export default memo(({show, onClose, orderId}:Param) => { export default memo(({ show, onClose, orderId, onSuccess }: Param) => {
//提交的数据 //提交的数据
const submitData = useRef({ const submitData = useRef({
return_explain: 0, return_explain: 0,
sale_order_id: 0, sale_order_id: 0,
reason_describe: '' reason_describe: '',
}) })
useEffect(() => { useEffect(() => {
console.log('show&&orderId::', show) if (show && orderId) {
if(show&&orderId) {
submitData.current.sale_order_id = orderId submitData.current.sale_order_id = orderId
refundExplain() refundExplain()
} }
}, [orderId, show]) }, [orderId, show])
//申请退款 //申请退款
const {fetchData} = ApplyRefundApi() const { fetchData } = ApplyRefundApi()
const getApplyRefund = async () => { const getApplyRefund = async () => {
if(!submitData.current.return_explain) return alert.error('请选择说明原因') if (!submitData.current.return_explain) return alert.error('请选择说明原因')
let res = await fetchData(submitData.current) let res = await fetchData(submitData.current)
if(res.success) { if (res.success) {
alert.error('申请成功') alert.success('申请成功')
onSuccess?.()
} else { } else {
alert.error('申请失败') alert.error('申请失败')
} }
@ -45,67 +45,68 @@ export default memo(({show, onClose, orderId}:Param) => {
//获取说明数据 //获取说明数据
const [list, setList] = useState<any[]>([]) const [list, setList] = useState<any[]>([])
const {fetchData: refundExplainFetchdata} = RefundExplainApi() const { fetchData: refundExplainFetchdata } = RefundExplainApi()
const refundExplain = async () => { const refundExplain = async () => {
let res = await refundExplainFetchdata() let res = await refundExplainFetchdata()
setList(() => res.data.list) setList(() => res.data.list)
} }
const [reason, setReason] = useState({id:0, name:''}) const [reason, setReason] = useState({ id: 0, name: '' })
const reasonSelect = useCallback((e) => { const reasonSelect = useCallback((e) => {
setReason({...reason, name:e.name, id:e.id}) setReason({ ...reason, name: e.name, id: e.id })
submitData.current.return_explain = e.id submitData.current.return_explain = e.id
closeReason() closeReason()
}, []) }, [])
//备注 //备注
const getOtherReason = useCallback((val) => { const getOtherReason = useCallback((val) => {
submitData.current.reason_describe = val submitData.current.reason_describe = val
}, []) }, [])
//显示说明 //显示说明
const [showReason, setShowReason] = useState(false) const [showReason, setShowReason] = useState(false)
const closeReason = useCallback(() => { const closeReason = useCallback(() => {
setShowReason(false) setShowReason(false)
}, []) }, [])
//提交 //提交
const onSubmit = (val) => { const onSubmit = (val) => {
if(val == 2) { if (val == 2) {
getApplyRefund() getApplyRefund()
} else { } else {
onClose?.() onClose?.()
submitData.current = { submitData.current = {
return_explain: 0, return_explain: 0,
sale_order_id: 0, sale_order_id: 0,
reason_describe: '' reason_describe: '',
} }
} }
} }
return ( return (
<> <>
<Popup show={show} title="申请退款" onClose={onClose} > <Popup show={show} title='申请退款' onClose={onClose}>
<View className={styles.apply_after_sales_con}> <View className={styles.apply_after_sales_con}>
<View className={styles.returnSaleInput_item}> <View className={styles.returnSaleInput_item}>
<View className={styles.title}>退</View> <View className={styles.title}>退</View>
<View className={styles.select} onClick={() => setShowReason(true)}> <View className={styles.select} onClick={() => setShowReason(true)}>
<Text>{reason.name||'请选择'}</Text> <Text className={reason.name ? styles.selected : ''}>{reason.name || '请选择'}</Text>
<Text className={classnames(styles.miconfont, 'iconfont icon-a-moreback')}></Text> <Text className={classnames(styles.miconfont, 'iconfont icon-a-moreback')}></Text>
</View> </View>
</View> </View>
<TextareaEnhance onChange={getOtherReason} title='备注' placeholder="请输入退款备注"/> <TextareaEnhance onChange={getOtherReason} title='备注' placeholder='请输入退款备注' />
<View className={styles.btns_con}> <View className={styles.btns_con}>
<View className={styles.btns_two}> <View className={styles.btns_two}>
<View className={styles.rest_btn} onClick={() => onSubmit(1)}></View> <View className={styles.rest_btn} onClick={() => onSubmit(1)}>
<View className={styles.verify_btn } onClick={() => onSubmit(2)}></View>
</View > </View>
<View className={styles.verify_btn} onClick={() => onSubmit(2)}>
</View>
</View>
</View> </View>
</View> </View>
</Popup> </Popup>
<ReasonPopup defaultValue={reason.id} show={showReason} onClose={closeReason} list={list} title="退款说明" onSelect={reasonSelect}/> <ReasonPopup defaultValue={reason.id} show={showReason} onClose={closeReason} list={list} title='退款说明' onSelect={reasonSelect} />
</> </>
) )
}) })

View File

@ -221,6 +221,9 @@ export default () => {
const applyRefundClose = useCallback(() => { const applyRefundClose = useCallback(() => {
setRefundShow(false) setRefundShow(false)
}, []) }, [])
const applyRefundSuccess = useCallback(() => {
getSaleOrderPreView()
}, [])
//查看物流 //查看物流
const getLogistics = useCallback(() => { const getLogistics = useCallback(() => {
@ -281,17 +284,9 @@ export default () => {
return ( return (
<View className={styles.order_main}> <View className={styles.order_main}>
{(orderDetail?.status != SaleorderstatusWaitingPrePayment.value && <OrderState orderInfo={orderDetail} />) || ( {(orderDetail?.status != SaleorderstatusWaitingPrePayment.value && <OrderState orderInfo={orderDetail} />) || <AdvanceOrderState orderInfo={orderDetail} onRefresh={refresh} />}
<AdvanceOrderState orderInfo={orderDetail} onRefresh={refresh} />
)}
<View> <View>
<AddressInfoDetail <AddressInfoDetail orderInfo={defaultAddress} onLogistics={getLogistics} onSelect={getAddress} onChangeShipmentMode={getShipmentMode} ref={addressRef} />
orderInfo={defaultAddress}
onLogistics={getLogistics}
onSelect={getAddress}
onChangeShipmentMode={getShipmentMode}
ref={addressRef}
/>
</View> </View>
<KindList order={formatPreViewOrderMemo} /> <KindList order={formatPreViewOrderMemo} />
<View className={styles.order_info}> <View className={styles.order_info}>
@ -315,9 +310,7 @@ export default () => {
</View> </View>
<View className={styles.order_desc} onClick={descOpen}> <View className={styles.order_desc} onClick={descOpen}>
<View className={styles.order_desc_con}></View> <View className={styles.order_desc_con}></View>
{(orderRemark && <View className={styles.order_desc_text}>{orderDetail?.remark}</View>) || ( {(orderRemark && <View className={styles.order_desc_text}>{orderDetail?.remark}</View>) || <View className={styles.order_desc_text_hint}></View>}
<View className={styles.order_desc_text_hint}></View>
)}
<View className={classnames(styles.miconfont, 'iconfont icon-a-moreback')}></View> <View className={classnames(styles.miconfont, 'iconfont icon-a-moreback')}></View>
</View> </View>
{orderDetail?.status != SaleOrderStatusCancel.value && ( {orderDetail?.status != SaleOrderStatusCancel.value && (
@ -331,7 +324,7 @@ export default () => {
</Popup> </Popup>
<Payment onSubmitSuccess={onPaySuccess} show={payMentShow} onClose={closePayShow} orderInfo={orderDetail} /> <Payment onSubmitSuccess={onPaySuccess} show={payMentShow} onClose={closePayShow} orderInfo={orderDetail} />
<ScanPayCheck show={showScanPayCheck} onClose={() => setShowScanPayCheck(false)} orderInfo={orderDetail} /> <ScanPayCheck show={showScanPayCheck} onClose={() => setShowScanPayCheck(false)} orderInfo={orderDetail} />
<ApplyRefund show={refundShow} onClose={applyRefundClose} orderId={orderDetail?.id} /> <ApplyRefund show={refundShow} onSuccess={applyRefundSuccess} onClose={applyRefundClose} orderId={orderDetail?.id} />
<ShopCart intoStatus='again' show={showCart} onClose={() => setShowCart(false)} /> <ShopCart intoStatus='again' show={showCart} onClose={() => setShowCart(false)} />
<ReturnRecord show={returnRecordShow} onClose={closeReturnRecord} id={orderDetail?.id} /> <ReturnRecord show={returnRecordShow} onClose={closeReturnRecord} id={orderDetail?.id} />
<View className='common_safe_area_y'></View> <View className='common_safe_area_y'></View>

View File

@ -1,62 +1,70 @@
import { goLink } from "@/common/common"; import { goLink } from '@/common/common'
import { ORDER_STATUS } from "@/common/enum"; import { ORDER_STATUS } from '@/common/enum'
import { formatHashTag, formatImgUrl, formatPriceDiv } from "@/common/fotmat"; import { formatHashTag, formatImgUrl, formatPriceDiv } from '@/common/fotmat'
import LabAndImg from "@/components/LabAndImg"; import LabAndImg from '@/components/LabAndImg'
import OrderBtns from "@/components/orderBtns"; import OrderBtns from '@/components/orderBtns'
import Payment from "@/pages/order/components/payment"; import Payment from '@/pages/order/components/payment'
import { useSelector } from "@/reducers/hooks"; import { useSelector } from '@/reducers/hooks'
import { Image, Text, View } from "@tarojs/components" import { Image, Text, View } from '@tarojs/components'
import { useRouter } from "@tarojs/taro"; import { useRouter } from '@tarojs/taro'
import classnames from "classnames"; import classnames from 'classnames'
import { memo, useCallback, useMemo, useRef, useState } from "react"; import { memo, useCallback, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss' import styles from './index.module.scss'
type Param = { type Param = {
value: { value: {
order_no: string, order_no: string
sale_mode: number, sale_mode: number
sale_mode_name: string, sale_mode_name: string
status_name: string, status_name: string
shipment_mode: number, shipment_mode: number
shipment_mode_name: string, shipment_mode_name: string
product_list: any[], product_list: any[]
total_fabrics: number, total_fabrics: number
total_colors: number, total_colors: number
total_number: number, total_number: number
status: 0, status: 0
id: number, id: number
lab: any, lab: any
rgb: any, rgb: any
texture_url: string, texture_url: string
payment_method: number, //支付方式 payment_method: number //支付方式
actual_amount: number, //实付金额 actual_amount: number //实付金额
wait_pay_amount: number, //待付金额 wait_pay_amount: number //待付金额
should_collect_order_id: number, //应付单id should_collect_order_id: number //应付单id
av_return_roll: number, av_return_roll: number
total_sale_price: number, total_sale_price: number
estimate_amount: number, estimate_amount: number
is_return: true|false is_return: true | false
}, }
onClickBtn?: (val:{status:number, orderInfo:Param['value']}) => void onClickBtn?: (val: { status: number; orderInfo: Param['value'] }) => void
} }
export default memo(({value, onClickBtn}: Param) => { export default memo(({ value, onClickBtn }: Param) => {
const userInfo = useSelector((state) => state.userInfo)
const userInfo = useSelector(state => state.userInfo)
//对应数量 //对应数量
const formatCount = useCallback((item, sale_mode) => { const formatCount = useCallback(
return sale_mode == 0? item.roll : Number(item.length / 100) (item, sale_mode) => {
}, [value]) return sale_mode == 0 ? item.roll : Number(item.length / 100)
},
[value],
)
//对应单价 //对应单价
const standardPrice = useCallback((price, sale_mode) => { const standardPrice = useCallback(
return '¥' + formatPriceDiv(price).toLocaleString() + '/' + (sale_mode == 1?'m':'kg') (price, sale_mode) => {
}, [value]) return '¥' + formatPriceDiv(price).toLocaleString() + '/' + (sale_mode == 1 ? 'm' : 'kg')
},
[value],
)
//点击订单按钮 //点击订单按钮
const orderBtnsClick = useCallback((status) => { const orderBtnsClick = useCallback(
onClickBtn?.({status, orderInfo:value}) (status) => {
}, [value]) onClickBtn?.({ status, orderInfo: value })
},
[value],
)
let {SaleOrderStatusTaking, SaleOrderStatusWaitingReceipt} = ORDER_STATUS let { SaleOrderStatusTaking, SaleOrderStatusWaitingReceipt } = ORDER_STATUS
//订单状态 //订单状态
// const orderStatus = useCallback((item) => { // const orderStatus = useCallback((item) => {
@ -67,19 +75,19 @@ export default memo(({value, onClickBtn}: Param) => {
const orderInfo = useMemo(() => { const orderInfo = useMemo(() => {
return { return {
orderId: value?.id, orderId: value?.id,
...value ...value,
} }
}, [value]) }, [value])
//总条数 //总条数
const numText = useMemo(() => { const numText = useMemo(() => {
let total_number_new = value?.sale_mode == 0? value?.total_number:(value?.total_number/100) let total_number_new = value?.sale_mode == 0 ? value?.total_number : value?.total_number / 100
return `${value?.total_fabrics} 种面料,${value?.total_colors} 种颜色,共 ${total_number_new}${value?.sale_mode == 0? ' 条':' 米'}` return `${value?.total_fabrics} 种面料,${value?.total_colors} 种颜色,共 ${total_number_new}${value?.sale_mode == 0 ? ' 条' : ' 米'}`
}, [value]) }, [value])
//订单状态 //订单状态
const orderStatus = useMemo(() => { const orderStatus = useMemo(() => {
if(value.status == SaleOrderStatusWaitingReceipt.value && value.shipment_mode == 1) { if (value.status == SaleOrderStatusWaitingReceipt.value && value.shipment_mode == 1) {
return '待提货' return '待提货'
} else { } else {
return value?.status_name return value?.status_name
@ -88,9 +96,9 @@ export default memo(({value, onClickBtn}: Param) => {
return ( return (
<View className={styles.order_item}> <View className={styles.order_item}>
<View className={styles.header} onClick={() => goLink('/pages/order/index', {id: value?.id})}> <View className={styles.header} onClick={() => goLink('/pages/order/index', { id: value?.id })}>
<View className={styles.user}> <View className={styles.user}>
<Image src={`${userInfo?.adminUserInfo?.avatar_url}`}/> <Image src={`${userInfo?.adminUserInfo?.avatar_url}`} />
</View> </View>
<View className={styles.order_con}> <View className={styles.order_con}>
<Text className={styles.name}>{userInfo?.adminUserInfo?.user_name}</Text> <Text className={styles.name}>{userInfo?.adminUserInfo?.user_name}</Text>
@ -102,10 +110,8 @@ export default memo(({value, onClickBtn}: Param) => {
<View className={styles.product_status}>{orderStatus}</View> <View className={styles.product_status}>{orderStatus}</View>
</View> </View>
</View> </View>
</View> </View>
<View className={styles.product_con} onClick={() => goLink('/pages/order/index', {id: value?.id})}> <View className={styles.product_con} onClick={() => goLink('/pages/order/index', { id: value?.id })}>
<View className={styles.product_title}> <View className={styles.product_title}>
<View className={styles.product_tag}>{value?.sale_mode_name}</View> <View className={styles.product_tag}>{value?.sale_mode_name}</View>
<View className={styles.product_name}>{formatHashTag(value?.product_list?.[0].code, value?.product_list?.[0].name)}</View> <View className={styles.product_name}>{formatHashTag(value?.product_list?.[0].code, value?.product_list?.[0].name)}</View>
@ -113,34 +119,45 @@ export default memo(({value, onClickBtn}: Param) => {
</View> </View>
<View className={styles.product_list}> <View className={styles.product_list}>
<View className={styles.image}> <View className={styles.image}>
<LabAndImg value={{lab:value.lab,rgb:value.rgb,texture_url:value.texture_url}}/> <LabAndImg
value={{
lab: value?.product_list?.[0].product_colors?.[0].lab,
rgb: value?.product_list?.[0].product_colors?.[0].rgb,
texture_url: value?.product_list?.[0].product_colors?.[0].texture_url,
}}
/>
<View className={styles.color_num}>{value?.product_list?.[0].product_colors?.[0].code}</View> <View className={styles.color_num}>{value?.product_list?.[0].product_colors?.[0].code}</View>
</View> </View>
<View className={styles.color_list}> <View className={styles.color_list}>
{value?.product_list?.[0].product_colors.map((itemColor, index) => { {value?.product_list?.[0].product_colors.map((itemColor, index) => {
return ( return (
(index <= 1)&&<View className={styles.color_item}> index <= 1 && (
<View className={styles.color_item}>
<View className={styles.color_title}>{formatHashTag(itemColor.code, itemColor.name)}</View> <View className={styles.color_title}>{formatHashTag(itemColor.code, itemColor.name)}</View>
<View className={styles.color_price}>{standardPrice(itemColor.sale_price, value.sale_mode)}</View> <View className={styles.color_price}>{standardPrice(itemColor.sale_price, value.sale_mode)}</View>
<View className={styles.color_num}>×{formatCount(itemColor, value.sale_mode) + (value.sale_mode == 0?' 条':' 米')}</View> <View className={styles.color_num}>×{formatCount(itemColor, value.sale_mode) + (value.sale_mode == 0 ? ' 条' : ' 米')}</View>
</View> </View>
) )
}) )
} })}
{value?.product_list?.[0].length > 2 && <View className={styles.color_item}> {value?.product_list?.[0].length > 2 && (
<View className={styles.color_item}>
<View className={styles.color_more}></View> <View className={styles.color_more}></View>
<View className={styles.color_more}></View> <View className={styles.color_more}></View>
<View className={styles.color_more}></View> <View className={styles.color_more}></View>
</View>} </View>
)}
</View> </View>
</View> </View>
<View className={styles.color_count_num}> <View className={styles.color_count_num}>
<Text>{numText}</Text> <Text>{numText}</Text>
<Text className={styles.price}><Text>¥</Text>{value.total_sale_price?formatPriceDiv(value.total_sale_price, 100, true):formatPriceDiv(value.estimate_amount, 100, true)}</Text> <Text className={styles.price}>
<Text>¥</Text>
{value.total_sale_price ? formatPriceDiv(value.total_sale_price, 100, true) : formatPriceDiv(value.estimate_amount, 100, true)}
</Text>
</View> </View>
</View> </View>
<OrderBtns orderInfo={orderInfo} onClick={orderBtnsClick} showStatus='list'/> <OrderBtns orderInfo={orderInfo} onClick={orderBtnsClick} showStatus='list' />
</View> </View>
) )
}) })

View File

@ -181,6 +181,9 @@ export default () => {
const applyRefundClose = useCallback(() => { const applyRefundClose = useCallback(() => {
setRefundShow(false) setRefundShow(false)
}, []) }, [])
const applyRefundSuccess = useCallback(() => {
getOrderList()
}, [])
//显示售后记录 //显示售后记录
const [returnRecordShow, setReturnRecordShow] = useState(false) const [returnRecordShow, setReturnRecordShow] = useState(false)
@ -210,14 +213,13 @@ export default () => {
{orderData?.list?.map((item) => { {orderData?.list?.map((item) => {
return ( return (
<View key={item.id} className={styles.order_item_con}> <View key={item.id} className={styles.order_item_con}>
{' '}
<Order value={item} onClickBtn={clickOrderBtn} /> <Order value={item} onClickBtn={clickOrderBtn} />
</View> </View>
) )
})} })}
</InfiniteScroll> </InfiniteScroll>
</View> </View>
<ApplyRefund show={refundShow} onClose={applyRefundClose} orderId={callBackOrderInfo?.id} /> <ApplyRefund show={refundShow} onClose={applyRefundClose} onSuccess={applyRefundSuccess} orderId={callBackOrderInfo?.id} />
<ShopCart intoStatus='again' show={showCart} onClose={() => setShowCart(false)} default_sale_mode={callBackOrderInfo?.sale_mode} /> <ShopCart intoStatus='again' show={showCart} onClose={() => setShowCart(false)} default_sale_mode={callBackOrderInfo?.sale_mode} />
<ReturnRecord show={returnRecordShow} onClose={closeReturnRecord} id={callBackOrderInfo?.id} /> <ReturnRecord show={returnRecordShow} onClose={closeReturnRecord} id={callBackOrderInfo?.id} />
<Payment onSubmitSuccess={onPaySuccess} show={payMentShow} onClose={closePayShow} orderInfo={callBackOrderInfo} /> <Payment onSubmitSuccess={onPaySuccess} show={payMentShow} onClose={closePayShow} orderInfo={callBackOrderInfo} />

View File

@ -1,21 +1,21 @@
import { AFTER_ORDER_STATUS, REFUND_STATUS_ORDER } from "@/common/enum"; import { AFTER_ORDER_STATUS, REFUND_STATUS_ORDER } from '@/common/enum'
import { Text, View } from "@tarojs/components" import { Text, View } from '@tarojs/components'
import classnames from "classnames"; import classnames from 'classnames'
import {memo, useMemo} from "react"; import { memo, useMemo } from 'react'
import styles from './index.module.scss' import styles from './index.module.scss'
type Param = { type Param = {
onLogistics?: (val: 1|2) => void, //1 上传物流 2 查看物流 onLogistics?: (val: 1 | 2) => void //1 上传物流 2 查看物流
orderInfo: { orderInfo: {
return_user_name?:string, return_user_name?: string
return_user_phone?: string, return_user_phone?: string
stage?: number, stage?: number
sale_mode?: 0|1|2, //0 大货 1剪板 2散剪 sale_mode?: 0 | 1 | 2 //0 大货 1剪板 2散剪
type?: number, //申请单退款状态 type?: number //申请单退款状态
return_address?: string
} }
} }
export default memo(({orderInfo, onLogistics}:Param) => { export default memo(({ orderInfo, onLogistics }: Param) => {
const { const {
ReturnStageApplying, ReturnStageApplying,
ReturnStageWaitCheck, ReturnStageWaitCheck,
@ -24,7 +24,7 @@ export default memo(({orderInfo, onLogistics}:Param) => {
ReturnStageCancel, ReturnStageCancel,
ReturnStageQualityCheckPendingRefund, ReturnStageQualityCheckPendingRefund,
ReturnStageServiceOrderPendingRefund, ReturnStageServiceOrderPendingRefund,
ReturnStageRejected ReturnStageRejected,
} = AFTER_ORDER_STATUS } = AFTER_ORDER_STATUS
const { const {
@ -35,16 +35,9 @@ export default memo(({orderInfo, onLogistics}:Param) => {
//是否显示地址 //是否显示地址
const showAddress = useMemo(() => { const showAddress = useMemo(() => {
let after_list = [ let after_list = [ReturnStageApplying.value, ReturnStageCancel.value, ReturnStageRejected.value]
ReturnStageApplying.value, let refurn_list = [ReturnApplyOrderTypeSalesRefund.value, ReturnApplyOrderTypeAdvanceReceiptRefund.value]
ReturnStageCancel.value, return !after_list.includes(orderInfo?.stage!) && orderInfo?.sale_mode != 1 && !refurn_list.includes(orderInfo?.type!)
ReturnStageRejected.value
]
let refurn_list = [
ReturnApplyOrderTypeSalesRefund.value,
ReturnApplyOrderTypeAdvanceReceiptRefund.value
]
return (!after_list.includes(orderInfo?.stage!)) && (orderInfo?.sale_mode != 1) && (!refurn_list.includes(orderInfo?.type!))
}, [orderInfo]) }, [orderInfo])
//上传物流 //上传物流
@ -52,33 +45,37 @@ export default memo(({orderInfo, onLogistics}:Param) => {
return orderInfo?.stage == ReturnStageWaitCheck.value return orderInfo?.stage == ReturnStageWaitCheck.value
}, [orderInfo]) }, [orderInfo])
return ( return (
<> <>
{showAddress&&<View className={styles.address_main}> {showAddress && (
<View className={styles.address_main}>
<View className={styles.address_title_tag}> <View className={styles.address_title_tag}>
<Text className={classnames(styles.miconfont, 'iconfont icon-zhuyi')}></Text> <Text className={classnames(styles.miconfont, 'iconfont icon-zhuyi')}></Text>
退退 退退
</View> </View>
<View className={styles.order_address} > <View className={styles.order_address}>
<View className={classnames(styles.order_address_icon, 'iconfont','icon-fahuo')}></View> <View className={classnames(styles.order_address_icon, 'iconfont', 'icon-fahuo')}></View>
<View className={styles.order_address_text_con}> <View className={styles.order_address_text_con}>
<View className={styles.order_address_text_title}> <View className={styles.order_address_text_title}>
<Text className={classnames(styles.address_text, styles.address_text_no)}>{orderInfo?.return_user_name}</Text> <Text className={classnames(styles.address_text, styles.address_text_no)}>{orderInfo?.return_address}</Text>
</View> </View>
<View className={styles.order_address_text_name}> <View className={styles.order_address_text_name}>
<Text></Text> <Text></Text>
<Text>{orderInfo?.return_user_phone}</Text> <Text>{orderInfo?.return_user_phone}</Text>
{upLogistics&&<View className={styles.updateBtn} onClick={() => onLogistics?.(1)}> {(upLogistics && (
<View className={styles.updateBtn} onClick={() => onLogistics?.(1)}>
</View> </View>
||<View className={styles.updateBtn} onClick={() => onLogistics?.(2)}> )) || (
<View className={styles.updateBtn} onClick={() => onLogistics?.(2)}>
</View>} </View>
)}
</View> </View>
</View> </View>
</View> </View>
</View>} </View>
)}
</> </>
) )
}) })

View File

@ -1,31 +1,30 @@
import { SaleOrderOrderDetailApi } from "@/api/salesAfterOrder"; import { SaleOrderOrderDetailApi } from '@/api/salesAfterOrder'
import { formatHashTag, formatPriceDiv, formatWeightDiv } from "@/common/fotmat"; import { formatHashTag, formatPriceDiv, formatWeightDiv } from '@/common/fotmat'
import LabAndImg from "@/components/LabAndImg"; import LabAndImg from '@/components/LabAndImg'
import Popup from "@/components/popup"; import Popup from '@/components/popup'
import { ScrollView, Text, View } from "@tarojs/components"; import { ScrollView, Text, View } from '@tarojs/components'
import { memo, useCallback, useEffect, useMemo, useState } from "react"; import { memo, useCallback, useEffect, useMemo, useState } from 'react'
import Taro from "@tarojs/taro"; import Taro from '@tarojs/taro'
import styles from './index.module.scss' import styles from './index.module.scss'
type Param = { type Param = {
show?: true|false, show?: true | false
onClose?: () => void, onClose?: () => void
onSubmit?: () => void, onSubmit?: () => void
id?: number id?: number
} }
export default memo(({show, onClose, onSubmit, id}:Param) => { export default memo(({ show, onClose, onSubmit, id }: Param) => {
useEffect(() => { useEffect(() => {
if(show && id) getSaleOrderPreView() if (show && id) getSaleOrderPreView()
if(!show) setFormatDetailOrder(() => null) if (!show) setFormatDetailOrder(() => null)
}, [show, id]) }, [show, id])
//获取订单详情 //获取订单详情
const [orderDetail, setOrderDetail] = useState<any>(null) //获取到的原始数据 const [orderDetail, setOrderDetail] = useState<any>(null) //获取到的原始数据
const {fetchData: saleOrderOrderDetailData} = SaleOrderOrderDetailApi() const { fetchData: saleOrderOrderDetailData } = SaleOrderOrderDetailApi()
const getSaleOrderPreView = async () => { const getSaleOrderPreView = async () => {
if(id) { if (id) {
let res = await saleOrderOrderDetailData({id: id}) let res = await saleOrderOrderDetailData({ id: id })
setOrderDetail(res.data) setOrderDetail(res.data)
} }
Taro.stopPullDownRefresh() Taro.stopPullDownRefresh()
@ -40,7 +39,7 @@ export default memo(({show, onClose, onSubmit, id}:Param) => {
total_colors: orderDetail.total_colors, //总颜色数量 total_colors: orderDetail.total_colors, //总颜色数量
total_number: orderDetail.total_number, //总数量 total_number: orderDetail.total_number, //总数量
total_fabrics: orderDetail.total_fabrics, //面料数量 total_fabrics: orderDetail.total_fabrics, //面料数量
unit: orderDetail.sale_mode == 0?'条':'m', //单位 unit: orderDetail.sale_mode == 0 ? '条' : 'm', //单位
list: orderDetail.product_list, list: orderDetail.product_list,
stage: orderDetail.stage, //订单状态 stage: orderDetail.stage, //订单状态
type: orderDetail.type, //退货or退款 type: orderDetail.type, //退货or退款
@ -54,54 +53,63 @@ export default memo(({show, onClose, onSubmit, id}:Param) => {
//监听获取到的数据 //监听获取到的数据
useEffect(() => { useEffect(() => {
if(orderDetail) if (orderDetail) formatData()
formatData()
}, [orderDetail]) }, [orderDetail])
//对应数量 //对应数量
const formatCount = useCallback((item) => { const formatCount = useCallback(
return formatDetailOrder?.sale_mode == 0? item.roll : Number(item.length / 100) (item) => {
}, [formatDetailOrder]) return formatDetailOrder?.sale_mode == 0 ? item.roll : Number(item.length / 100)
},
[formatDetailOrder],
)
//对应单价 //对应单价
const standardPrice = useCallback(price => { const standardPrice = useCallback(
return formatPriceDiv(price).toLocaleString() + '/' + (formatDetailOrder?.sale_mode == 1?'m':'kg') (price) => {
}, [formatDetailOrder]) return formatPriceDiv(price).toLocaleString() + '/' + (formatDetailOrder?.sale_mode == 1 ? 'm' : 'kg')
},
[formatDetailOrder],
)
//数量格式 //数量格式
const numText = useMemo(() => { const numText = useMemo(() => {
if(formatDetailOrder) { if (formatDetailOrder) {
let tatal_number = formatDetailOrder?.sale_mode == 0?formatDetailOrder?.total_number:formatDetailOrder?.total_number/100 let tatal_number = formatDetailOrder?.sale_mode == 0 ? formatDetailOrder?.total_number : formatDetailOrder?.total_number / 100
return `${formatDetailOrder?.total_fabrics} 种面料,${formatDetailOrder?.total_colors} 种颜色,共 ${tatal_number}${formatDetailOrder?.unit}` return `${formatDetailOrder?.total_fabrics} 种面料,${formatDetailOrder?.total_colors} 种颜色,共 ${tatal_number} ${formatDetailOrder?.unit}`
} }
}, [formatDetailOrder]) }, [formatDetailOrder])
//整理颜色 //整理颜色
const labAndRgbAndUrl = useCallback((item) => { const labAndRgbAndUrl = useCallback((item) => {
return {lab:{...item?.lab}, rgb:{...item?.rgb}, texturl_url: item?.texturl_url} return { lab: { ...item?.lab }, rgb: { ...item?.rgb }, texturl_url: item?.texturl_url }
}, []) }, [])
return ( return (
<> <>
<Popup show={show} title="申请记录" onClose={onClose}> <Popup show={show} title='申请记录' onClose={onClose}>
<View className={styles.apply_record_main}> <View className={styles.apply_record_main}>
{formatDetailOrder&&<> {formatDetailOrder && (
<View className={styles.kind_number}><Text>{numText}</Text></View> <>
<View className={styles.kind_number}>
<Text>{numText}</Text>
</View>
<ScrollView scrollY className={styles.apply_record_scroll}> <ScrollView scrollY className={styles.apply_record_scroll}>
<View className={styles.orders_list_con}> <View className={styles.orders_list_con}>
{ {formatDetailOrder?.list?.map((item) => {
formatDetailOrder?.list?.map(item => { return (
return <View key={item.product_code} className={styles.order_list}> <View key={item.product_code} className={styles.order_list}>
<View className={styles.order_list_title}> <View className={styles.order_list_title}>
<View className={styles.tag}>{formatDetailOrder.sale_mode_name}</View> <View className={styles.tag}>{formatDetailOrder.sale_mode_name}</View>
<View className={styles.title}>{formatHashTag(item.code, item.name)}</View> <View className={styles.title}>{formatHashTag(item.code, item.name)}</View>
<View className={styles.num}>{item?.product_colors.length}</View> <View className={styles.num}>{item?.product_colors.length}</View>
</View> </View>
<View className={styles.order_list_scroll}> <View className={styles.order_list_scroll}>
{item?.product_colors?.map(colorItem => { {item?.product_colors?.map((colorItem) => {
return <View key={colorItem.id} className={styles.order_list_item}> return (
<View key={colorItem.id} className={styles.order_list_item}>
<View className={styles.order_list_item_img}> <View className={styles.order_list_item_img}>
<LabAndImg value={labAndRgbAndUrl(colorItem)}/> <LabAndImg value={labAndRgbAndUrl(colorItem)} />
</View> </View>
<View className={styles.order_list_item_con}> <View className={styles.order_list_item_con}>
<View className={styles.order_list_item_des}> <View className={styles.order_list_item_des}>
@ -112,23 +120,27 @@ export default memo(({show, onClose, onSubmit, id}:Param) => {
</View> </View>
</View> </View>
<View className={styles.order_list_item_count}> <View className={styles.order_list_item_count}>
<View className={styles.count_num}>×{formatCount(colorItem)}<text>{formatDetailOrder.unit}</text></View> <View className={styles.count_num}>
<View className={styles.count_price}><text>¥</text>{formatPriceDiv(colorItem.estimate_amount, 100, true)}</View> ×{formatCount(colorItem)}
<text>{formatDetailOrder.unit}</text>
</View>
<View className={styles.count_price}>
<text>¥</text>
{formatPriceDiv(colorItem.estimate_amount, 100, true)}
</View> </View>
</View> </View>
</View> </View>
</View>
)
})} })}
</View> </View>
</View> </View>
}) )
} })}
{/* <View className={styles.order_total}>
<Text></Text>
<Text>×{orderDetail?.total_number}</Text>
</View> */}
</View> </View>
</ScrollView> </ScrollView>
</>} </>
)}
</View> </View>
</Popup> </Popup>
</> </>

View File

@ -1,30 +1,30 @@
import Popup from "@/components/popup"; import Popup from '@/components/popup'
import { Text, View } from "@tarojs/components"; import { Text, View } from '@tarojs/components'
import { memo, useCallback, useEffect, useRef, useState } from "react"; import { memo, useCallback, useEffect, useRef, useState } from 'react'
import UploadImage from "@/components/uploadImage" import UploadImage from '@/components/uploadImage'
import styles from './index.module.scss' import styles from './index.module.scss'
import TextareaEnhance from "@/components/textareaEnhance"; import TextareaEnhance from '@/components/textareaEnhance'
import { ReturnApplyLogisticsApi } from "@/api/salesAfterOrder"; import { ReturnApplyLogisticsApi } from '@/api/salesAfterOrder'
import { alert } from "@/common/common"; import { alert } from '@/common/common'
type Param = { type Param = {
show?: true|false, show?: true | false
onClose?: () => void, onClose?: () => void
onSubmit?: () => void, onSubmit?: () => void
id?: number, //订单id id?: number //订单id
images: string[], //图片列表 images: string[] //图片列表
descValue?: string, //描述 descValue?: string //描述
onlyRead?: false|true //true 只读 onlyRead?: false | true //true 只读
} }
export default memo(({show = false, onClose, onSubmit, id = 0, images = [], descValue = '', onlyRead = false}: Param) => { export default memo(({ show = false, onClose, onSubmit, id = 0, images = [], descValue = '', onlyRead = false }: Param) => {
//需要提交的数据 //需要提交的数据
const submitData = useRef({ const submitData = useRef({
accessory_url: [], accessory_url: [],
remark: '', remark: '',
id: 0 id: 0,
}) })
useEffect(() => { useEffect(() => {
if(id) submitData.current.id = id if (id) submitData.current.id = id
}, [id]) }, [id])
//获取图片列表 //获取图片列表
@ -38,12 +38,12 @@ export default memo(({show = false, onClose, onSubmit, id = 0, images = [], desc
}, []) }, [])
//确定 //确定
const {fetchData} = ReturnApplyLogisticsApi() const { fetchData } = ReturnApplyLogisticsApi()
const onSubmitEven = async () => { const onSubmitEven = async () => {
if(!id) return alert.error('参数有误') if (!id) return alert.error('参数有误')
if(submitData.current.accessory_url.length <= 0) return alert.error('请上传附件') if (submitData.current.accessory_url.length <= 0) return alert.error('请上传附件')
let res = await fetchData(submitData.current) let res = await fetchData(submitData.current)
if(res.success) { if (res.success) {
alert.success('上传成功') alert.success('上传成功')
} else { } else {
alert.error('上传失败') alert.error('上传失败')
@ -53,20 +53,24 @@ export default memo(({show = false, onClose, onSubmit, id = 0, images = [], desc
return ( return (
<> <>
<Popup show={show} title={onlyRead?'查看物流':"上传物流"} onClose={onClose}> <Popup show={show} title={onlyRead ? '查看物流' : '上传物流'} onClose={onClose}>
<View className={styles.logistics_main}> <View className={styles.logistics_main}>
<View className={styles.logistics_image}> <View className={styles.logistics_image}>
<Text className={styles.title_desc}></Text> <Text className={styles.title_desc}></Text>
<View className={styles.upload_image}> <View className={styles.upload_image}>
<UploadImage onChange={getImageList} defaultList={images} onlyRead={onlyRead}/> <UploadImage onChange={getImageList} defaultList={images} onlyRead={onlyRead} />
</View> </View>
</View> </View>
<View className={styles.logistics_desc}> <View className={styles.logistics_desc}>
<TextareaEnhance defaultValue={descValue} onChange={getOtherReason} title="备注:" onlyRead={onlyRead} placeholder="请输入备注信息"/> <TextareaEnhance defaultValue={descValue} onChange={getOtherReason} title='备注:' onlyRead={onlyRead} placeholder='请输入备注信息' />
</View> </View>
{!onlyRead&&<View className={styles.btns_two}> {!onlyRead && (
<View className={styles.verify_btn } onClick={() => onSubmitEven()}></View> <View className={styles.btns_two}>
</View >} <View className={styles.verify_btn} onClick={() => onSubmitEven()}>
</View>
</View>
)}
</View> </View>
</Popup> </Popup>
</> </>

View File

@ -1,23 +1,22 @@
import { SaleOrderOrderDetailApi } from '@/api/salesAfterOrder'
import { SaleOrderOrderDetailApi } from "@/api/salesAfterOrder"; import { AFTER_ORDER_STATUS, ORDER_STATUS } from '@/common/enum'
import { AFTER_ORDER_STATUS, ORDER_STATUS } from "@/common/enum"; import { formatDateTime, formatImgUrl, formatPriceDiv } from '@/common/fotmat'
import { formatDateTime, formatImgUrl, formatPriceDiv } from "@/common/fotmat"; import AfterOrderBtns from '@/components/afterOrderBtns'
import AfterOrderBtns from "@/components/afterOrderBtns"; import SearchInput from '@/components/searchInput'
import SearchInput from "@/components/searchInput"; import useLogin from '@/use/useLogin'
import useLogin from "@/use/useLogin"; import { Image, Text, Textarea, View } from '@tarojs/components'
import { Image, Text, Textarea, View } from "@tarojs/components" import Taro, { useDidShow, usePullDownRefresh, useRouter } from '@tarojs/taro'
import Taro, {useDidShow, usePullDownRefresh, useRouter } from "@tarojs/taro"; import classnames from 'classnames'
import classnames from "classnames"; import { useCallback, useEffect, useMemo, useRef, useState, memo } from 'react'
import { useCallback, useEffect, useMemo, useRef, useState, memo } from "react"; import AddressInfoDetail from './components/addressInfoDetail'
import AddressInfoDetail from "./components/addressInfoDetail"; import ApplyRecord from './components/applyRecord'
import ApplyRecord from "./components/applyRecord"; import ContentBox from './components/contentBox'
import ContentBox from "./components/contentBox"; import KindList from './components/kindList'
import KindList from "./components/kindList"; import OrderState from './components/orderState'
import OrderState from "./components/orderState"; import ReturnLogistics from './components/returnLogistics'
import ReturnLogistics from "./components/returnLogistics";
import styles from './index.module.scss' import styles from './index.module.scss'
export default () => { export default () => {
useLogin() useLogin()
const router = useRouter() const router = useRouter()
const orderId = useRef<number>(Number(router.params.id)) const orderId = useRef<number>(Number(router.params.id))
@ -27,10 +26,10 @@ import styles from './index.module.scss'
//获取订单详情 //获取订单详情
const [orderDetail, setOrderDetail] = useState<any>() //获取到的原始数据 const [orderDetail, setOrderDetail] = useState<any>() //获取到的原始数据
const {fetchData: saleOrderOrderDetailData} = SaleOrderOrderDetailApi() const { fetchData: saleOrderOrderDetailData } = SaleOrderOrderDetailApi()
const getSaleOrderPreView = async () => { const getSaleOrderPreView = async () => {
if(orderId.current) { if (orderId.current) {
let res = await saleOrderOrderDetailData({id: orderId.current}) let res = await saleOrderOrderDetailData({ id: orderId.current })
setOrderDetail(res.data) setOrderDetail(res.data)
} }
Taro.stopPullDownRefresh() Taro.stopPullDownRefresh()
@ -38,8 +37,7 @@ import styles from './index.module.scss'
//监听获取到的数据 //监听获取到的数据
useEffect(() => { useEffect(() => {
if(orderDetail) if (orderDetail) formatData()
formatData()
}, [orderDetail]) }, [orderDetail])
//格式化数据格式 //格式化数据格式
@ -47,25 +45,27 @@ import styles from './index.module.scss'
const formatData = () => { const formatData = () => {
setFormatDetailOrder({ setFormatDetailOrder({
...orderDetail, ...orderDetail,
unit: orderDetail.sale_mode == 0?'条':'m', //单位 unit: orderDetail.sale_mode == 0 ? '条' : 'm', //单位
}) })
} }
const formatPreViewOrderMemo = useMemo(() => { const formatPreViewOrderMemo = useMemo(() => {
return formatDetailOrder return formatDetailOrder
}, [formatDetailOrder]) }, [formatDetailOrder])
//获取底部按钮点击, 获取按钮状态 //获取底部按钮点击, 获取按钮状态
const orderStateClick = useCallback((val) => { const orderStateClick = useCallback(
if(val == 1 || val == 6) { (val) => {
if (val == 1 || val == 6) {
getSaleOrderPreView() getSaleOrderPreView()
} else if(val == 8) { } else if (val == 8) {
//申请记录 //申请记录
setApplyRecord(true) setApplyRecord(true)
} else if (val == 5) { } else if (val == 5) {
onShowLogistics(1) onShowLogistics(1)
} }
}, [orderDetail]) },
[orderDetail],
)
//页面下拉刷新 //页面下拉刷新
usePullDownRefresh(() => { usePullDownRefresh(() => {
@ -75,21 +75,19 @@ import styles from './index.module.scss'
//按钮所需数据 //按钮所需数据
const orderInfo = useMemo(() => { const orderInfo = useMemo(() => {
return { return {
...orderDetail ...orderDetail,
} }
}, [orderDetail]) }, [orderDetail])
//售后订单状态枚举 //售后订单状态枚举
const { const {} = AFTER_ORDER_STATUS
} = AFTER_ORDER_STATUS
//物流显示 //物流显示
const [logisticsShow, setLogisticsShow] = useState(false) const [logisticsShow, setLogisticsShow] = useState(false)
const [logistics, setLogistics] = useState(false) const [logistics, setLogistics] = useState(false)
const onShowLogistics = useCallback((val) => { const onShowLogistics = useCallback((val) => {
setLogisticsShow(true) setLogisticsShow(true)
if(val != 1) setLogistics(true) if (val != 1) setLogistics(true)
}, []) }, [])
const onCloseLogistics = useCallback(() => { const onCloseLogistics = useCallback(() => {
setLogisticsShow(false) setLogisticsShow(false)
@ -105,20 +103,28 @@ import styles from './index.module.scss'
return ( return (
<View className={styles.order_main}> <View className={styles.order_main}>
<OrderState orderInfo={orderDetail}/> <OrderState orderInfo={orderDetail} />
<AddressInfoDetail orderInfo={orderDetail} onLogistics={onShowLogistics}/> <AddressInfoDetail orderInfo={orderDetail} onLogistics={onShowLogistics} />
<KindList order={formatPreViewOrderMemo}/> <KindList order={formatPreViewOrderMemo} />
<OrderDes orderInfo={orderDetail}/> <OrderDes orderInfo={orderDetail} />
<AfterOrderBtns orderInfo={orderInfo} onClick={orderStateClick}/> <AfterOrderBtns orderInfo={orderInfo} onClick={orderStateClick} />
<AfterSalePricture urls={orderDetail?.fabric_piece_accessory_url}/> <AfterSalePricture urls={orderDetail?.fabric_piece_accessory_url} />
<ReturnLogistics onlyRead={logistics} images={orderDetail?.accessory_url} descValue={orderDetail?.take_goods_remark} show={logisticsShow} id={orderDetail?.return_apply_order_id} onClose={onCloseLogistics} onSubmit={logisticsSuccess}/> <ReturnLogistics
<ApplyRecord show={applyRecord} id={orderDetail?.id} onClose={() => setApplyRecord(false)}/> onlyRead={logistics}
<View className="common_safe_area_y"></View> images={orderDetail?.accessory_url}
descValue={orderDetail?.take_goods_remark}
show={logisticsShow}
id={orderDetail?.return_apply_order_id}
onClose={onCloseLogistics}
onSubmit={logisticsSuccess}
/>
<ApplyRecord show={applyRecord} id={orderDetail?.id} onClose={() => setApplyRecord(false)} />
<View className='common_safe_area_y'></View>
</View> </View>
) )
} }
const OrderDes = memo(({orderInfo}:{orderInfo?:any}) => { const OrderDes = memo(({ orderInfo }: { orderInfo?: any }) => {
//复制功能 //复制功能
const clipboardData = (val) => { const clipboardData = (val) => {
Taro.setClipboardData({ Taro.setClipboardData({
@ -126,24 +132,28 @@ import styles from './index.module.scss'
success: function (res) { success: function (res) {
Taro.showToast({ Taro.showToast({
icon: 'none', icon: 'none',
title: '复制成功' title: '复制成功',
}) })
} },
}) })
} }
return ( return (
<View className={styles.order_info} > <View className={styles.order_info}>
<View className={styles.order_info_title}></View> <View className={styles.order_info_title}></View>
<SearchInput showBorder={false} title='售后单号' height='50rpx'> <SearchInput showBorder={false} title='售后单号' height='50rpx'>
<View className={styles.order_num}> <View className={styles.order_num}>
<Text>{orderInfo?.return_order_no}</Text> <Text>{orderInfo?.return_order_no}</Text>
<View className={styles.order_num_btn} onClick={() => clipboardData(orderInfo?.return_order_no)}></View> <View className={styles.order_num_btn} onClick={() => clipboardData(orderInfo?.return_order_no)}>
</View>
</View> </View>
</SearchInput> </SearchInput>
<SearchInput showBorder={false} title='订单号' height='50rpx'> <SearchInput showBorder={false} title='订单号' height='50rpx'>
<View className={styles.order_num}> <View className={styles.order_num}>
<Text>{orderInfo?.order_no}</Text> <Text>{orderInfo?.order_no}</Text>
<View className={styles.order_num_btn} onClick={() => clipboardData(orderInfo?.order_no)}></View> <View className={styles.order_num_btn} onClick={() => clipboardData(orderInfo?.order_no)}>
</View>
</View> </View>
</SearchInput> </SearchInput>
<SearchInput showBorder={false} title='退货原因' height='50rpx'> <SearchInput showBorder={false} title='退货原因' height='50rpx'>
@ -163,13 +173,12 @@ import styles from './index.module.scss'
</SearchInput> </SearchInput>
</View> </View>
) )
}) })
const AfterSalePricture = memo(({urls = []}:{urls: string[]}) => {
const AfterSalePricture = memo(({ urls = [] }: { urls: string[] }) => {
const showList = useMemo(() => { const showList = useMemo(() => {
let res = urls.map(item => { let res = urls.map((item) => {
return formatImgUrl(item, "!w800") return formatImgUrl(item, '!w800')
}) })
return res return res
}, [urls]) }, [urls])
@ -178,16 +187,18 @@ import styles from './index.module.scss'
const showImage = () => { const showImage = () => {
Taro.previewImage({ Taro.previewImage({
current: showList[0], // 当前显示 current: showList[0], // 当前显示
urls: showList // 需要预览的图片http链接列表 urls: showList, // 需要预览的图片http链接列表
}) })
} }
return ( return (
<ContentBox title="售后图片"> <ContentBox title='售后图片'>
<View className={styles.after_sale_picture_list}> <View className={styles.after_sale_picture_list}>
{urls?.map(item=> <View className={styles.after_sale_picture_item} onClick={showImage}> {urls?.map((item) => (
<View className={styles.after_sale_picture_item} onClick={showImage}>
<Image src={formatImgUrl(item)} /> <Image src={formatImgUrl(item)} />
</View>)} </View>
))}
</View> </View>
</ContentBox> </ContentBox>
) )
}) })

View File

@ -1,102 +1,101 @@
import Search from "@/components/search" import Search from '@/components/search'
import useLogin from "@/use/useLogin" import useLogin from '@/use/useLogin'
import {View } from "@tarojs/components" import { View } from '@tarojs/components'
import Taro, { useDidShow} from "@tarojs/taro" import Taro, { useDidShow } from '@tarojs/taro'
import { useCallback, useEffect, useMemo, useRef, useState } from "react" import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss' import styles from './index.module.scss'
import classnames from "classnames"; import classnames from 'classnames'
import Order from "./components/order" import Order from './components/order'
import InfiniteScroll from "@/components/infiniteScroll" import InfiniteScroll from '@/components/infiniteScroll'
import { dataLoadingStatus, getFilterData } from "@/common/util" import { dataLoadingStatus, getFilterData } from '@/common/util'
import OrderStatusList from "./components/orderStatusList" import OrderStatusList from './components/orderStatusList'
import { GetSaleOrderListApi, RefundOrderSatausApi } from "@/api/salesAfterOrder" import { GetSaleOrderListApi, RefundOrderSatausApi } from '@/api/salesAfterOrder'
import ApplyRecord from "../components/applyRecord" import ApplyRecord from '../components/applyRecord'
import ReturnLogistics from "../components/returnLogistics" import ReturnLogistics from '../components/returnLogistics'
export default () => { export default () => {
useLogin() useLogin()
//搜索参数 //搜索参数
const [searchField, setSearchField] = useState<{status: number|null, page: number, size: number, name: string}>({ const [searchField, setSearchField] = useState<{ status: number | null; page: number; size: number; name: string }>({
status: null, status: null,
page : 1, page: 1,
size : 10, size: 10,
name:'' name: '',
}) })
//获取订单状态 //获取订单状态
const [statusList, setStatusList] = useState<any[]>([{id: -1, name: '全部'}]) const [statusList, setStatusList] = useState<any[]>([{ id: -1, name: '全部' }])
const {fetchData: fetchDataStatus} = RefundOrderSatausApi() const { fetchData: fetchDataStatus } = RefundOrderSatausApi()
const getOrderStatusList = async () => { const getOrderStatusList = async () => {
let res = await fetchDataStatus() let res = await fetchDataStatus()
setStatusList((e) => [...e, ...res.data.list]) setStatusList((e) => [...e, ...res.data.list])
} }
useEffect(() => { useEffect(() => {
getOrderStatusList() getOrderStatusList()
setSearchField((e) => ({...e, status:-1})) setSearchField((e) => ({ ...e, status: -1 }))
}, []) }, [])
//获取订单列表 //获取订单列表
const {fetchData: listFetchData, state:orderState} = GetSaleOrderListApi() const { fetchData: listFetchData, state: orderState } = GetSaleOrderListApi()
const [orderData, setOrderData] = useState<{list:any[], total:number}>({list:[], total:0}) const [orderData, setOrderData] = useState<{ list: any[]; total: number }>({ list: [], total: 0 })
const getOrderList = async () => { const getOrderList = async () => {
let res = await listFetchData(getFilterData(searchField)) let res = await listFetchData(getFilterData(searchField))
setOrderData({list: res.data.list, total: res.data.total}) setOrderData({ list: res.data.list, total: res.data.total })
setRefresherTriggeredStatus(() => false) setRefresherTriggeredStatus(() => false)
} }
useDidShow(() => { useDidShow(() => {
if(searchField.status != null) getOrderList() if (searchField.status != null) getOrderList()
}) })
//监听筛选条件变化 //监听筛选条件变化
useEffect(() => { useEffect(() => {
if(searchField.status != null) getOrderList() if (searchField.status != null) getOrderList()
}, [searchField]) }, [searchField])
//上拉加载数据 //上拉加载数据
const pageNum = useRef({size: searchField.size, page: searchField.page}) const pageNum = useRef({ size: searchField.size, page: searchField.page })
const getScrolltolower = useCallback(() => { const getScrolltolower = useCallback(() => {
if(orderData.list.length < orderData.total) { if (orderData.list.length < orderData.total) {
pageNum.current.page++ pageNum.current.page++
const size = pageNum.current.size * pageNum.current.page const size = pageNum.current.size * pageNum.current.page
setSearchField((e) => ({...e, size })) setSearchField((e) => ({ ...e, size }))
} }
}, [orderData]) }, [orderData])
//状态改变 //状态改变
const changeStatus = useCallback((e) => { const changeStatus = useCallback((e) => {
pageNum.current.page = 1 pageNum.current.page = 1
setSearchField((value) => ({...value, status:e, size:10})) setSearchField((value) => ({ ...value, status: e, size: 10 }))
setOrderData(() => ({list:[], total:0})) setOrderData(() => ({ list: [], total: 0 }))
}, []) }, [])
//数据加载状态 //数据加载状态
const statusMore = useMemo(() => { const statusMore = useMemo(() => {
return dataLoadingStatus({list:orderData.list, total: orderData.total, status: orderState.loading}) return dataLoadingStatus({ list: orderData.list, total: orderData.total, status: orderState.loading })
}, [orderData, orderState]) }, [orderData, orderState])
//输入了搜索关键字 //输入了搜索关键字
const getSearchData = useCallback((e) => { const getSearchData = useCallback((e) => {
pageNum.current.page = 1 pageNum.current.page = 1
setOrderData(() => ({list:[], total:0})) setOrderData(() => ({ list: [], total: 0 }))
setSearchField((val) => ({...val, name:e, size:10})) setSearchField((val) => ({ ...val, name: e, size: 10 }))
}, []) }, [])
//列表下拉刷新 //列表下拉刷新
const [refresherTriggeredStatus, setRefresherTriggeredStatus] = useState(false) const [refresherTriggeredStatus, setRefresherTriggeredStatus] = useState(false)
const getRefresherRefresh = async () => { const getRefresherRefresh = async () => {
pageNum.current.size = 1 pageNum.current.size = 1
setRefresherTriggeredStatus(true) setRefresherTriggeredStatus(true)
setSearchField((val) => ({...val, size:10})) setSearchField((val) => ({ ...val, size: 10 }))
} }
//监听点击的按钮 //监听点击的按钮
const [callBackOrderInfo, setCallBackPayOrderInfo] = useState<any>() const [callBackOrderInfo, setCallBackPayOrderInfo] = useState<any>()
const clickOrderBtn = useCallback(({status, orderInfo}) => { const clickOrderBtn = useCallback(
if(status == 1 || status == 6) { ({ status, orderInfo }) => {
if (status == 1 || status == 6) {
getOrderList() getOrderList()
} else if (status == 8) { } else if (status == 8) {
setApplyRecord(true) setApplyRecord(true)
@ -104,7 +103,9 @@ export default () => {
onShowLogistics(() => true) onShowLogistics(() => true)
} }
setCallBackPayOrderInfo(orderInfo) setCallBackPayOrderInfo(orderInfo)
}, [orderData]) },
[orderData],
)
//显示记录 //显示记录
const [applyRecord, setApplyRecord] = useState(false) const [applyRecord, setApplyRecord] = useState(false)
@ -126,18 +127,34 @@ export default () => {
return ( return (
<View className={styles.order_list_main}> <View className={styles.order_list_main}>
<View className={styles.title}> <View className={styles.title}>
<Search placeIcon="out" placeholder="搜索商品/名称/颜色/订单号" showBtn={true} changeOnSearch={getSearchData} debounceTime={300}/> <Search placeIcon='out' placeholder='搜索商品/名称/颜色/订单号' showBtn={true} changeOnSearch={getSearchData} debounceTime={300} />
<OrderStatusList list={statusList} onSelect={changeStatus} defaultId={1}/> <OrderStatusList list={statusList} onSelect={changeStatus} defaultId={1} />
</View> </View>
<View className={styles.order_list}> <View className={styles.order_list}>
<InfiniteScroll statusMore={statusMore} selfonScrollToLower={getScrolltolower} refresherEnabled={true} refresherTriggered={refresherTriggeredStatus} selfOnRefresherRefresh={getRefresherRefresh}> <InfiniteScroll
{orderData?.list.map(item => { statusMore={statusMore}
return <View key={item.id} className={styles.order_item_con}> <Order value={item} onClickBtn={clickOrderBtn}/></View> selfonScrollToLower={getScrolltolower}
refresherEnabled={true}
refresherTriggered={refresherTriggeredStatus}
selfOnRefresherRefresh={getRefresherRefresh}>
{orderData?.list.map((item) => {
return (
<View key={item.id} className={styles.order_item_con}>
<Order value={item} onClickBtn={clickOrderBtn} />
</View>
)
})} })}
</InfiniteScroll> </InfiniteScroll>
</View> </View>
<ApplyRecord show={applyRecord} id={callBackOrderInfo?.id} onClose={() => setApplyRecord(false)}/> <ApplyRecord show={applyRecord} id={callBackOrderInfo?.id} onClose={() => setApplyRecord(false)} />
<ReturnLogistics images={callBackOrderInfo?.accessory_url} descValue={callBackOrderInfo?.take_goods_remark} show={logisticsShow} id={callBackOrderInfo?.return_apply_order_id} onClose={onCloseLogistics} onSubmit={logisticsSuccess}/> <ReturnLogistics
images={callBackOrderInfo?.accessory_url}
descValue={callBackOrderInfo?.take_goods_remark}
show={logisticsShow}
id={callBackOrderInfo?.return_apply_order_id}
onClose={onCloseLogistics}
onSubmit={logisticsSuccess}
/>
</View> </View>
) )
} }

View File

@ -1,29 +1,29 @@
.main{ .main {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
height: 100vh; height: 100vh;
background-color: $color_bg_one; background-color: $color_bg_one;
.search{ .search {
padding: 20px; padding: 20px;
.SearchInput{ .SearchInput {
background-color: #fff; background-color: #fff;
padding: 10px 20px; padding: 10px 20px;
box-sizing: border-box; box-sizing: border-box;
border-radius: 10px; border-radius: 10px;
} }
.bluetooth_color{ .bluetooth_color {
.color_bock{ .color_bock {
width: 100px; width: 100px;
height: 46px; height: 46px;
} }
.color_bock_no{ .color_bock_no {
font-size: $font_size_medium; font-size: $font_size_medium;
color: $color_font_three; color: $color_font_three;
} }
} }
} }
.filter{ .filter {
.filter_all { .filter_all {
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
@ -31,80 +31,80 @@
padding: 20px 130px; padding: 20px 130px;
font-size: $font_size_medium; font-size: $font_size_medium;
color: $color_font_three; color: $color_font_three;
.text_zh, .text_sc{ .text_zh,
.text_sc {
color: $color_main; color: $color_main;
display: flex; display: flex;
align-items: center; align-items: center;
.sortIcon{ .sortIcon {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
position: relative; position: relative;
.icon_one{ .icon_one {
font-size: $font_size_medium; font-size: $font_size_medium;
position: absolute; position: absolute;
margin:auto; margin: auto;
top:0; top: 0;
} }
} }
} }
.text_ss{ .text_ss {
position: relative; position: relative;
.miconfont{ .miconfont {
font-size: 20px; font-size: 20px;
margin-left: 5px; margin-left: 5px;
} }
&::before{ &::before {
content: ''; content: '';
width: 2px; width: 2px;
height: 32px; height: 32px;
background-color: #C2C2C2; background-color: #c2c2c2;
position: absolute; position: absolute;
top: 0; top: 0;
left: -30px; left: -30px;
} }
} }
} }
.filter_btn_con{ .filter_btn_con {
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
align-items: center; align-items: center;
height: 86px; height: 86px;
} }
.filter_scroll{ .filter_scroll {
flex:1; flex: 1;
width: 0; width: 0;
padding-left: 20px; padding-left: 20px;
::-webkit-scrollbar { ::-webkit-scrollbar {
display:none; display: none;
width:0; width: 0;
height:0; height: 0;
color:transparent; color: transparent;
} }
} }
.filter_btn{ .filter_btn {
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
padding: 20px; padding: 20px;
margin-right: 20px; margin-right: 20px;
flex:1; flex: 1;
view{ view {
font-size: $font_size_medium; font-size: $font_size_medium;
background-color: #F0F0F0; background-color: #f0f0f0;
border-radius: 24px; border-radius: 24px;
min-width: 126px; min-width: 126px;
height: 46.93px; height: 46.93px;
text-align: center; text-align: center;
line-height: 46.93px; line-height: 46.93px;
color: $color_font_three; color: $color_font_three;
&:nth-last-child(n+2) { &:nth-last-child(n + 2) {
margin-right: 10px; margin-right: 10px;
} }
&:nth-last-child(1) { &:nth-last-child(1) {
margin-right: 30px; margin-right: 30px;
} }
} }
.selected{ .selected {
background-color: #ecf5ff; background-color: #ecf5ff;
border: 2px solid #cde5ff; border: 2px solid #cde5ff;
color: $color_main; color: $color_main;
@ -112,88 +112,88 @@
height: 42.93px; height: 42.93px;
} }
} }
.filter_more{ .filter_more {
font-size: $font_size_medium; font-size: $font_size_medium;
color: $color_font_three; color: $color_font_three;
padding: 0 30px 0 20px; padding: 0 30px 0 20px;
position: relative; position: relative;
height: 100%; height: 100%;
line-height: 86px; line-height: 86px;
&::before{ &::before {
content: ''; content: '';
opacity: 1; opacity: 1;
width: 30px; width: 30px;
height: 100%; height: 100%;
position: absolute; position: absolute;
left: -15px; left: -15px;
background-image: linear-gradient(to right, rgba(248, 248, 248, 0.3), rgba(248, 248, 248, 1) 60% ); background-image: linear-gradient(to right, rgba(248, 248, 248, 0.3), rgba(248, 248, 248, 1) 60%);
// z-index: 99; // z-index: 99;
} }
.miconfont{ .miconfont {
font-size: 27px; font-size: 27px;
} }
} }
} }
.list{ .list {
height: calc(100vh - 440px); height: calc(100vh - 440px);
.list_num { .list_num {
font-size: $font_size_min; font-size: $font_size_min;
color:$color_font_two; color: $color_font_two;
padding: 10px 38px; padding: 10px 38px;
border-bottom: 1PX solid rgb(233, 233, 233); border-bottom: 1px solid rgb(233, 233, 233);
} }
.scroll{ .scroll {
height: 100%; height: 100%;
padding-top: 3px; padding-top: 3px;
} }
.product_list{ .product_list {
padding: 38px; padding: 38px;
display: grid; display: grid;
grid-template-columns: 321px 321px; grid-template-columns: 321px 321px;
justify-content: space-between; justify-content: space-between;
.product_item{ .product_item {
width: 321px; width: 321px;
background-color: #fff; background-color: #fff;
border-radius: 20px; border-radius: 20px;
margin-bottom: 20px; margin-bottom: 20px;
box-shadow: 0px 0px 10px 0px rgba(0,0,0,0.1) ; box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.1);
.product_img{ .product_img {
width: 100%; width: 100%;
height: 224px; height: 224px;
border-radius: 20px 20px 0px 0px; border-radius: 20px 20px 0px 0px;
position: relative; position: relative;
image{ image {
width: 100%; width: 100%;
height: 100%; height: 100%;
border-radius: 20px 20px 0px 0px; border-radius: 20px 20px 0px 0px;
} }
.color_num { .color_num {
background: rgba(0,0,0, 0.5); background: rgba(0, 0, 0, 0.5);
border-radius: 0px 50px 0px 30px; border-radius: 0px 50px 0px 30px;
font-size: $font_size_min; font-size: $font_size_min;
color: #fff; color: #fff;
position: absolute; position: absolute;
left:0; left: 0;
bottom:0; bottom: 0;
padding: 5px 20px; padding: 5px 20px;
box-sizing: border-box; box-sizing: border-box;
} }
} }
} }
.product_info{ .product_info {
padding: 20px; padding: 20px;
.title{ .title {
font-size: $font_size; font-size: $font_size;
color: $color_font_three; color: $color_font_three;
@include common_ellipsis() @include common_ellipsis();
} }
.tag_list{ .tag_list {
display: flex; display: flex;
margin-top: 16px; margin-top: 16px;
.tag{ .tag {
padding: 3px 10px; padding: 3px 10px;
background-color: #CDE5FF; background-color: #cde5ff;
font-size: $font_size_min; font-size: $font_size_min;
border-radius: 5px; border-radius: 5px;
color: $color_main; color: $color_main;
@ -202,11 +202,11 @@
} }
} }
} }
.introduce{ .introduce {
font-size: $font_size_medium; font-size: $font_size_medium;
color: $color_font_two; color: $color_font_two;
margin-top: 16px; margin-top: 16px;
@include common_ellipsis() @include common_ellipsis();
} }
} }
} }

View File

@ -1,12 +1,12 @@
.main{ .main {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
height: 100vh; height: 100vh;
background-color: #F8F8F8; background-color: #f8f8f8;
.search{ .search {
padding: 20px; padding: 20px;
} }
.filter{ .filter {
.filter_all { .filter_all {
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
@ -14,80 +14,80 @@
padding: 20px 50px; padding: 20px 50px;
font-size: $font_size_medium; font-size: $font_size_medium;
color: $color_font_three; color: $color_font_three;
.text_zh, .text_sc{ .text_zh,
.text_sc {
color: $color_main; color: $color_main;
display: flex; display: flex;
align-items: center; align-items: center;
.sortIcon{ .sortIcon {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
position: relative; position: relative;
.icon_one{ .icon_one {
font-size: $font_size_medium; font-size: $font_size_medium;
position: absolute; position: absolute;
margin:auto; margin: auto;
top:0; top: 0;
} }
} }
} }
.text_ss{ .text_ss {
position: relative; position: relative;
.miconfont{ .miconfont {
font-size: 30px; font-size: 30px;
margin-left: 5px; margin-left: 5px;
} }
&::before{ &::before {
content: ''; content: '';
width: 2px; width: 2px;
height: 32px; height: 32px;
background-color: #C2C2C2; background-color: #c2c2c2;
position: absolute; position: absolute;
top: 0; top: 0;
left: -30px; left: -30px;
} }
} }
} }
.filter_btn_con{ .filter_btn_con {
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
align-items: center; align-items: center;
height: 86px; height: 86px;
} }
.filter_scroll{ .filter_scroll {
flex:1; flex: 1;
width: 0; width: 0;
padding-left: 20px; padding-left: 20px;
::-webkit-scrollbar { ::-webkit-scrollbar {
display:none; display: none;
width:0; width: 0;
height:0; height: 0;
color:transparent; color: transparent;
} }
} }
.filter_btn{ .filter_btn {
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
padding: 20px; padding: 20px;
margin-right: 20px; margin-right: 20px;
flex:1; flex: 1;
view{ view {
font-size: $font_size_medium; font-size: $font_size_medium;
background-color: #F0F0F0; background-color: #f0f0f0;
border-radius: 24px; border-radius: 24px;
min-width: 126px; min-width: 126px;
height: 46.93px; height: 46.93px;
text-align: center; text-align: center;
line-height: 46.93px; line-height: 46.93px;
color: $color_font_three; color: $color_font_three;
&:nth-last-child(n+2) { &:nth-last-child(n + 2) {
margin-right: 10px; margin-right: 10px;
} }
&:nth-last-child(1) { &:nth-last-child(1) {
margin-right: 30px; margin-right: 30px;
} }
} }
.selected{ .selected {
background-color: #ecf5ff; background-color: #ecf5ff;
border: 2px solid #cde5ff; border: 2px solid #cde5ff;
color: $color_main; color: $color_main;
@ -95,88 +95,88 @@
height: 42.93px; height: 42.93px;
} }
} }
.filter_more{ .filter_more {
font-size: $font_size_medium; font-size: $font_size_medium;
color: $color_font_three; color: $color_font_three;
padding: 0 30px 0 20px; padding: 0 30px 0 20px;
position: relative; position: relative;
height: 100%; height: 100%;
line-height: 86px; line-height: 86px;
&::before{ &::before {
content: ''; content: '';
opacity: 1; opacity: 1;
width: 30px; width: 30px;
height: 100%; height: 100%;
position: absolute; position: absolute;
left: -15px; left: -15px;
background-image: linear-gradient(to right, rgba(248, 248, 248, 0.3), rgba(248, 248, 248, 1) 60% ); background-image: linear-gradient(to right, rgba(248, 248, 248, 0.3), rgba(248, 248, 248, 1) 60%);
// z-index: 99; // z-index: 99;
} }
.miconfont{ .miconfont {
font-size: 27px; font-size: 27px;
} }
} }
} }
.list{ .list {
height: calc(100vh - 330px); height: calc(100vh - 330px);
.list_num { .list_num {
font-size: $font_size_min; font-size: $font_size_min;
color:$color_font_two; color: $color_font_two;
padding: 10px 38px; padding: 10px 38px;
border-bottom: 1PX solid #e9e9e9; border-bottom: 1px solid #e9e9e9;
} }
.scroll{ .scroll {
height: 100%; height: 100%;
padding-top: 3px; padding-top: 3px;
} }
.product_list{ .product_list {
padding: 38px; padding: 38px;
display: grid; display: grid;
grid-template-columns: 321px 321px; grid-template-columns: 321px 321px;
justify-content: space-between; justify-content: space-between;
.product_item{ .product_item {
width: 321px; width: 321px;
background-color: #fff; background-color: #fff;
border-radius: 20px; border-radius: 20px;
margin-bottom: 20px; margin-bottom: 20px;
box-shadow: 0px 0px 10px 0px rgba(0,0,0,0.1) ; box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.1);
.product_img{ .product_img {
width: 100%; width: 100%;
height: 224px; height: 224px;
border-radius: 20px 20px 0px 0px; border-radius: 20px 20px 0px 0px;
position: relative; position: relative;
image{ image {
width: 100%; width: 100%;
height: 100%; height: 100%;
border-radius: 20px 20px 0px 0px; border-radius: 20px;
} }
.color_num { .color_num {
background: rgba(0,0,0, 0.5); background: rgba(0, 0, 0, 0.5);
border-radius: 50px 0px 0px 0px; border-radius: 50px 0px 0px 0px;
font-size: $font_size_min; font-size: $font_size_min;
color: #fff; color: #fff;
position: absolute; position: absolute;
right:0; right: 0;
bottom:0; bottom: 0;
padding: 5px 20px; padding: 5px 20px;
box-sizing: border-box; box-sizing: border-box;
} }
} }
} }
.product_info{ .product_info {
padding: 20px; padding: 20px;
.title{ .title {
font-size: $font_size; font-size: $font_size;
color: $color_font_three; color: $color_font_three;
@include common_ellipsis(); @include common_ellipsis();
} }
.tag_list{ .tag_list {
display: flex; display: flex;
margin-top: 16px; margin-top: 16px;
.tag{ .tag {
padding: 3px 10px; padding: 3px 10px;
background-color: #CDE5FF; background-color: #cde5ff;
font-size: $font_size_min; font-size: $font_size_min;
border-radius: 5px; border-radius: 5px;
color: $color_main; color: $color_main;
@ -186,7 +186,7 @@
} }
} }
} }
.introduce{ .introduce {
font-size: $font_size_medium; font-size: $font_size_medium;
color: $color_font_two; color: $color_font_two;
margin-top: 16px; margin-top: 16px;

View File

@ -1,41 +1,40 @@
import React, {useRef, useState } from "react" import React, { useRef, useState } from 'react'
import Taro from "@tarojs/taro"; import Taro from '@tarojs/taro'
import { Command } from "@/common/bluetooth/command"; import { Command } from '@/common/bluetooth/command'
import { uint8ArrayToFloat32, uint8ArrayToHex, waitFor } from "@/common/bluetooth/utils"; import { uint8ArrayToFloat32, uint8ArrayToHex, waitFor } from '@/common/bluetooth/utils'
interface params { interface params {
init: () => void init: () => void
state: Object, state: Object
startScan: () => void, startScan: () => void
measureAndGetLab: () => any, measureAndGetLab: () => any
getAdapterState: () => void, getAdapterState: () => void
connect: (any) => void, connect: (any) => void
disconnect: () => void disconnect: () => void
} }
const Context = React.createContext<params|unknown>(null) const Context = React.createContext<params | unknown>(null)
interface stateStype { interface stateStype {
listeners: any, listeners: any
discovering: boolean, discovering: boolean
available: boolean, available: boolean
connected: any, connected: any
connecting: any, connecting: any
serviceRule: any, serviceRule: any
serviceId: any, serviceId: any
characteristicRule: any, characteristicRule: any
characteristicId: any, characteristicId: any
/** 正在执行的命令 */ /** 正在执行的命令 */
command: any, command: any
responseResolve: any, responseResolve: any
responseReject: any, responseReject: any
responseTimer: any, responseTimer: any
/** 是否显示蓝牙调试信息 */ /** 是否显示蓝牙调试信息 */
debug: any, debug: any
//搜索到的设备 //搜索到的设备
devices: any, devices: any
//取色仪主动返回的数据 //取色仪主动返回的数据
deviceLab: any deviceLab: any
} }
@ -68,57 +67,56 @@ let stateObj: stateStype = {
//搜索到的设备 //搜索到的设备
devices: [], devices: [],
//取色仪主动返回的数据 //取色仪主动返回的数据
deviceLab: null deviceLab: null,
} }
export default (props) => { export default (props) => {
let refStatus = useRef(stateObj) let refStatus = useRef(stateObj)
let [state, setState] = useState(refStatus.current) let [state, setState] = useState(refStatus.current)
const changeStatus = (obj:Object): void => { const changeStatus = (obj: Object): void => {
refStatus.current = {...refStatus.current, ...obj} refStatus.current = { ...refStatus.current, ...obj }
setState({...refStatus.current}) setState({ ...refStatus.current })
} }
const init = async () => { const init = async () => {
try{ try {
await openAdapter(); await openAdapter()
}catch(e) { } catch (e) {
changeStatus({available:false}) changeStatus({ available: false })
} }
// 绑定事件通知 // 绑定事件通知
Taro.onBluetoothAdapterStateChange(res => { Taro.onBluetoothAdapterStateChange((res) => {
emit({ type: 'stateUpdate', detail: res }); emit({ type: 'stateUpdate', detail: res })
}); })
Taro.onBLEConnectionStateChange(res => { Taro.onBLEConnectionStateChange((res) => {
emit({ type: res.connected ? 'connected' : 'disconnect', detail: res }); emit({ type: res.connected ? 'connected' : 'disconnect', detail: res })
}); })
Taro.onBLECharacteristicValueChange(({ value }) => notifySubscriber(value)); Taro.onBLECharacteristicValueChange(({ value }) => notifySubscriber(value))
subscribe(async ev => { subscribe(async (ev) => {
if (ev.type === 'stateUpdate') { if (ev.type === 'stateUpdate') {
// 蓝牙状态发生的变化 // 蓝牙状态发生的变化
changeStatus({discovering:ev.detail.discovering, available:ev.detail.available}) changeStatus({ discovering: ev.detail.discovering, available: ev.detail.available })
} else if (ev.type === 'disconnect' && refStatus.current.connected && refStatus.current.connected.deviceId === ev.detail.deviceId) { } else if (ev.type === 'disconnect' && refStatus.current.connected && refStatus.current.connected.deviceId === ev.detail.deviceId) {
// 断开连接 // 断开连接
changeStatus({ changeStatus({
connected:null, connected: null,
serviceId:null, serviceId: null,
characteristicId:null, characteristicId: null,
deviceLab:null, deviceLab: null,
devices:[] devices: [],
}) })
Taro.showToast({ icon: 'none', title: '蓝牙连接已断开' }); Taro.showToast({ icon: 'none', title: '蓝牙连接已断开' })
} else if (ev.type === 'connected' && refStatus.current.connecting) { } else if (ev.type === 'connected' && refStatus.current.connecting) {
// 连接成功 // 连接成功
changeStatus({connected: refStatus.current.connecting, connecting: null}) changeStatus({ connected: refStatus.current.connecting, connecting: null })
Taro.showToast({ title: '蓝牙已连接' }); Taro.showToast({ title: '蓝牙已连接' })
} else if (ev.type === 'measure') { } else if (ev.type === 'measure') {
//监听取色仪主动推送lab //监听取色仪主动推送lab
await measureAndGetLab() await measureAndGetLab()
} }
})
});
} }
/** 打开蓝牙适配器 */ /** 打开蓝牙适配器 */
@ -126,9 +124,9 @@ export default (props) => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
Taro.openBluetoothAdapter({ Taro.openBluetoothAdapter({
success: resolve, success: resolve,
fail: reject fail: reject,
}); })
}); })
} }
/** /**
@ -136,15 +134,15 @@ export default (props) => {
* @param {{type: string; data: any}} event * @param {{type: string; data: any}} event
*/ */
const emit = (event) => { const emit = (event) => {
refStatus.current.listeners.forEach(cb => { refStatus.current.listeners.forEach((cb) => {
cb && cb(event); cb && cb(event)
}); })
} }
const subscribe = (cb) => { const subscribe = (cb) => {
if (cb) { if (cb) {
changeStatus({ changeStatus({
listeners: refStatus.current.listeners.add(cb) listeners: refStatus.current.listeners.add(cb),
}) })
} }
} }
@ -157,7 +155,7 @@ export default (props) => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
Taro.getBluetoothAdapterState({ Taro.getBluetoothAdapterState({
success: resolve, success: resolve,
fail: reject fail: reject,
}) })
}) })
} }
@ -169,33 +167,33 @@ export default (props) => {
*/ */
const startScan = (duration = 30000) => { const startScan = (duration = 30000) => {
console.log('开始寻找') console.log('开始寻找')
changeStatus({devices:[]}) changeStatus({ devices: [] })
Taro.onBluetoothDeviceFound(getDevices); Taro.onBluetoothDeviceFound(getDevices)
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
Taro.startBluetoothDevicesDiscovery({ Taro.startBluetoothDevicesDiscovery({
allowDuplicatesKey: true, allowDuplicatesKey: true,
success: resolve, success: resolve,
fail: reject fail: reject,
}); })
if (duration > 0) { if (duration > 0) {
setTimeout(() => { setTimeout(() => {
Taro.offBluetoothDeviceFound(getDevices); Taro.offBluetoothDeviceFound(getDevices)
Taro.stopBluetoothDevicesDiscovery(); Taro.stopBluetoothDevicesDiscovery()
console.log("停止搜索") console.log('停止搜索')
}, duration); }, duration)
} }
}); })
} }
//获取搜索到的设备 //获取搜索到的设备
const getDevices = (res) => { const getDevices = (res) => {
res.devices.forEach(device => { res.devices.forEach((device) => {
// 排除掉已搜索到的设备和名称不合法的设备, 将新发现的设备添加到列表中 // 排除掉已搜索到的设备和名称不合法的设备, 将新发现的设备添加到列表中
if (/^CM/.test(device.name) && !refStatus.current.devices.find(i => i.deviceId === device.deviceId)) { if (/^CM/.test(device.name) && !refStatus.current.devices.find((i) => i.deviceId === device.deviceId)) {
changeStatus({devices: [ ...refStatus.current.devices, device ]}) changeStatus({ devices: [...refStatus.current.devices, device] })
} }
}); })
} }
/** /**
@ -204,37 +202,37 @@ export default (props) => {
*/ */
const connect = async (device) => { const connect = async (device) => {
try { try {
changeStatus({connecting: device}) changeStatus({ connecting: device })
console.log('connecting::', device) console.log('connecting::', device)
await createConnection(device.deviceId); await createConnection(device.deviceId)
await discoverService(device.deviceId); await discoverService(device.deviceId)
await discoverCharacteristic(device.deviceId); await discoverCharacteristic(device.deviceId)
await notifyCharacteristicValueChange(device.deviceId); await notifyCharacteristicValueChange(device.deviceId)
} catch (e) { } catch (e) {
changeStatus({connecting: null}) changeStatus({ connecting: null })
Taro.showToast({ icon: 'none', title: '蓝牙连接失败' }); Taro.showToast({ icon: 'none', title: '蓝牙连接失败' })
throw e; throw e
} }
} }
/** 断开当前连接的设备 */ /** 断开当前连接的设备 */
const disconnect = async () => { const disconnect = async () => {
if (!refStatus.current.connected && !refStatus.current.connecting) return; if (!refStatus.current.connected && !refStatus.current.connecting) return
if (refStatus.current.connected) { if (refStatus.current.connected) {
await closeConnection(refStatus.current.connected.deviceId); await closeConnection(refStatus.current.connected.deviceId)
resetCommand(); resetCommand()
changeStatus({ changeStatus({
connected: null, connected: null,
serviceId: null, serviceId: null,
characteristicId: null, characteristicId: null,
devices: [], devices: [],
deviceLab: null deviceLab: null,
}) })
} }
if (refStatus.current.connecting) { if (refStatus.current.connecting) {
await closeConnection(refStatus.current.connecting.deviceId); await closeConnection(refStatus.current.connecting.deviceId)
changeStatus({connecting:null}) changeStatus({ connecting: null })
} }
} }
@ -245,9 +243,9 @@ export default (props) => {
deviceId, deviceId,
timeout: 2000, timeout: 2000,
success: resolve, success: resolve,
fail: reject fail: reject,
}); })
}); })
} }
/** 关闭 BLE 连接 */ /** 关闭 BLE 连接 */
@ -256,9 +254,9 @@ export default (props) => {
Taro.closeBLEConnection({ Taro.closeBLEConnection({
deviceId, deviceId,
success: resolve, success: resolve,
fail: reject fail: reject,
}); })
}); })
} }
/** 搜索服务 */ /** 搜索服务 */
@ -267,17 +265,17 @@ export default (props) => {
Taro.getBLEDeviceServices({ Taro.getBLEDeviceServices({
deviceId, deviceId,
success: ({ services }) => { success: ({ services }) => {
const service = services.find(i => refStatus.current.serviceRule.test(i.uuid)); const service = services.find((i) => refStatus.current.serviceRule.test(i.uuid))
if (!service) { if (!service) {
reject(new Error('服务不可用')); reject(new Error('服务不可用'))
} else { } else {
changeStatus({serviceId: service.uuid}) changeStatus({ serviceId: service.uuid })
resolve(service); resolve(service)
} }
}, },
fail: reject fail: reject,
}); })
}); })
} }
/** 搜索特征 */ /** 搜索特征 */
@ -287,17 +285,17 @@ export default (props) => {
deviceId, deviceId,
serviceId: refStatus.current.serviceId, serviceId: refStatus.current.serviceId,
success: ({ characteristics }) => { success: ({ characteristics }) => {
const characteristic = characteristics.find(i => refStatus.current.characteristicRule.test(i.uuid)); const characteristic = characteristics.find((i) => refStatus.current.characteristicRule.test(i.uuid))
if (!characteristic) { if (!characteristic) {
reject(new Error('特征不可用')); reject(new Error('特征不可用'))
} else { } else {
changeStatus({characteristicId: characteristic.uuid}) changeStatus({ characteristicId: characteristic.uuid })
resolve(characteristic); resolve(characteristic)
} }
}, },
fail: reject fail: reject,
})
}) })
});
} }
/** 启动特征通知 */ /** 启动特征通知 */
@ -307,11 +305,11 @@ export default (props) => {
deviceId, deviceId,
serviceId: refStatus.current.serviceId, serviceId: refStatus.current.serviceId,
characteristicId: refStatus.current.characteristicId, characteristicId: refStatus.current.characteristicId,
state:stateParm, state: stateParm,
success: resolve, success: resolve,
fail: reject fail: reject,
}); })
}); })
} }
/** /**
@ -321,22 +319,22 @@ export default (props) => {
function notifySubscriber(buffer) { function notifySubscriber(buffer) {
if (refStatus.current.command) { if (refStatus.current.command) {
if (refStatus.current.debug) { if (refStatus.current.debug) {
console.log(`[BLE RESP] ${uint8ArrayToHex(new Uint8Array(buffer))}`); console.log(`[BLE RESP] ${uint8ArrayToHex(new Uint8Array(buffer))}`)
} }
refStatus.current.command.fillResponse(buffer); refStatus.current.command.fillResponse(buffer)
if (refStatus.current.command.isComplete) { if (refStatus.current.command.isComplete) {
if (refStatus.current.command.isValid && refStatus.current.responseResolve) { if (refStatus.current.command.isValid && refStatus.current.responseResolve) {
refStatus.current.responseResolve(refStatus.current.command.response); refStatus.current.responseResolve(refStatus.current.command.response)
} else if (!refStatus.current.command.isValid) { } else if (!refStatus.current.command.isValid) {
refStatus.current.responseReject(new Error('无效数据')); refStatus.current.responseReject(new Error('无效数据'))
} }
resetCommand(); resetCommand()
} }
} else { } else {
const uint8Array = new Uint8Array(buffer); const uint8Array = new Uint8Array(buffer)
if (uint8Array[0] === 0xbb && uint8Array[1] === 1 && uint8Array[3] === 0) { if (uint8Array[0] === 0xbb && uint8Array[1] === 1 && uint8Array[3] === 0) {
const ev = { type: 'measure', detail: { mode: uint8Array[2] } }; const ev = { type: 'measure', detail: { mode: uint8Array[2] } }
emit(ev); emit(ev)
} }
} }
} }
@ -349,32 +347,31 @@ export default (props) => {
function exec(command) { function exec(command) {
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {
if (refStatus.current.command) { if (refStatus.current.command) {
reject(new Error('正在执行其他命令')); reject(new Error('正在执行其他命令'))
} else { } else {
try { try {
refStatus.current.command = command; refStatus.current.command = command
const data = command.data; const data = command.data
for (let i = 0; i < data.length; i++) { for (let i = 0; i < data.length; i++) {
await sendData(data[i]); await sendData(data[i])
} }
if (command.responseSize <= 0) { if (command.responseSize <= 0) {
resolve(true); resolve(true)
resetCommand(); resetCommand()
} else { } else {
refStatus.current.responseReject = reject; refStatus.current.responseReject = reject
refStatus.current.responseResolve = resolve; refStatus.current.responseResolve = resolve
refStatus.current.responseTimer = setTimeout(() => { refStatus.current.responseTimer = setTimeout(() => {
reject(new Error('命令响应超时')); reject(new Error('命令响应超时'))
resetCommand(); resetCommand()
}, command.timeout); }, command.timeout)
} }
} catch (e) { } catch (e) {
reject(e); reject(e)
} }
} }
})
});
} }
/** /**
@ -383,30 +380,30 @@ export default (props) => {
*/ */
function sendData(buffer) { function sendData(buffer) {
if (refStatus.current.debug) { if (refStatus.current.debug) {
console.log(`[BLE SEND] ${uint8ArrayToHex(new Uint8Array(buffer))}`); console.log(`[BLE SEND] ${uint8ArrayToHex(new Uint8Array(buffer))}`)
} }
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
console.log('current:::',refStatus.current) console.log('current:::', refStatus.current)
Taro.writeBLECharacteristicValue({ Taro.writeBLECharacteristicValue({
deviceId: refStatus.current.connected.deviceId, deviceId: refStatus.current.connected.deviceId,
serviceId: refStatus.current.serviceId, serviceId: refStatus.current.serviceId,
characteristicId: refStatus.current.characteristicId, characteristicId: refStatus.current.characteristicId,
value: buffer, value: buffer,
success: resolve, success: resolve,
fail: reject fail: reject,
})
}) })
});
} }
function resetCommand() { function resetCommand() {
if (refStatus.current.responseTimer) { if (refStatus.current.responseTimer) {
clearTimeout(refStatus.current.responseTimer); clearTimeout(refStatus.current.responseTimer)
} }
changeStatus({ changeStatus({
command: null, command: null,
responseResolve: null, responseResolve: null,
responseReject: null, responseReject: null,
responseTimer: null responseTimer: null,
}) })
} }
@ -415,13 +412,13 @@ export default (props) => {
* @param {number} mode * @param {number} mode
* @returns {Promise} * @returns {Promise}
*/ */
async function measure (mode = 0) { async function measure(mode = 0) {
console.log('current1:::',Command.WakeUp) console.log('current1:::', Command.WakeUp)
await exec(Command.WakeUp); await exec(Command.WakeUp)
console.log('current2:::',Command.WakeUp) console.log('current2:::', Command.WakeUp)
await waitFor(50); await waitFor(50)
console.log('current3:::',Command.WakeUp) console.log('current3:::', Command.WakeUp)
return await exec(Command.measure(mode)); return await exec(Command.measure(mode))
} }
/** /**
@ -430,14 +427,14 @@ export default (props) => {
* @returns {Promise<{ L: number, a: number, b: number }>} * @returns {Promise<{ L: number, a: number, b: number }>}
*/ */
async function getLab(mode = 0) { async function getLab(mode = 0) {
await exec(Command.WakeUp); await exec(Command.WakeUp)
await waitFor(50); await waitFor(50)
const data: any = await exec(Command.getLab(mode)); const data: any = await exec(Command.getLab(mode))
return { return {
L: uint8ArrayToFloat32(data.slice(5, 9)), L: uint8ArrayToFloat32(data.slice(5, 9)),
a: uint8ArrayToFloat32(data.slice(9, 13)), a: uint8ArrayToFloat32(data.slice(9, 13)),
b: uint8ArrayToFloat32(data.slice(13, 17)), b: uint8ArrayToFloat32(data.slice(13, 17)),
}; }
} }
/** /**
@ -446,32 +443,35 @@ export default (props) => {
* @returns {Promise<{L: number, a: number, b: number}>} * @returns {Promise<{L: number, a: number, b: number}>}
*/ */
async function measureAndGetLab(mode = 0) { async function measureAndGetLab(mode = 0) {
await measure(mode); await measure(mode)
await waitFor(50); await waitFor(50)
const lab = await getLab(mode); const lab = await getLab(mode)
console.log('lab2::',lab) console.log('lab2::', lab)
changeStatus({deviceLab:lab}) changeStatus({ deviceLab: lab })
return lab return lab
} }
return <Context.Provider children={props.children} value={{ return (
<Context.Provider
children={props.children}
value={{
init, init,
state, state,
startScan, startScan,
measureAndGetLab, measureAndGetLab,
getAdapterState, getAdapterState,
connect, connect,
disconnect disconnect,
}} /> }}
/>
)
} }
export const useBluetoothTwo = () => { export const useBluetoothTwo = () => {
const res = React.useContext<any>(Context) const res = React.useContext<any>(Context)
if(res) { if (res) {
return {...res} return { ...res }
} else { } else {
return {} return {}
} }
} }

View File

@ -1,41 +1,40 @@
import React, {useRef, useState } from "react" import React, { useRef, useState } from 'react'
import Taro from "@tarojs/taro"; import Taro from '@tarojs/taro'
import { Command } from "@/common/bluetooth/command"; import { Command } from '@/common/bluetooth/command'
import { uint8ArrayToFloat32, uint8ArrayToHex, waitFor } from "@/common/bluetooth/utils"; import { uint8ArrayToFloat32, uint8ArrayToHex, waitFor } from '@/common/bluetooth/utils'
interface params { interface params {
init: () => void init: () => void
state: Object, state: Object
startScan: () => void, startScan: () => void
measureAndGetLab: () => any, measureAndGetLab: () => any
getAdapterState: () => void, getAdapterState: () => void
connect: (any) => void, connect: (any) => void
disconnect: () => void disconnect: () => void
} }
const Context = React.createContext<params|unknown>(null) const Context = React.createContext<params | unknown>(null)
interface stateStype { interface stateStype {
listeners: any, listeners: any
discovering: boolean, discovering: boolean
available: boolean, available: boolean
connected: any, connected: any
connecting: any, connecting: any
serviceRule: any, serviceRule: any
serviceId: any, serviceId: any
characteristicRule: any, characteristicRule: any
characteristicId: any, characteristicId: any
/** 正在执行的命令 */ /** 正在执行的命令 */
command: any, command: any
responseResolve: any, responseResolve: any
responseReject: any, responseReject: any
responseTimer: any, responseTimer: any
/** 是否显示蓝牙调试信息 */ /** 是否显示蓝牙调试信息 */
debug: any, debug: any
//搜索到的设备 //搜索到的设备
devices: any, devices: any
//取色仪主动返回的数据 //取色仪主动返回的数据
deviceLab: any deviceLab: any
} }
@ -68,57 +67,56 @@ let stateObj: stateStype = {
//搜索到的设备 //搜索到的设备
devices: [], devices: [],
//取色仪主动返回的数据 //取色仪主动返回的数据
deviceLab: null deviceLab: null,
} }
export default (props) => { export default (props) => {
let refStatus = useRef(stateObj) let refStatus = useRef(stateObj)
let [state, setState] = useState(refStatus.current) let [state, setState] = useState(refStatus.current)
const changeStatus = (obj:Object): void => { const changeStatus = (obj: Object): void => {
refStatus.current = {...refStatus.current, ...obj} refStatus.current = { ...refStatus.current, ...obj }
setState({...refStatus.current}) setState({ ...refStatus.current })
} }
const init = async () => { const init = async () => {
try{ try {
await openAdapter(); await openAdapter()
}catch(e) { } catch (e) {
changeStatus({available:false}) changeStatus({ available: false })
} }
// 绑定事件通知 // 绑定事件通知
Taro.onBluetoothAdapterStateChange(res => { Taro.onBluetoothAdapterStateChange((res) => {
emit({ type: 'stateUpdate', detail: res }); emit({ type: 'stateUpdate', detail: res })
}); })
Taro.onBLEConnectionStateChange(res => { Taro.onBLEConnectionStateChange((res) => {
emit({ type: res.connected ? 'connected' : 'disconnect', detail: res }); emit({ type: res.connected ? 'connected' : 'disconnect', detail: res })
}); })
Taro.onBLECharacteristicValueChange(({ value }) => notifySubscriber(value)); Taro.onBLECharacteristicValueChange(({ value }) => notifySubscriber(value))
subscribe(async ev => { subscribe(async (ev) => {
if (ev.type === 'stateUpdate') { if (ev.type === 'stateUpdate') {
// 蓝牙状态发生的变化 // 蓝牙状态发生的变化
changeStatus({discovering:ev.detail.discovering, available:ev.detail.available}) changeStatus({ discovering: ev.detail.discovering, available: ev.detail.available })
} else if (ev.type === 'disconnect' && refStatus.current.connected && refStatus.current.connected.deviceId === ev.detail.deviceId) { } else if (ev.type === 'disconnect' && refStatus.current.connected && refStatus.current.connected.deviceId === ev.detail.deviceId) {
// 断开连接 // 断开连接
changeStatus({ changeStatus({
connected:null, connected: null,
serviceId:null, serviceId: null,
characteristicId:null, characteristicId: null,
deviceLab:null, deviceLab: null,
devices:[] devices: [],
}) })
Taro.showToast({ icon: 'none', title: '蓝牙连接已断开' }); Taro.showToast({ icon: 'none', title: '蓝牙连接已断开' })
} else if (ev.type === 'connected' && refStatus.current.connecting) { } else if (ev.type === 'connected' && refStatus.current.connecting) {
// 连接成功 // 连接成功
changeStatus({connected: refStatus.current.connecting, connecting: null}) changeStatus({ connected: refStatus.current.connecting, connecting: null })
Taro.showToast({ title: '蓝牙已连接' }); Taro.showToast({ title: '蓝牙已连接' })
} else if (ev.type === 'measure') { } else if (ev.type === 'measure') {
//监听取色仪主动推送lab //监听取色仪主动推送lab
await measureAndGetLab() await measureAndGetLab()
} }
})
});
} }
/** 打开蓝牙适配器 */ /** 打开蓝牙适配器 */
@ -126,9 +124,9 @@ export default (props) => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
Taro.openBluetoothAdapter({ Taro.openBluetoothAdapter({
success: resolve, success: resolve,
fail: reject fail: reject,
}); })
}); })
} }
/** /**
@ -136,15 +134,15 @@ export default (props) => {
* @param {{type: string; data: any}} event * @param {{type: string; data: any}} event
*/ */
const emit = (event) => { const emit = (event) => {
refStatus.current.listeners.forEach(cb => { refStatus.current.listeners.forEach((cb) => {
cb && cb(event); cb && cb(event)
}); })
} }
const subscribe = (cb) => { const subscribe = (cb) => {
if (cb) { if (cb) {
changeStatus({ changeStatus({
listeners: refStatus.current.listeners.add(cb) listeners: refStatus.current.listeners.add(cb),
}) })
} }
} }
@ -157,7 +155,7 @@ export default (props) => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
Taro.getBluetoothAdapterState({ Taro.getBluetoothAdapterState({
success: resolve, success: resolve,
fail: reject fail: reject,
}) })
}) })
} }
@ -169,33 +167,33 @@ export default (props) => {
*/ */
const startScan = (duration = 30000) => { const startScan = (duration = 30000) => {
console.log('开始寻找') console.log('开始寻找')
changeStatus({devices:[]}) changeStatus({ devices: [] })
Taro.onBluetoothDeviceFound(getDevices); Taro.onBluetoothDeviceFound(getDevices)
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
Taro.startBluetoothDevicesDiscovery({ Taro.startBluetoothDevicesDiscovery({
allowDuplicatesKey: true, allowDuplicatesKey: true,
success: resolve, success: resolve,
fail: reject fail: reject,
}); })
if (duration > 0) { if (duration > 0) {
setTimeout(() => { setTimeout(() => {
Taro.offBluetoothDeviceFound(getDevices); Taro.offBluetoothDeviceFound(getDevices)
Taro.stopBluetoothDevicesDiscovery(); Taro.stopBluetoothDevicesDiscovery()
console.log("停止搜索") console.log('停止搜索')
}, duration); }, duration)
} }
}); })
} }
//获取搜索到的设备 //获取搜索到的设备
const getDevices = (res) => { const getDevices = (res) => {
res.devices.forEach(device => { res.devices.forEach((device) => {
// 排除掉已搜索到的设备和名称不合法的设备, 将新发现的设备添加到列表中 // 排除掉已搜索到的设备和名称不合法的设备, 将新发现的设备添加到列表中
if (/^CM/.test(device.name) && !refStatus.current.devices.find(i => i.deviceId === device.deviceId)) { if (/^CM/.test(device.name) && !refStatus.current.devices.find((i) => i.deviceId === device.deviceId)) {
changeStatus({devices: [ ...refStatus.current.devices, device ]}) changeStatus({ devices: [...refStatus.current.devices, device] })
} }
}); })
} }
/** /**
@ -204,37 +202,37 @@ export default (props) => {
*/ */
const connect = async (device) => { const connect = async (device) => {
try { try {
changeStatus({connecting: device}) changeStatus({ connecting: device })
console.log('connecting::', device) console.log('connecting::', device)
await createConnection(device.deviceId); await createConnection(device.deviceId)
await discoverService(device.deviceId); await discoverService(device.deviceId)
await discoverCharacteristic(device.deviceId); await discoverCharacteristic(device.deviceId)
await notifyCharacteristicValueChange(device.deviceId); await notifyCharacteristicValueChange(device.deviceId)
} catch (e) { } catch (e) {
changeStatus({connecting: null}) changeStatus({ connecting: null })
Taro.showToast({ icon: 'none', title: '蓝牙连接失败' }); Taro.showToast({ icon: 'none', title: '蓝牙连接失败' })
throw e; throw e
} }
} }
/** 断开当前连接的设备 */ /** 断开当前连接的设备 */
const disconnect = async () => { const disconnect = async () => {
if (!refStatus.current.connected && !refStatus.current.connecting) return; if (!refStatus.current.connected && !refStatus.current.connecting) return
if (refStatus.current.connected) { if (refStatus.current.connected) {
await closeConnection(refStatus.current.connected.deviceId); await closeConnection(refStatus.current.connected.deviceId)
resetCommand(); resetCommand()
changeStatus({ changeStatus({
connected: null, connected: null,
serviceId: null, serviceId: null,
characteristicId: null, characteristicId: null,
devices: [], devices: [],
deviceLab: null deviceLab: null,
}) })
} }
if (refStatus.current.connecting) { if (refStatus.current.connecting) {
await closeConnection(refStatus.current.connecting.deviceId); await closeConnection(refStatus.current.connecting.deviceId)
changeStatus({connecting:null}) changeStatus({ connecting: null })
} }
} }
@ -245,9 +243,9 @@ export default (props) => {
deviceId, deviceId,
timeout: 2000, timeout: 2000,
success: resolve, success: resolve,
fail: reject fail: reject,
}); })
}); })
} }
/** 关闭 BLE 连接 */ /** 关闭 BLE 连接 */
@ -256,9 +254,9 @@ export default (props) => {
Taro.closeBLEConnection({ Taro.closeBLEConnection({
deviceId, deviceId,
success: resolve, success: resolve,
fail: reject fail: reject,
}); })
}); })
} }
/** 搜索服务 */ /** 搜索服务 */
@ -267,17 +265,17 @@ export default (props) => {
Taro.getBLEDeviceServices({ Taro.getBLEDeviceServices({
deviceId, deviceId,
success: ({ services }) => { success: ({ services }) => {
const service = services.find(i => refStatus.current.serviceRule.test(i.uuid)); const service = services.find((i) => refStatus.current.serviceRule.test(i.uuid))
if (!service) { if (!service) {
reject(new Error('服务不可用')); reject(new Error('服务不可用'))
} else { } else {
changeStatus({serviceId: service.uuid}) changeStatus({ serviceId: service.uuid })
resolve(service); resolve(service)
} }
}, },
fail: reject fail: reject,
}); })
}); })
} }
/** 搜索特征 */ /** 搜索特征 */
@ -287,17 +285,17 @@ export default (props) => {
deviceId, deviceId,
serviceId: refStatus.current.serviceId, serviceId: refStatus.current.serviceId,
success: ({ characteristics }) => { success: ({ characteristics }) => {
const characteristic = characteristics.find(i => refStatus.current.characteristicRule.test(i.uuid)); const characteristic = characteristics.find((i) => refStatus.current.characteristicRule.test(i.uuid))
if (!characteristic) { if (!characteristic) {
reject(new Error('特征不可用')); reject(new Error('特征不可用'))
} else { } else {
changeStatus({characteristicId: characteristic.uuid}) changeStatus({ characteristicId: characteristic.uuid })
resolve(characteristic); resolve(characteristic)
} }
}, },
fail: reject fail: reject,
})
}) })
});
} }
/** 启动特征通知 */ /** 启动特征通知 */
@ -307,11 +305,11 @@ export default (props) => {
deviceId, deviceId,
serviceId: refStatus.current.serviceId, serviceId: refStatus.current.serviceId,
characteristicId: refStatus.current.characteristicId, characteristicId: refStatus.current.characteristicId,
state:stateParm, state: stateParm,
success: resolve, success: resolve,
fail: reject fail: reject,
}); })
}); })
} }
/** /**
@ -321,22 +319,22 @@ export default (props) => {
function notifySubscriber(buffer) { function notifySubscriber(buffer) {
if (refStatus.current.command) { if (refStatus.current.command) {
if (refStatus.current.debug) { if (refStatus.current.debug) {
console.log(`[BLE RESP] ${uint8ArrayToHex(new Uint8Array(buffer))}`); console.log(`[BLE RESP] ${uint8ArrayToHex(new Uint8Array(buffer))}`)
} }
refStatus.current.command.fillResponse(buffer); refStatus.current.command.fillResponse(buffer)
if (refStatus.current.command.isComplete) { if (refStatus.current.command.isComplete) {
if (refStatus.current.command.isValid && refStatus.current.responseResolve) { if (refStatus.current.command.isValid && refStatus.current.responseResolve) {
refStatus.current.responseResolve(refStatus.current.command.response); refStatus.current.responseResolve(refStatus.current.command.response)
} else if (!refStatus.current.command.isValid) { } else if (!refStatus.current.command.isValid) {
refStatus.current.responseReject(new Error('无效数据')); refStatus.current.responseReject(new Error('无效数据'))
} }
resetCommand(); resetCommand()
} }
} else { } else {
const uint8Array = new Uint8Array(buffer); const uint8Array = new Uint8Array(buffer)
if (uint8Array[0] === 0xbb && uint8Array[1] === 1 && uint8Array[3] === 0) { if (uint8Array[0] === 0xbb && uint8Array[1] === 1 && uint8Array[3] === 0) {
const ev = { type: 'measure', detail: { mode: uint8Array[2] } }; const ev = { type: 'measure', detail: { mode: uint8Array[2] } }
emit(ev); emit(ev)
} }
} }
} }
@ -349,32 +347,31 @@ export default (props) => {
function exec(command) { function exec(command) {
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {
if (refStatus.current.command) { if (refStatus.current.command) {
reject(new Error('正在执行其他命令')); reject(new Error('正在执行其他命令'))
} else { } else {
try { try {
refStatus.current.command = command; refStatus.current.command = command
const data = command.data; const data = command.data
for (let i = 0; i < data.length; i++) { for (let i = 0; i < data.length; i++) {
await sendData(data[i]); await sendData(data[i])
} }
if (command.responseSize <= 0) { if (command.responseSize <= 0) {
resolve(true); resolve(true)
resetCommand(); resetCommand()
} else { } else {
refStatus.current.responseReject = reject; refStatus.current.responseReject = reject
refStatus.current.responseResolve = resolve; refStatus.current.responseResolve = resolve
refStatus.current.responseTimer = setTimeout(() => { refStatus.current.responseTimer = setTimeout(() => {
reject(new Error('命令响应超时')); reject(new Error('命令响应超时'))
resetCommand(); resetCommand()
}, command.timeout); }, command.timeout)
} }
} catch (e) { } catch (e) {
reject(e); reject(e)
} }
} }
})
});
} }
/** /**
@ -383,30 +380,30 @@ export default (props) => {
*/ */
function sendData(buffer) { function sendData(buffer) {
if (refStatus.current.debug) { if (refStatus.current.debug) {
console.log(`[BLE SEND] ${uint8ArrayToHex(new Uint8Array(buffer))}`); console.log(`[BLE SEND] ${uint8ArrayToHex(new Uint8Array(buffer))}`)
} }
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
console.log('current:::',refStatus.current) console.log('current:::', refStatus.current)
Taro.writeBLECharacteristicValue({ Taro.writeBLECharacteristicValue({
deviceId: refStatus.current.connected.deviceId, deviceId: refStatus.current.connected.deviceId,
serviceId: refStatus.current.serviceId, serviceId: refStatus.current.serviceId,
characteristicId: refStatus.current.characteristicId, characteristicId: refStatus.current.characteristicId,
value: buffer, value: buffer,
success: resolve, success: resolve,
fail: reject fail: reject,
})
}) })
});
} }
function resetCommand() { function resetCommand() {
if (refStatus.current.responseTimer) { if (refStatus.current.responseTimer) {
clearTimeout(refStatus.current.responseTimer); clearTimeout(refStatus.current.responseTimer)
} }
changeStatus({ changeStatus({
command: null, command: null,
responseResolve: null, responseResolve: null,
responseReject: null, responseReject: null,
responseTimer: null responseTimer: null,
}) })
} }
@ -415,13 +412,13 @@ export default (props) => {
* @param {number} mode * @param {number} mode
* @returns {Promise} * @returns {Promise}
*/ */
async function measure (mode = 0) { async function measure(mode = 0) {
console.log('current1:::',Command.WakeUp) console.log('current1:::', Command.WakeUp)
await exec(Command.WakeUp); await exec(Command.WakeUp)
console.log('current2:::',Command.WakeUp) console.log('current2:::', Command.WakeUp)
await waitFor(50); await waitFor(50)
console.log('current3:::',Command.WakeUp) console.log('current3:::', Command.WakeUp)
return await exec(Command.measure(mode)); return await exec(Command.measure(mode))
} }
/** /**
@ -430,14 +427,14 @@ export default (props) => {
* @returns {Promise<{ L: number, a: number, b: number }>} * @returns {Promise<{ L: number, a: number, b: number }>}
*/ */
async function getLab(mode = 0) { async function getLab(mode = 0) {
await exec(Command.WakeUp); await exec(Command.WakeUp)
await waitFor(50); await waitFor(50)
const data: any = await exec(Command.getLab(mode)); const data: any = await exec(Command.getLab(mode))
return { return {
L: uint8ArrayToFloat32(data.slice(5, 9)), L: uint8ArrayToFloat32(data.slice(5, 9)),
a: uint8ArrayToFloat32(data.slice(9, 13)), a: uint8ArrayToFloat32(data.slice(9, 13)),
b: uint8ArrayToFloat32(data.slice(13, 17)), b: uint8ArrayToFloat32(data.slice(13, 17)),
}; }
} }
/** /**
@ -446,32 +443,35 @@ export default (props) => {
* @returns {Promise<{L: number, a: number, b: number}>} * @returns {Promise<{L: number, a: number, b: number}>}
*/ */
async function measureAndGetLab(mode = 0) { async function measureAndGetLab(mode = 0) {
await measure(mode); await measure(mode)
await waitFor(50); await waitFor(50)
const lab = await getLab(mode); const lab = await getLab(mode)
console.log('lab2::',lab) console.log('lab2::', lab)
changeStatus({deviceLab:lab}) changeStatus({ deviceLab: lab })
return lab return lab
} }
return <Context.Provider children={props.children} value={{ return (
<Context.Provider
children={props.children}
value={{
init, init,
state, state,
startScan, startScan,
measureAndGetLab, measureAndGetLab,
getAdapterState, getAdapterState,
connect, connect,
disconnect disconnect,
}} /> }}
/>
)
} }
export const useBluetooth = () => { export const useBluetooth = () => {
const res = React.useContext<any>(Context) const res = React.useContext<any>(Context)
if(res) { if (res) {
return {...res} return { ...res }
} else { } else {
return {} return {}
} }
} }

View File

@ -1,19 +1,32 @@
import { alert } from "@/common/common"; import { alert } from '@/common/common'
import Taro from "@tarojs/taro"; import Taro from '@tarojs/taro'
import { memo, useCallback, useState } from "react"; import { memo, useCallback, useState } from 'react'
type Scope = 'scope.userLocation'|'scope.userLocation'|'scope.record'|'scope.camera'|'scope.bluetooth'|'scope.writePhotosAlbum'|'scope.addPhoneContact'|'scope.addPhoneCalendar'|'scope.werun'|'scope.address'|'scope.invoiceTitle'|'scope.invoice'|'scope.userInfo' type Scope =
| 'scope.userLocation'
| 'scope.userLocation'
| 'scope.record'
| 'scope.camera'
| 'scope.bluetooth'
| 'scope.writePhotosAlbum'
| 'scope.addPhoneContact'
| 'scope.addPhoneCalendar'
| 'scope.werun'
| 'scope.address'
| 'scope.invoiceTitle'
| 'scope.invoice'
| 'scope.userInfo'
type Param = { type Param = {
scope: Scope, scope: Scope
msg: string //检查不通过时警告 msg: string //检查不通过时警告
} }
export default ({scope, msg}: Param) => { export default ({ scope, msg }: Param) => {
//这个hook微信授权检查授权 //这个hook微信授权检查授权
const check = useCallback(() => { const check = useCallback(() => {
return new Promise((reslove, reject) => { return new Promise((reslove, reject) => {
Taro.getSetting({ Taro.getSetting({
success: (res) => { success: (res) => {
if(res.authSetting[scope]) { if (res.authSetting[scope]) {
reslove(true) reslove(true)
} else if (res.authSetting[scope] === undefined) { } else if (res.authSetting[scope] === undefined) {
Taro.authorize({ Taro.authorize({
@ -24,28 +37,26 @@ export default ({scope, msg}: Param) => {
fail() { fail() {
alert.none(msg) alert.none(msg)
reject(false) reject(false)
} },
}) })
} else { } else {
Taro.openSetting({ Taro.openSetting({
success(res) { success(res) {
if(res.authSetting[scope]) { if (res.authSetting[scope]) {
reslove(true) reslove(true)
} else { } else {
alert.none(msg) alert.none(msg)
reject(false) reject(false)
} }
} },
}) })
} }
} },
}) })
}) })
}, [scope]) }, [scope])
return { return {
check, check,
} }
} }

View File

@ -1,7 +1,7 @@
import { SubscriptionMessageApi } from "@/api/user" import { SubscriptionMessageApi } from '@/api/user'
import Taro from "@tarojs/taro" import Taro from '@tarojs/taro'
import dayjs from "dayjs" import dayjs from 'dayjs'
import { useEffect, useRef, useState } from "react" import { useEffect, useRef, useState } from 'react'
//倒计时hook //倒计时hook
export const useTimeCountDown = () => { export const useTimeCountDown = () => {
@ -9,15 +9,15 @@ export const useTimeCountDown = () => {
DD: '', DD: '',
HH: '', HH: '',
MM: '', MM: '',
SS: '' SS: '',
}) })
const [timeStatus, setTimeStatus] = useState<0|1|2>(0) //倒计时状体 0:倒计时未开始 1:倒计时中, 2倒计时已结束 const [timeStatus, setTimeStatus] = useState<0 | 1 | 2>(0) //倒计时状体 0:倒计时未开始 1:倒计时中, 2倒计时已结束
const timeObj:any = useRef() const timeObj: any = useRef()
const endTime = useRef('') const endTime = useRef('')
const onStart = (val = '') => { const onStart = (val = '') => {
console.log('time:::', val) console.log('time:::', val)
endTime.current = val endTime.current = val
if(endTime.current) { if (endTime.current) {
clearInterval(timeObj.current) clearInterval(timeObj.current)
timeObj.current = setInterval(() => { timeObj.current = setInterval(() => {
count_down() count_down()
@ -30,54 +30,53 @@ export const useTimeCountDown = () => {
} }
}, []) }, [])
const count_down = () => { const count_down = () => {
var startData = dayjs(); var startData = dayjs()
var endDate = dayjs(endTime.current); var endDate = dayjs(endTime.current)
setTimeStatus(() => 1) setTimeStatus(() => 1)
if(startData >= endDate) { if (startData >= endDate) {
clearInterval(timeObj.current) clearInterval(timeObj.current)
setShowTime((e) => ({...e, DD:'00', HH:'00', MM:'00', SS:'00'})) setShowTime((e) => ({ ...e, DD: '00', HH: '00', MM: '00', SS: '00' }))
setTimeStatus(() => 2) setTimeStatus(() => 2)
return false return false
} }
var _dd = endDate.diff(startData,'day'); var _dd = endDate.diff(startData, 'day')
var _hh = endDate.diff(startData,'hour'); var _hh = endDate.diff(startData, 'hour')
var _mm = endDate.diff(startData,'minute'); var _mm = endDate.diff(startData, 'minute')
var _ss = endDate.diff(startData,'second'); var _ss = endDate.diff(startData, 'second')
// 转换 // 转换
var hh = _hh - (_dd*24); var hh = _hh - _dd * 24
var mm = _mm - (_hh*60); var mm = _mm - _hh * 60
var ss = _ss - (_mm*60); var ss = _ss - _mm * 60
// 格式化 // 格式化
var DD = ('00'+_dd).slice(-2); var DD = ('00' + _dd).slice(-2)
var HH = ('00'+hh).slice(-2); var HH = ('00' + hh).slice(-2)
var MM = ('00'+mm).slice(-2); var MM = ('00' + mm).slice(-2)
var SS = ('00'+ss).slice(-2); var SS = ('00' + ss).slice(-2)
console.log('endTime::', `${DD}-${HH}-${MM}-${SS}`) console.log('endTime::', `${DD}-${HH}-${MM}-${SS}`)
setShowTime((e) => ({...e, DD, HH, MM, SS})) setShowTime((e) => ({ ...e, DD, HH, MM, SS }))
} }
return { return {
showTime, showTime,
onStart, onStart,
timeStatus timeStatus,
} }
} }
//订阅消息hook //订阅消息hook
export const UseSubscriptionMessage = () => { export const UseSubscriptionMessage = () => {
const {fetchData: fetchDataMessage} = SubscriptionMessageApi() const { fetchData: fetchDataMessage } = SubscriptionMessageApi()
const openSubscriptionMessage = ({orderId = 0, scenes = 0}:{orderId?: number, scenes: number}) => { const openSubscriptionMessage = ({ orderId = 0, scenes = 0 }: { orderId?: number; scenes: number }) => {
return new Promise(async (resolve) => { return new Promise(async (resolve) => {
let params:{sale_order_id?: number, scenes?: number} = {} let params: { sale_order_id?: number; scenes?: number } = {}
orderId&&(params.sale_order_id = orderId) orderId && (params.sale_order_id = orderId)
params.scenes = scenes params.scenes = scenes
let res = await fetchDataMessage(params) let res = await fetchDataMessage(params)
if(res.success&&res.data.TemplateID&&res.data.TemplateID.length > 0) { if (res.success && res.data.TemplateID && res.data.TemplateID.length > 0) {
Taro.requestSubscribeMessage({ Taro.requestSubscribeMessage({
tmplIds: res.data.TemplateID, tmplIds: res.data.TemplateID,
complete: function (res) { complete: function (res) {
resolve(res) resolve(res)
} },
}) })
} else { } else {
resolve(true) resolve(true)
@ -86,7 +85,6 @@ export const UseSubscriptionMessage = () => {
} }
return { return {
openSubscriptionMessage openSubscriptionMessage,
} }
} }

View File

@ -1,26 +1,26 @@
import { useDispatch } from 'react-redux' import { useDispatch } from 'react-redux'
import {SET_SHOPCOUNT, CLEAR_SHOPCOUNT} from '@/constants/common' import { SET_SHOPCOUNT, CLEAR_SHOPCOUNT } from '@/constants/common'
import {DataParam} from '@/reducers/commonData' import { DataParam } from '@/reducers/commonData'
import { useCallback, useState } from 'react' import { useCallback, useState } from 'react'
import { GetShoppingCartApi } from '@/api/shopCart' import { GetShoppingCartApi } from '@/api/shopCart'
import { useSelector } from '@/reducers/hooks' import { useSelector } from '@/reducers/hooks'
export default () => { export default () => {
const commonData = useSelector(state => state.commonData) const commonData = useSelector((state) => state.commonData)
const dispatch = useDispatch() const dispatch = useDispatch()
const setShopCount = (shopCount: number) => { const setShopCount = (shopCount: number) => {
dispatch({type:SET_SHOPCOUNT, data:{shopCount}}) dispatch({ type: SET_SHOPCOUNT, data: { shopCount } })
} }
const removeShopCount = () => { const removeShopCount = () => {
dispatch({type:CLEAR_SHOPCOUNT}) dispatch({ type: CLEAR_SHOPCOUNT })
} }
const {fetchData: fetchDataShopCount} = GetShoppingCartApi() const { fetchData: fetchDataShopCount } = GetShoppingCartApi()
const getShopCount = async () => { const getShopCount = async () => {
//获取购物车数据数量 //获取购物车数据数量
const {data} = await fetchDataShopCount() const { data } = await fetchDataShopCount()
let color_list = data.color_list||[] let color_list = data.color_list || []
setShopCount(color_list.length) setShopCount(color_list.length)
} }
@ -28,6 +28,6 @@ export default () => {
setShopCount, setShopCount,
removeShopCount, removeShopCount,
getShopCount, getShopCount,
commonData commonData,
} }
} }

View File

@ -1,42 +1,39 @@
import Taro, { useRouter } from '@tarojs/taro' import Taro, { useRouter } from '@tarojs/taro'
import { useEffect, useRef, useState } from 'react' import { useEffect, useRef, useState } from 'react'
import {BASE_URL, WX_APPID} from '@/common/constant' import { BASE_URL, WX_APPID } from '@/common/constant'
import useUserInfo from "./useUserInfo" import useUserInfo from './useUserInfo'
import qs from 'qs'; import qs from 'qs'
import useLogin from './useLogin'; import useLogin from './useLogin'
import useLoginRequest from './useLoginRequest'; import useLoginRequest from './useLoginRequest'
type Params = { type Params = {
code: string|null code: string | null
success: true|false success: true | false
data: any, data: any
msg: string, msg: string
loading: true|false, loading: true | false
error: any, error: any
query: any, query: any
filter: any, filter: any
sort: any, sort: any
total: number, total: number
multiple: true|false, // 请求多次 multiple: true | false // 请求多次
count: number, // 第几次请求 count: number // 第几次请求
token: string, // token token: string // token
page?: number, page?: number
pageSize?: number pageSize?: number
} }
type option = { type option = {
url?: string, url?: string
method?: 'get'|'post'|'put'|'delete', method?: 'get' | 'post' | 'put' | 'delete'
type?: string, type?: string
data?: any, data?: any
page?: number, page?: number
pageSize?: number, pageSize?: number
pagination?: true|false, pagination?: true | false
base_url?: string, base_url?: string
apiMsgStatus?: true|false apiMsgStatus?: true | false
} }
/** /**
@ -94,7 +91,8 @@ const showStatus = (status) => {
* @param {Object} options.data * @param {Object} options.data
* @returns {Object} fetch(), loading, error, code, msg * @returns {Object} fetch(), loading, error, code, msg
*/ */
export const useRequest = (options:option = { export const useRequest = (
options: option = {
url: '/', url: '/',
method: 'get', method: 'get',
type: 'json', type: 'json',
@ -103,11 +101,11 @@ export const useRequest = (options:option = {
pageSize: 24, pageSize: 24,
pagination: false, // 是否分页 pagination: false, // 是否分页
base_url: '', base_url: '',
apiMsgStatus: true //是否直接弹出后端错误 apiMsgStatus: true, //是否直接弹出后端错误
}) => { },
) => {
options.url = `${options.base_url||BASE_URL}${options.url}` options.url = `${options.base_url || BASE_URL}${options.url}`
let params:Params = { let params: Params = {
code: null, // 业务码 code: null, // 业务码
success: false, // 请求是否成功 success: false, // 请求是否成功
data: {}, data: {},
@ -123,23 +121,23 @@ export const useRequest = (options:option = {
token: '', // token token: '', // token
} }
const stateRef = useRef({...params}) const stateRef = useRef({ ...params })
const [state, setState] = useState({...stateRef.current}) const [state, setState] = useState({ ...stateRef.current })
const {removeToken, removeSessionKey, removeUserInfo} = useUserInfo() const { removeToken, removeSessionKey, removeUserInfo } = useUserInfo()
const {login} = useLoginRequest() const { login } = useLoginRequest()
// 请求函数 // 请求函数
const fetchData = async (sub_options?:any) => { const fetchData = async (sub_options?: any) => {
stateRef.current.loading = true stateRef.current.loading = true
setState((e) => ({...e, loading:true})) setState((e) => ({ ...e, loading: true }))
stateRef.current.query = { stateRef.current.query = {
...sub_options, ...sub_options,
...options.pagination && { ...(options.pagination && {
page: stateRef.current.page, page: stateRef.current.page,
size: stateRef.current.pageSize, size: stateRef.current.pageSize,
}, }),
...stateRef.current.filter, ...stateRef.current.filter,
...stateRef.current.sort ...stateRef.current.sort,
} }
try { try {
let token = Taro.getStorageSync('token') let token = Taro.getStorageSync('token')
@ -147,39 +145,37 @@ export const useRequest = (options:option = {
...options, ...options,
...{ ...{
header: { header: {
"Platform": 6, Platform: 6,
"Appid": WX_APPID, Appid: WX_APPID,
"Authorization": token || stateRef.current.token, Authorization: token || stateRef.current.token,
}
}, },
...options.method?.toUpperCase() == 'GET' ? { },
data: stateRef.current.query ...(options.method?.toUpperCase() == 'GET'
} : { ? {
data: options.type?.toUpperCase() == 'FORMDATA' ? qs.stringify(stateRef.current.query) : stateRef.current.query data: stateRef.current.query,
} }
: {
data: options.type?.toUpperCase() == 'FORMDATA' ? qs.stringify(stateRef.current.query) : stateRef.current.query,
}),
} }
const result = await Taro.request(q as any) const result = await Taro.request(q as any)
const { statusCode } = result const { statusCode } = result
const { const { code, msg, data } = result.data
code,
msg,
data
} = result.data
if (statusCode === 200) { if (statusCode === 200) {
stateRef.current.success = (code === 0 ? true : false) stateRef.current.success = code === 0 ? true : false
stateRef.current.code = code stateRef.current.code = code
stateRef.current.msg = msg stateRef.current.msg = msg
stateRef.current.data = data stateRef.current.data = data
stateRef.current.total = data?.list ? data?.total : 0 stateRef.current.total = data?.list ? data?.total : 0
if(code !== 0) { if (code !== 0) {
options.apiMsgStatus !== false &&Taro.showToast({ options.apiMsgStatus !== false &&
Taro.showToast({
title: `${msg}`, title: `${msg}`,
icon: 'none' icon: 'none',
}) })
console.log('错误::',msg) console.log('错误::', msg)
} }
}else{ } else {
if (statusCode === 401) { if (statusCode === 401) {
removeToken() removeToken()
removeSessionKey() removeSessionKey()
@ -188,21 +184,19 @@ export const useRequest = (options:option = {
} else { } else {
Taro.showToast({ Taro.showToast({
title: `错误:${showStatus(statusCode)}`, title: `错误:${showStatus(statusCode)}`,
icon: 'none' icon: 'none',
}) })
} }
} }
} catch (e) { } catch (e) {
stateRef.current.success = false stateRef.current.success = false
stateRef.current.error = true stateRef.current.error = true
stateRef.current.msg = e.errMsg stateRef.current.msg = e.errMsg
console.log('后台错误信息::',e.errMsg) console.log('后台错误信息::', e.errMsg)
} }
stateRef.current.error = false stateRef.current.error = false
stateRef.current.loading = false stateRef.current.loading = false
setState(() => ({...stateRef.current})) setState(() => ({ ...stateRef.current }))
return stateRef.current return stateRef.current
} }
@ -210,5 +204,4 @@ export const useRequest = (options:option = {
fetchData, fetchData,
state, state,
} }
} }

View File

@ -1,44 +1,44 @@
import useUserInfo from "./useUserInfo" import useUserInfo from './useUserInfo'
import Taro, { useDidShow, useRouter } from "@tarojs/taro" import Taro, { useDidShow, useRouter } from '@tarojs/taro'
import { GetWxUserInfoApi, GetAdminUserInfoApi, GetPhoneNumberApi, BindingCompanyApi } from "@/api/user" import { GetWxUserInfoApi, GetAdminUserInfoApi, GetPhoneNumberApi, BindingCompanyApi } from '@/api/user'
import useLoginRequest from "./useLoginRequest" import useLoginRequest from './useLoginRequest'
import { SHARE_SCENE } from "@/common/enum" import { SHARE_SCENE } from '@/common/enum'
import { GetShortCodeApi } from "@/api/share" import { GetShortCodeApi } from '@/api/share'
import { alert } from "@/common/common" import { alert } from '@/common/common'
import { LoginApi } from "@/api/login" import { LoginApi } from '@/api/login'
import { IMG_CND_Prefix } from "@/common/constant" import { IMG_CND_Prefix } from '@/common/constant'
export default () => { export default () => {
const {setUserInfo, setAdminUserInfo, setSortCode, userInfo} = useUserInfo() const { setUserInfo, setAdminUserInfo, setSortCode, userInfo } = useUserInfo()
useDidShow(() => { useDidShow(() => {
checkLogin() checkLogin()
}) })
//登录请求 //登录请求
const {login} = useLoginRequest() const { login } = useLoginRequest()
// const {fetchData:login} = LoginApi() // const {fetchData:login} = LoginApi()
const wxLogin = async () => { const wxLogin = async () => {
try { try {
await login() await login()
getAdminUserInfo() getAdminUserInfo()
} catch(e) { } catch (e) {
console.log('登录失败::',e) console.log('登录失败::', e)
} }
} }
//获取用户信息 //获取用户信息
const {fetchData: useFetchData} = GetAdminUserInfoApi() const { fetchData: useFetchData } = GetAdminUserInfoApi()
const getAdminUserInfo = async () => { const getAdminUserInfo = async () => {
let res = await useFetchData() let res = await useFetchData()
setAdminUserInfo({...res.data}) setAdminUserInfo({ ...res.data })
getShortCode(res.data.user_id) getShortCode(res.data.user_id)
} }
//登录加checkLogin检查 //登录加checkLogin检查
const checkLogin = () => { const checkLogin = () => {
return new Promise( async (reslove) => { return new Promise(async (reslove) => {
if(!userInfo.token) { if (!userInfo.token) {
await wxLogin() await wxLogin()
reslove(true) reslove(true)
} else { } else {
@ -58,17 +58,17 @@ export default () => {
} }
//获取用户头像等信息数据 //获取用户头像等信息数据
const {fetchData: fetchDataUserInfo} = GetWxUserInfoApi() const { fetchData: fetchDataUserInfo } = GetWxUserInfoApi()
const getSelfUserInfo = async () => { const getSelfUserInfo = async () => {
return new Promise((reslove, reject) => { return new Promise((reslove, reject) => {
if(userInfo.adminUserInfo?.is_authorize_name) { if (userInfo.adminUserInfo?.is_authorize_name) {
reslove(true) reslove(true)
return true return true
} }
Taro.getUserProfile({ Taro.getUserProfile({
desc: '用于完善会员资料', desc: '用于完善会员资料',
success: async (res) => { success: async (res) => {
if(!userInfo.session_key) { if (!userInfo.session_key) {
await wxLogin() await wxLogin()
} }
const user_res = await fetchDataUserInfo({ const user_res = await fetchDataUserInfo({
@ -76,54 +76,51 @@ export default () => {
raw_data: res.rawData, raw_data: res.rawData,
signature: res.signature, signature: res.signature,
encrypted_data: res.encryptedData, encrypted_data: res.encryptedData,
iv: res.iv iv: res.iv,
}) })
if(user_res.success) { if (user_res.success) {
setUserInfo({...user_res.data}) setUserInfo({ ...user_res.data })
getAdminUserInfo() getAdminUserInfo()
reslove(true) reslove(true)
} else { } else {
reject(user_res.msg) reject(user_res.msg)
} }
}, },
fail:(e) => { fail: (e) => {
console.log('授权失败::',e) console.log('授权失败::', e)
reject(e.errMsg) reject(e.errMsg)
} },
}) })
}) })
} }
//获取手机号码 //获取手机号码
const {fetchData: fetchDataUserPhone} = GetPhoneNumberApi() const { fetchData: fetchDataUserPhone } = GetPhoneNumberApi()
const {fetchData: fetchBindingCompany} = BindingCompanyApi() const { fetchData: fetchBindingCompany } = BindingCompanyApi()
const getPhoneNumber = (code) => { const getPhoneNumber = (code) => {
return new Promise( async (reslove, reject) => { return new Promise(async (reslove, reject) => {
if(userInfo.adminUserInfo?.is_authorize_phone) { if (userInfo.adminUserInfo?.is_authorize_phone) {
reslove(true) reslove(true)
return true return true
} }
const res = await fetchDataUserPhone({code}) const res = await fetchDataUserPhone({ code })
if(res.success) { if (res.success) {
setUserInfo({...userInfo.userInfo, phone:res.data.phone_number}) setUserInfo({ ...userInfo.userInfo, phone: res.data.phone_number })
await fetchBindingCompany() await fetchBindingCompany()
getAdminUserInfo() getAdminUserInfo()
reslove(res.data) reslove(res.data)
} else { } else {
reject(res.msg) reject(res.msg)
} }
}) })
} }
//获取分享码(右上角分享码) //获取分享码(右上角分享码)
const {SharePage} = SHARE_SCENE const { SharePage } = SHARE_SCENE
const {fetchData: fetchDataShortCode} = GetShortCodeApi() const { fetchData: fetchDataShortCode } = GetShortCodeApi()
const getShortCode = async (user_id) => { const getShortCode = async (user_id) => {
const {data: resPage} = await fetchDataShortCode({"share_user_id": user_id, type:SharePage.value}) const { data: resPage } = await fetchDataShortCode({ share_user_id: user_id, type: SharePage.value })
setSortCode({...userInfo.sort_code, shareShortPage: {title: '打造面料爆品 专注客户服务', code: resPage.md5_key, img:IMG_CND_Prefix + '/mall/share_img_01.png'}}) setSortCode({ ...userInfo.sort_code, shareShortPage: { title: '打造面料爆品 专注客户服务', code: resPage.md5_key, img: IMG_CND_Prefix + '/mall/share_img_01.png' } })
} }
return { return {
@ -132,6 +129,6 @@ export default () => {
getSelfUserInfo, getSelfUserInfo,
getPhoneNumber, getPhoneNumber,
userInfo, userInfo,
getAdminUserInfo getAdminUserInfo,
} }
} }

View File

@ -1,12 +1,9 @@
import Taro from '@tarojs/taro'; import Taro from '@tarojs/taro'
import {UPLOAD_CDN_URL } from '@/common/constant' import { UPLOAD_CDN_URL } from '@/common/constant'
import { GetSignApi } from '@/api/cdn' import { GetSignApi } from '@/api/cdn'
export default () => { export default () => {
const { fetchData: GetSign, state } = GetSignApi()
const { fetchData: GetSign, state} = GetSignApi()
// 上传图片 获取authPolicy // 上传图片 获取authPolicy
/* /*
@ -15,12 +12,11 @@ export default () => {
*/ */
const getSecret = (scene, type) => { const getSecret = (scene, type) => {
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {
const SAVE_PATH = `/${scene}/{filemd5}{day}{hour}{min}{sec}{.suffix}`
const SAVE_PATH = `/${scene}/{filemd5}{day}{hour}{min}{sec}{.suffix}`;
let params = { let params = {
'method': 'post', method: 'post',
'save_key': SAVE_PATH save_key: SAVE_PATH,
} }
// 获取签名 // 获取签名
let res = await GetSign(params) let res = await GetSign(params)
@ -29,23 +25,22 @@ export default () => {
} else { } else {
reject({ reject({
code: res.code || '9999', code: res.code || '9999',
msg: res.msg msg: res.msg,
}); })
} }
}) })
} }
const getFileType = (name) => { const getFileType = (name) => {
if (!name) return false; if (!name) return false
var imgType = ["gif", "jpeg", "jpg", "bmp", "png"]; var imgType = ['gif', 'jpeg', 'jpg', 'bmp', 'png']
var videoType = ["avi", "wmv", "mkv", "mp4", "mov", "rm", "3gp", "flv", "mpg", "rmvb", "quicktime"]; var videoType = ['avi', 'wmv', 'mkv', 'mp4', 'mov', 'rm', '3gp', 'flv', 'mpg', 'rmvb', 'quicktime']
if (RegExp("\.?(" + imgType.join("|") + ")$", "i").test(name.toLowerCase())) { if (RegExp('.?(' + imgType.join('|') + ')$', 'i').test(name.toLowerCase())) {
return 'image'; return 'image'
} else if (RegExp("\.(" + videoType.join("|") + ")$", "i").test(name.toLowerCase())) { } else if (RegExp('.(' + videoType.join('|') + ')$', 'i').test(name.toLowerCase())) {
return 'video'; return 'video'
} else { } else {
return false; return false
} }
} }
@ -58,24 +53,24 @@ export default () => {
*/ */
const uploadCDNImg = (file, secene, type) => { const uploadCDNImg = (file, secene, type) => {
let filetype = file.path let filetype = file.path
console.log('filetype::',filetype) console.log('filetype::', filetype)
if (!getFileType(filetype)) { if (!getFileType(filetype)) {
Taro.showToast({ Taro.showToast({
title: "上传文件类型错误", title: '上传文件类型错误',
icon: "none", icon: 'none',
duration: 3800 duration: 3800,
}) })
return false return false
} }
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
getSecret(secene, type) getSecret(secene, type)
.then(result => { .then((result) => {
let res:any = result let res: any = result
console.log('bucket', res.bucket); console.log('bucket', res.bucket)
var formdata = { var formdata = {
'authorization': res.authorization, authorization: res.authorization,
'policy': res.policy, policy: res.policy,
} }
const uploadTask = Taro.uploadFile({ const uploadTask = Taro.uploadFile({
@ -83,43 +78,42 @@ export default () => {
formData: formdata, formData: formdata,
filePath: file.path, filePath: file.path,
name: 'file', name: 'file',
success: res => { success: (res) => {
resolve(JSON.parse(`${res.data}`)) resolve(JSON.parse(`${res.data}`))
}, },
fail: err => { fail: (err) => {
console.log(err) console.log(err)
reject(err) reject(err)
} },
}) })
uploadTask.progress(res => { uploadTask.progress((res) => {
console.log('上传进度', res.progress); console.log('上传进度', res.progress)
if (res.progress < 100) { if (res.progress < 100) {
Taro.showLoading({ Taro.showLoading({
title: '上传中...' title: '上传中...',
}) })
} else { } else {
Taro.hideLoading() Taro.hideLoading()
} }
}) })
}) })
.catch(result => { .catch((result) => {
reject(result) reject(result)
Taro.showToast({ Taro.showToast({
title: "获取密钥失败!", title: '获取密钥失败!',
icon: "none", icon: 'none',
duration: 3800 duration: 3800,
}) })
}) })
}) })
} }
// product 产品相关,图片、纹理图等 全平台 // product 产品相关,图片、纹理图等 全平台
// after-sale 售后(申请退货、退款)相关的、图片、视频 全平台 // after-sale 售后(申请退货、退款)相关的、图片、视频 全平台
// mall 电子商城相关的 全平台 // mall 电子商城相关的 全平台
// logistics 物流(发货、提货)相关的、图片、视频 全平台 // logistics 物流(发货、提货)相关的、图片、视频 全平台
type cdn_upload_type_Param = 'product'|'after-sale'|'mall'|'logistics' type cdn_upload_type_Param = 'product' | 'after-sale' | 'mall' | 'logistics'
/** /**
* *
* @param cdn_upload_type * @param cdn_upload_type
@ -128,15 +122,15 @@ export default () => {
*/ */
const getWxPhoto = (cdn_upload_type: cdn_upload_type_Param, count: number = 1) => { const getWxPhoto = (cdn_upload_type: cdn_upload_type_Param, count: number = 1) => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let list:any[] = [] let list: any[] = []
Taro.chooseImage({ Taro.chooseImage({
count: count, count: count,
sizeType: ['original', 'compressed'], sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'], sourceType: ['album', 'camera'],
success: async function (res) { success: async function (res) {
try { try {
if(count > 1) { if (count > 1) {
for(let i = 0; i < res.tempFiles.length; i++) { for (let i = 0; i < res.tempFiles.length; i++) {
let data = await uploadCDNImg(res.tempFiles[i], cdn_upload_type, cdn_upload_type) let data = await uploadCDNImg(res.tempFiles[i], cdn_upload_type, cdn_upload_type)
list.push(data) list.push(data)
} }
@ -146,20 +140,16 @@ export default () => {
let data = await uploadCDNImg(res.tempFiles[0], cdn_upload_type, cdn_upload_type) let data = await uploadCDNImg(res.tempFiles[0], cdn_upload_type, cdn_upload_type)
resolve(data) resolve(data)
} }
} catch (res) {
} catch(res) {
reject(res) reject(res)
} }
},
}
}) })
}) })
} }
return { return {
uploadCDNImg, uploadCDNImg,
getWxPhoto getWxPhoto,
} }
} }

View File

@ -1,40 +1,40 @@
import { useDispatch, useSelector } from 'react-redux' import { useDispatch, useSelector } from 'react-redux'
import { CLEAR_SESSIONKEY, SET_USERINFO, SET_TOKEN, SET_SESSIONKEY, CLEAR_USERINFO, CLEAR_TOKEN, SET_ADMINUSERINFO, SET_SORTCODE} from '@/constants/userInfo' import { CLEAR_SESSIONKEY, SET_USERINFO, SET_TOKEN, SET_SESSIONKEY, CLEAR_USERINFO, CLEAR_TOKEN, SET_ADMINUSERINFO, SET_SORTCODE } from '@/constants/userInfo'
import {DataParam, UserParam, UserAdminParam, SortCodeParam} from '@/reducers/userInfo' import { DataParam, UserParam, UserAdminParam, SortCodeParam } from '@/reducers/userInfo'
export default () => { export default () => {
const userInfo = useSelector((state:DataParam) => state.userInfo) as DataParam const userInfo = useSelector((state: DataParam) => state.userInfo) as DataParam
const dispatch = useDispatch() const dispatch = useDispatch()
const setToken = (token: string) => { const setToken = (token: string) => {
dispatch({type:SET_TOKEN, data:{token}}) dispatch({ type: SET_TOKEN, data: { token } })
} }
const setSessionKey = (sessionkey: string) => { const setSessionKey = (sessionkey: string) => {
dispatch({type:SET_SESSIONKEY, data:{session_key: sessionkey}}) dispatch({ type: SET_SESSIONKEY, data: { session_key: sessionkey } })
} }
const setUserInfo = (userInfo: UserParam) => { const setUserInfo = (userInfo: UserParam) => {
dispatch({type:SET_USERINFO, data:{userInfo}}) dispatch({ type: SET_USERINFO, data: { userInfo } })
} }
const setAdminUserInfo = (adminUserInfo: UserAdminParam) => { const setAdminUserInfo = (adminUserInfo: UserAdminParam) => {
dispatch({type:SET_ADMINUSERINFO, data:{adminUserInfo}}) dispatch({ type: SET_ADMINUSERINFO, data: { adminUserInfo } })
} }
const setSortCode = (sortCode:SortCodeParam) => { const setSortCode = (sortCode: SortCodeParam) => {
dispatch({type:SET_SORTCODE, data:{sort_code:sortCode}}) dispatch({ type: SET_SORTCODE, data: { sort_code: sortCode } })
} }
const removeUserInfo = () => { const removeUserInfo = () => {
dispatch({type:CLEAR_USERINFO}) dispatch({ type: CLEAR_USERINFO })
} }
const removeToken = () => { const removeToken = () => {
dispatch({type:CLEAR_TOKEN}) dispatch({ type: CLEAR_TOKEN })
} }
const removeSessionKey = () => { const removeSessionKey = () => {
dispatch({type:CLEAR_SESSIONKEY}) dispatch({ type: CLEAR_SESSIONKEY })
} }
return { return {