ts_aimz/pages/index/index.js

629 lines
21 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// index.js
import ProjectService from '../../net/api/projectApi'
import UserApi from '../../net/api/userApi'
import {
previewUrl,
copyrightUrl
} from '../../net/http'
const Cache = require('../../utils/storage')
const Utils = require('../../utils/util')
const data =require('../../utils/data')
const app = getApp()
const deviceInfo = wx.getDeviceInfo()
const screenInfo = wx.getWindowInfo();
const statusBarHeight = screenInfo.statusBarHeight; // 状态栏高度
const navBarHeight = deviceInfo.platform == 'IOS' ? 48 : 50; // 导航栏高度iOS 为 44pxAndroid 为 48px
const tabBarHeight = screenInfo.screenHeight - (screenInfo.safeArea ? screenInfo.safeArea.bottom : 50);
const screenHeight = screenInfo.screenHeight
const screenWidth = screenInfo.screenWidth
const windowHeight = screenInfo.windowHeight - navBarHeight - statusBarHeight; //可用内容高度
Page({
data: {
indexPage: true,
needRefresh: false, //是否需要刷新
imgAssets: app.globalData.imgAssetsUrl,
localAssets: app.globalData.localAssets,
appTitle: app.globalData.appTitle,
statusBarHeight: statusBarHeight,
menuRight: 0,
hasMsg: false,
navBarHeight: navBarHeight,
totalHeight: navBarHeight, // 导航栏总高度
contentHeight: windowHeight,
screenHeight: screenHeight, //屏幕高度
screenWidth: screenWidth, //屏幕宽度
tabBarHeight: tabBarHeight, //tabbar高度
tagList: [],
currentTag: '',
imgUrl: previewUrl,
typeList: [{
value: 'FREE',
label: '免费试用'
},
{
value: 'MATERIAL',
label: '写材料'
},
{
value: 'ALL',
label: '全托管'
},
],
currentType: '',
expandList: [{
value: 'PKG',
label: '安装包'
},
{
value: 'VIDEO_DEMO',
label: '演示视频'
},
{
value: 'URGENT',
label: '加急'
},
],
currentExpand: '',
currentStatus: 'PROCESSING', //默认状态 PROCESSING进行中 COMPLETE完成
listLoading: 'loading', //loading 状态
listRefreshTrig: false, //是否正在刷新
pageData: {
page: 1,
rows: 10
},
projectList: [], //项目列表
noticeContent: '',
defaultNotice: '用AI创造用平台保护——欢迎来到您的著作权守护站!',
showDownload: false,
sysPreviewUrl: '',
tempItem: null,
errorHint: '',
showError: false,
successHint: '',
showSuccess: false, //
downloadProgress: 0, //下载文件进度
downloading: false, //下载文件中
isLoadMore: false, //是否正在加载更多中
hasMore: true, //是否有更多数据
showAd: false, //显示优惠卷广告
tempCoupons: [], //优惠卷
isNoShowToday: false, //今日不再显示
tabList: data.tabList,
},
onLoad(e) {
const _self = this
//获取通知
_self.doGetNotice()
//获取标签选项
_self.doGetTagList()
//获取列表
const params = _self.buildParams(1, true)
_self.doGetSelfList(params, true)
const noShowToday = Cache.get('noShowToday')
const currentDate = new Date().toLocaleDateString();
if (noShowToday && noShowToday === currentDate) {
this.setData({
isNoShowToday: true
});
} else {
_self.doGetClaimsCoupons()
}
this.countViewHeight()
this.getMineInfo()
//设置通知图标
const rect = wx.getMenuButtonBoundingClientRect()
this.setData({
menuRight: rect.width + 5
})
//获取消息通知
// this.getMsgNotice()
},
//消息通知
getMsgNotice() {
const data = {
page: 1,
rows: 1,
isRead: 0,
keywords: ''
}
const _self = this
UserApi.doGetMineMsgNotice(data)
.then(res => {
console.log(res)
if (res.rows && res.rows.length > 0) {
_self.setData({
'tabList[2].hasMsg': true
})
} else {
_self.setData({
'tabList[2].hasMsg': false
})
}
})
.catch(err => {
_self.setData({
'tabList[2].hasMsg': false
})
})
},
//获取我的个人信息
getMineInfo() {
UserApi.doGetMineAccount()
.then(res => {
Cache.set('userId', res.userId)
})
.catch(err => {
console.log(err)
})
},
onShow() {
const pages = getCurrentPages();
const currentPage = pages[pages.length - 1];
const tabList = this.data.tabList;
tabList.forEach(item => {
item.selected = item.pagePath === currentPage.route;
});
this.setData({
tabList
});
this.getMsgNotice()
if (this.data.needRefresh) {
this.setData({
needRefresh: false
})
this.doRefreshList()
}
},
//计算剩余高度
countViewHeight() {
const query = wx.createSelectorQuery();
const _self = this
// 指定要查询的 view 元素
query.select('#title-box').boundingClientRect();
query.exec((res) => {
if (res[0]) {
const height = res[0].height;
//屏幕高度-内容高度-tabbar高度
const contentHeight = _self.data.screenHeight - height - 50
const h = Utils.pxToRpx(contentHeight, _self.data.screenWidth)
const tempH = h - 130
_self.setData({
contentHeight: tempH
})
} else {
console.log('未找到指定的 view 元素');
}
})
},
//获取可以申领的优惠卷
doGetClaimsCoupons() {
const _self = this
UserApi.doGetClaimsCouponsList()
.then(res => {
if (res && res.length > 0) {
_self.setData({
tempCoupons: res,
showAd: true
})
}
}, err => {
console.log(err)
})
},
//创建项目
createCopy() {
wx.navigateTo({
url: '/pages/copyright/createBuy/createBuy',
})
},
//充值
goPayment() {
wx.navigateTo({
url: '/pages/copyright/payment/payment',
})
},
//切换状态
doChangeStatus(e) {
this.setData({
currentStatus: e.currentTarget.dataset.value
})
const params = this.buildParams(1, true)
this.doGetSelfList(params, true)
},
//切换类型
doChangeType(e) {
const _self = this
if (_self.data.currentType == e.currentTarget.dataset.value) {
_self.setData({
currentType: ''
})
} else {
_self.setData({
currentType: e.currentTarget.dataset.value
})
}
const params = _self.buildParams(1, true)
_self.doGetSelfList(params, true)
},
//切换附加
doChangeExpand(e) {
const _self = this
if (_self.data.currentExpand == e.currentTarget.dataset.value) {
_self.setData({
currentExpand: ''
})
} else {
this.setData({
currentExpand: e.currentTarget.dataset.value
})
}
const params = _self.buildParams(1, true)
_self.doGetSelfList(params, true)
},
//切换标签
doChangeTag(e) {
const _self = this
if (_self.data.currentTag == e.currentTarget.dataset.value) {
_self.setData({
currentTag: ''
})
} else {
_self.setData({
currentTag: e.currentTarget.dataset.value
})
}
const params = _self.buildParams(1, true)
_self.doGetSelfList(params, true)
},
//构建请求参数
buildParams(page, isRefresh) {
const _self = this
_self.setData({
projectList: isRefresh ? [] : _self.data.projectList,
'pageData.page': page
})
const [part1, part2] = _self.data.currentTag.split(':')
const params = {
page: _self.data.pageData.page,
rows: _self.data.pageData.rows,
tagNot: part2 ? part2 : '',
tagDataId: part1,
chargeType: _self.data.currentType, //
chargeAdditionals: _self.data.currentExpand, //额外附加
status: _self.data.currentStatus, //当前项目状态
}
return params
},
//刷新列表
doRefreshList() {
console.log('正在刷新...')
const _self = this
_self.setData({
listRefreshTrig: true,
listLoading: 'loading'
})
const params = _self.buildParams(1, true)
_self.doGetSelfList(params, true)
},
//获取通知
doGetNotice() {
const _self = this
ProjectService.doGetNotice()
.then(res => {
console.log(res)
_self.setData({
noticeContent: res.data && res.data != '' ? res.data : _self.data.defaultNotice
})
}, err => {
console.log(err)
})
},
//获取标签
doGetTagList() {
const _self = this
ProjectService.doGetTagList()
.then(res => {
_self.setData({
tagList: res
})
}, err => {
console.log(err)
})
},
doOpenCreate() {
wx.navigateTo({
url: '/pages/copyright/createBuy/createBuy',
})
},
//获取项目列表
doGetSelfList(params, isRefresh) {
const _self = this
_self.setData({
listLoading: isRefresh ? 'loading' : ''
})
ProjectService.doGetSelfProjectList(params)
.then(res => {
console.log(res)
var status = 'success'
status = res.rows && res.rows.length > 0 ? 'success' : 'create'
const list = _self.addPrefixToPreviewImgs(res.rows)
_self.setData({
listLoading: isRefresh ? status : '',
projectList: _self.data.projectList.concat(list),
listRefreshTrig: false,
isLoadMore: false
})
console.log(_self.data.projectList.length < res.total)
_self.setData({
hasMore: _self.data.projectList.length < res.total
})
}, err => {
_self.setData({
listLoading: 'error',
listRefreshTrig: false,
isLoadMore: false,
hasMore: true
})
})
},
//为列表图片添加前缀
addPrefixToPreviewImgs(data) {
const prefix = this.data.imgUrl;
return data.map(item => {
const aiStatuses = Object.values(item.aiSetting)
const genderStatus = item.generate.generateStatus
// 状态判断函数
// const isGenerating = () => genderStatus === 'GENERATING' || aiStatuses.includes('GENERATING');
const isGenerating = () => genderStatus === 'GENERATING' || aiStatuses.indexOf('GENERATING') !== -1;
const isSuccess = () => aiStatuses.every(s => s === 'SUCCESS') && genderStatus === 'SUCCESS';
const shouldRegenerate = () => genderStatus === 'FAILED';
// 主逻辑
if (isGenerating()) {
item.btnStatus = 'GENERATING'
} else if (isSuccess()) {
item.btnStatus = 'DOWNLOAD'
} else if (!aiStatuses.every(s => s === 'SUCCESS')) {
item.btnStatus = 'AIGEN'
} else if (shouldRegenerate()) {
item.btnStatus = 'RELOAD'
} else {
item.btnStatus = 'GEN'
}
if (item.codeTypePage && item.codeTypePage.previewImgs) {
const imgIds = item.codeTypePage.previewImgs.split(',');
item.codeTypePage.previewImgs = imgIds.map(id => prefix + id);
}
return item;
});
},
//显示下载
doShowDownload(e) {
const item = e.currentTarget.dataset.value
const _self = this
this.setData({
showDownload: true,
sysPreviewUrl: `${copyrightUrl}/${item.previewUrl}`,
tempItem: item
})
},
//下载
download(e) {
const _self = this
_self.setData({
downloadProgress: 0,
downloading: true, //显示下载进度
showDownload: false, //关闭底部弹窗
})
const path = e.currentTarget.dataset.path
const url = copyrightUrl + path + _self.data.tempItem.projId
console.log(url)
const token = Cache.get('token')
const header = {}
if (token) {
header.Auth = `Bearer ${token}`;
}
const downloadTask = wx.downloadFile({
url: url,
header: header,
success(res) {
console.log('下载成功', res)
_self.setData({
downloadProgress: 0,
downloading: false
})
if (res.statusCode === 200) {
_self.setData({
successHint: '下载成功',
showSuccess: true
})
// 从响应头中获取文件名
const contentDisposition = res.header['Content-Disposition'];
let fileName = '';
if (contentDisposition) {
const match = contentDisposition.match(/filename=(.*)/);
if (match && match[1]) {
fileName = match[1].replace(/['"]/g, '');
}
}
if (fileName) {
// 保存文件时使用获取到的文件名
wx.getFileSystemManager().saveFile({
tempFilePath: res.tempFilePath,
filePath: wx.env.USER_DATA_PATH + '/' + fileName,
success: function (res) {
const savedFilePath = res.savedFilePath;
console.log('文件下载并保存成功', savedFilePath);
if (savedFilePath.endsWith(".txt")) {
wx.navigateTo({
url: '/pages/readTxt/readTxt?filePath=' + savedFilePath,
})
} else {
wx.openDocument({
filePath: savedFilePath,
showMenu: true
})
}
},
fail: function (err) {
console.error('文件保存失败', err);
_self.showErr('很抱歉,文件下载出现问题。建议您稍作等待,之后再尝试下载。')
}
})
} else {
console.error('未从响应头中获取到文件名');
_self.showErr('很抱歉,文件下载出现问题。建议您稍作等待,之后再尝试下载。')
}
} else {
_self.showErr('很抱歉,文件下载出现问题。建议您稍作等待,之后再尝试下载。')
}
},
fail(err) {
_self.showErr('很抱歉,文件下载出现问题。建议您稍作等待,之后再尝试下载。')
console.log(`下载失败${err}`)
}
})
downloadTask.onProgressUpdate(res => {
console.log(res.progress)
_self.setData({
downloadProgress: res.progress
})
});
},
//显示错误信息
showErr(msg) {
const _self = this
_self.setData({
errorHint: msg,
showError: true,
showDownload: false,
downloading: false,
downloadProgress: 0
})
},
//去生成项目
doCreatePro(e) {
wx.showLoading({
title: '生成中...',
})
const _self = this
const item = e.currentTarget.dataset.value
ProjectService.doBuildProject(item.projId)
.then(res => {
// 刷新列表
wx.hideLoading()
console.log(res)
_self.setData({
successHint: '正在生成中,请耐心等待',
showSuccess: true
})
_self.doRefreshList()
})
.catch(err => {
console.log(err)
wx.hideLoading()
_self.setData({
errorHint: err.msg ? err.msg : '生成失败,请稍后重试',
showError: true
})
})
},
//重新生成
doReCreate(e) {
console.log(e)
const item = e.currentTarget.dataset.value
const _self = this
wx.showLoading({
title: '提交中...',
})
ProjectService.doReCreate(item.projId)
.then(res => {
wx.hideLoading()
_self.setData({
successHint: '提交成功,正在生成中,请耐心等待',
showSuccess: true
})
_self.doRefreshList()
}, err => {
wx.hideLoading()
_self.setData({
successHint: '提交失败,请稍后重试',
showSuccess: true
})
})
},
//加载更多
doLoadMore() {
//判断是否正在加载中
const _self = this
console.log(_self.data.isLoadMore)
console.log(_self.data.hasMore)
if (_self.data.isLoadMore || !_self.data.hasMore) {
return
}
//判断是否有更多
_self.setData({
isLoadMore: true,
'pageData.page': ++_self.data.pageData.page
})
const params = _self.buildParams(_self.data.pageData.page, false)
_self.doGetSelfList(params, false)
},
//关闭广告
doCloseAd(e) {
const isShow = e.detail
// isShow=true 今日不再显示
if (isShow) {
const currentDate = new Date().toLocaleDateString();
Cache.set('noShowToday', currentDate)
this.setData({
isNoShowToday: true
});
}
},
//收下优惠卷
doFurlCoupons(e) {
console.log('收下优惠卷')
const _self = this
const isShow = e.detail
// isShow=true 今日不再显示
if (isShow) {
const currentDate = new Date().toLocaleDateString();
Cache.set('noShowToday', currentDate)
this.setData({
isNoShowToday: true
});
}
wx.showLoading({
title: '领取中...',
})
const requests = _self.data.tempCoupons.map(item => {
const coupons = {
couponId: item.couponId
}
return UserApi.doSaveCoupons(coupons)
})
Promise.all(requests)
.then(res => {
wx.hideLoading()
_self.setData({
successHint: '本次领取操作已成功,您可以在 “我的” 页面查看相关信息。',
showSuccess: true,
})
})
.catch(err => {
wx.hideLoading()
_self.setData({
errorHint: err.msg ? err.msg : '本次领取操作未成功,请重新进入小程序后再次尝试。',
showError: true,
})
})
},
copyLink(e) {
var link = e.currentTarget.dataset.value
wx.setClipboardData({
data: link,
})
}
})