forked from gzzfw/frontEnd/gzDyh

zhangyongtian
2024-09-09 cee01cbfea118cb90a8d34b220315c9a9444941e
gz-wxparty/utils/util.js
@@ -5,7 +5,7 @@
const url = api.url;
// 是否是开发环境
const isDebug = true;
const isDebug = false;
const baseUrl = isDebug ? api.url.debug : api.url.web;
@@ -17,479 +17,485 @@
// request
const request = ({
    url,
    type,
    submitData,
    service,
    v1,
    noToken
  url,
  type,
  submitData,
  service,
  v1,
  ai,
  noToken
}) => {
    const app = getApp();
  const app = getApp();
    let token = app.globalData.token;
    if (!token && !noToken) {
        console.log(typeof app.globalData.access_token, 'app.globalData.access_token1111111111111')
        if (!app.globalData.access_token) {
            showModal({
  let token = app.globalData.token;
  if (!token && !noToken) {
    console.log(typeof app.globalData.access_token, 'app.globalData.access_token1111111111111')
    if (!app.globalData.access_token) {
      showModal({
        title: '提示信息',
        content: '抱歉!登录状态已失效,请重新登录',
        confirmText: '重新登录',
        showCancel: false,
        success: (res) => {
          if (res.confirm) {
            loginOutClearData();
            wx.navigateTo({
              url: '../../pages/login/index',
            });
          }
        },
      });
      return false;
    }
  }
  let baseUrl = isDebug ? api.url.debug : api.url.web;
  let visitUrl = `${baseUrl}${api.url[service] || ''}/api/${v1 ? 'v1' :ai ? 'ai' : 'wechat'}/${url}`;
  return new Promise((resolve, reject) => {
    wx.request({
      url: visitUrl,
      data: submitData,
      method: type,
      header: {
        Authorization: token,
      },
      success: (res) => {
        if (res.errMsg === 'request:ok') {
          const {
            statusCode
          } = res;
          if (statusCode >= 400) {
            errorModal({
              content: '抱歉!请求失败,稍后重试'
            });
            resolve({
              type: false
            });
            return false;
          }
          const {
            code,
            data,
            msg
          } = res.data;
          let obj = {};
          if (code === '0' || code === 0) {
            obj = {
              type: true,
              data
            };
          } else if (code === 401 || code === '401') {
            if (app.globalData.access_token !== 1) {
              errorModal({
                title: '提示信息',
                content: '抱歉!登录状态已失效,请重新登录',
                confirmText: '重新登录',
                showCancel: false,
                success: (res) => {
                    if (res.confirm) {
                        loginOutClearData();
                        wx.navigateTo({
                            url: '../../pages/login/index',
                        });
                    }
                success: () => {
                  loginOutClearData();
                  wx.navigateTo({
                    url: '../../pages/login/index'
                  });
                },
              });
            }
            obj = {
              type: false
            };
          } else {
            errorModal({
              content: msg
            });
            return false;
            obj = {
              type: false
            };
          }
          resolve(obj);
        } else {
          errorModal({
            content: '抱歉!请求失败,稍后重试'
          });
          resolve({
            type: false
          });
        }
    }
    let baseUrl = isDebug ? api.url.debug : api.url.web;
    let visitUrl = `${baseUrl}${api.url[service] || ''}/api/${v1 ? 'v1' : 'wechat'}/${url}`;
    return new Promise((resolve, reject) => {
        wx.request({
            url: visitUrl,
            data: submitData,
            method: type,
            header: {
                Authorization: token,
            },
            success: (res) => {
                if (res.errMsg === 'request:ok') {
                    const {
                        statusCode
                    } = res;
                    if (statusCode >= 400) {
                        errorModal({
                            content: '抱歉!请求失败,稍后重试'
                        });
                        resolve({
                            type: false
                        });
                        return false;
                    }
                    const {
                        code,
                        data,
                        msg
                    } = res.data;
                    let obj = {};
                    if (code === '0' || code === 0) {
                        obj = {
                            type: true,
                            data
                        };
                    } else if (code === 401 || code === '401') {
                        if (app.globalData.access_token !== 1) {
                            errorModal({
                                title: '提示信息',
                                content: '抱歉!登录状态已失效,请重新登录',
                                confirmText: '重新登录',
                                success: () => {
                                    loginOutClearData();
                                    wx.navigateTo({
                                        url: '../../pages/login/index'
                                    });
                                },
                            });
                        }
                        obj = {
                            type: false
                        };
                    } else {
                        errorModal({
                            content: msg
                        });
                        obj = {
                            type: false
                        };
                    }
                    resolve(obj);
                } else {
                    errorModal({
                        content: '抱歉!请求失败,稍后重试'
                    });
                    resolve({
                        type: false
                    });
                }
            },
            fail: () => {
                errorModal({
                    content: '抱歉!服务器出现错误,稍后重试'
                });
                resolve({
                    type: false
                });
            },
      },
      fail: () => {
        errorModal({
          content: '抱歉!服务器出现错误,稍后重试'
        });
        resolve({
          type: false
        });
      },
    });
  });
};
//
const commonRequest = ({
    url,
    submitData,
    type
  url,
  submitData,
  type
}) => {
    return new Promise((resolve, reject) => {
        wx.request({
            url: url,
            data: submitData,
            method: type,
            header: {
                'content-type': 'application/json; charset=utf-8', // 默认值
            },
            scriptCharset: 'utf-8',
            success: (res) => {
                const {
                    statusCode,
                    errMsg,
                    data
                } = res;
                if (statusCode >= 400) {
                    errorModal({
                        content: '抱歉!请求错误,稍后重试'
                    });
                    resolve(false);
                    return false;
                }
                if (errMsg === 'request:ok') {
                    resolve(data);
                } else {
                    resolve(false);
                }
            },
            fail: () => {
                resolve(false);
            },
        });
  return new Promise((resolve, reject) => {
    wx.request({
      url: url,
      data: submitData,
      method: type,
      header: {
        'content-type': 'application/json; charset=utf-8', // 默认值
      },
      scriptCharset: 'utf-8',
      success: (res) => {
        const {
          statusCode,
          errMsg,
          data
        } = res;
        if (statusCode >= 400) {
          errorModal({
            content: '抱歉!请求错误,稍后重试'
          });
          resolve(false);
          return false;
        }
        if (errMsg === 'request:ok') {
          resolve(data);
        } else {
          resolve(false);
        }
      },
      fail: () => {
        resolve(false);
      },
    });
  });
};
// 消息提示框
const showToast = ({
    title,
    icon = 'none',
    mask = true,
    duration = 2000,
    success
  title,
  icon = 'none',
  mask = true,
  duration = 2000,
  success
}) => {
    return wx.showToast({
        title: title,
        icon: icon,
        mask: mask,
        duration: duration,
        success: (res) => {
            success && success(res);
        },
    });
  return wx.showToast({
    title: title,
    icon: icon,
    mask: mask,
    duration: duration,
    success: (res) => {
      success && success(res);
    },
  });
};
const ellipsis = ({
  value,
  len
}) => {
  if (!value) return '';
  if (value.length > len) {
    return value.slice(0, len) + '...';
  }
  return value;
};
//api错误modal框消息提示
let errorNum = false; //控制报错信息不会重复弹出
const errorModal = ({
    title,
    content,
    confirmText,
    success,
    className
  title,
  content,
  confirmText,
  success,
  className
}) => {
    if (errorNum) {
        return false;
    }
    errorNum = true;
    return wx.showModal({
        title: title || '错误提示',
        content: content,
        className: className,
        showCancel: false,
        confirmColor: '#d10202',
        confirmText: confirmText || '知道了',
        success: (res) => {
            if (res.confirm) {
                errorNum = false;
                success && success(res);
            }
        },
    });
  if (errorNum) {
    return false;
  }
  errorNum = true;
  return wx.showModal({
    title: title || '错误提示',
    content: content,
    className: className,
    showCancel: false,
    confirmColor: '#d10202',
    confirmText: confirmText || '知道了',
    success: (res) => {
      if (res.confirm) {
        errorNum = false;
        success && success(res);
      }
    },
  });
};
//modal提示操作
const showModal = ({
    title = '温馨提示',
    content,
    showCancel = true,
    cancelText = '取消',
    confirmText = '确定',
    success
  title = '温馨提示',
  content,
  showCancel = true,
  cancelText = '取消',
  confirmText = '确定',
  success
}) => {
    return wx.showModal({
        content: content,
        showCancel: showCancel,
        confirmColor: '#1A6FB8',
        title: title,
        cancelText: cancelText,
        confirmText: confirmText,
        success: (res) => {
            success && success(res);
        },
    });
  return wx.showModal({
    content: content,
    showCancel: showCancel,
    confirmColor: '#1A6FB8',
    title: title,
    cancelText: cancelText,
    confirmText: confirmText,
    success: (res) => {
      success && success(res);
    },
  });
};
//loading
let loadingVisible = 0;
const showLoading = (title = '加载中...', mask = true) => {
    if (loadingVisible) {
        loadingVisible = loadingVisible + 1;
        return;
    }
    loadingVisible = 1;
    return wx.showLoading({
        title: title,
        mask: mask,
    });
  if (loadingVisible) {
    loadingVisible = loadingVisible + 1;
    return;
  }
  loadingVisible = 1;
  return wx.showLoading({
    title: title,
    mask: mask,
  });
};
const hideLoading = () => {
    loadingVisible = loadingVisible - 1;
    if (loadingVisible) return;
    return wx.hideLoading();
  loadingVisible = loadingVisible - 1;
  if (loadingVisible) return;
  return wx.hideLoading();
};
// 时间格式化
const timeFormat = (time, type) => {
    let formatType = type ? type : 'YYYY-MM-DD HH:mm';
    return time ? moment(time).format(formatType) : '';
  let formatType = type ? type : 'YYYY-MM-DD HH:mm';
  return time ? moment(time).format(formatType) : '';
};
// 计算消息时间距离当前时间
const getMsgTime = (endTime, startTime = new Date()) => {
    let end = moment(endTime),
        start = moment(startTime),
        minDiff = end.diff(start, 'minute');
    if (minDiff < 60) {
        return `${minDiff}分钟`;
    }
    let hoursDiff = minDiff / 60;
    if (hoursDiff < 24) {
        return `${hoursDiff}小时`;
    }
    let dayDiff = hoursDiff / 24;
    return `${dayDiff}天`;
  let end = moment(endTime),
    start = moment(startTime),
    minDiff = end.diff(start, 'minute');
  if (minDiff < 60) {
    return `${minDiff}分钟`;
  }
  let hoursDiff = minDiff / 60;
  if (hoursDiff < 24) {
    return `${hoursDiff}小时`;
  }
  let dayDiff = hoursDiff / 24;
  return `${dayDiff}天`;
};
// 退出登录清除数据
const loginOutClearData = () => {
    const app = getApp();
    app.globalData.token = '';
    wx.removeStorage({
        key: 'userInfo'
    });
  const app = getApp();
  app.globalData.token = '';
  wx.removeStorage({
    key: 'userInfo'
  });
};
// 手机号码正则
const mobileRegExp = (value) => {
    return /^1(3[0-9]|5[0-3,5-9]|7[1-3,5-8]|8[0-9]|9[0-9])\d{8}$/g.test(value);
  return /^1(3[0-9]|5[0-3,5-9]|7[1-3,5-8]|8[0-9]|9[0-9])\d{8}$/g.test(value);
};
// 睡眠
const sleep = (timeout = 500) => {
    return new Promise((resolve) => setTimeout(resolve, timeout));
  return new Promise((resolve) => setTimeout(resolve, timeout));
};
// 获取唯一的key
const getBusinessId = () => {
    let four = `${parseInt(Math.random() * 10)}${parseInt(Math.random() * 10)}${parseInt(Math.random() * 10)}${parseInt(Math.random() * 10)}`;
    let result = `${moment().format('YYYYMMDDHHmmss')}${four}`;
    return result;
  let four = `${parseInt(Math.random() * 10)}${parseInt(Math.random() * 10)}${parseInt(Math.random() * 10)}${parseInt(Math.random() * 10)}`;
  let result = `${moment().format('YYYYMMDDHHmmss')}${four}`;
  return result;
};
// 省市区选择
const changeLocation = (e, location, selectData) => {
    const {
        value,
        index
    } = e.detail.detail;
    let value_id = value[index].value;
    let faterArr = location;
    for (let i = 0; i < index; i++) {
        faterArr = faterArr[selectData[i].defaultIndex].children || [];
    }
    faterForEach: for (let i = 0; i <= faterArr.length - 1; i++) {
        if (faterArr[i].value === value_id) {
            selectData[index].defaultIndex = i;
            let arr = faterArr[i];
            for (let y = index + 1; y < value.length; y++) {
                selectData[y].values = JSON.parse(JSON.stringify(arr.children)) || [];
                selectData[y].defaultIndex = 0;
                // 当children不存在时赋值
                if (arr.children) {
                    arr = arr.children[0];
                }
                selectData[y].values.forEach((x) => {
                    delete x.children;
                });
            }
            break faterForEach;
  const {
    value,
    index
  } = e.detail.detail;
  let value_id = value[index].value;
  let faterArr = location;
  for (let i = 0; i < index; i++) {
    faterArr = faterArr[selectData[i].defaultIndex].children || [];
  }
  faterForEach: for (let i = 0; i <= faterArr.length - 1; i++) {
    if (faterArr[i].value === value_id) {
      selectData[index].defaultIndex = i;
      let arr = faterArr[i];
      for (let y = index + 1; y < value.length; y++) {
        selectData[y].values = JSON.parse(JSON.stringify(arr.children)) || [];
        selectData[y].defaultIndex = 0;
        // 当children不存在时赋值
        if (arr.children) {
          arr = arr.children[0];
        }
        selectData[y].values.forEach((x) => {
          delete x.children;
        });
      }
      break faterForEach;
    }
    return selectData;
  }
  return selectData;
};
// 计算默认的省市区下标
const getLocationIndex = (data, currentData) => {
    let selectOption = JSON.parse(JSON.stringify(data));
    let submitData = currentData;
    let arr = [0, 0, 0, 0];
    if (submitData.prov) {
        forEach: for (let i = 0; i < selectOption.length; i++) {
            if (selectOption[i].value === submitData.prov) {
                arr[0] = i;
                break forEach;
            }
        }
  let selectOption = JSON.parse(JSON.stringify(data));
  let submitData = currentData;
  let arr = [0, 0, 0];
  if (submitData.city) {
    forEach: for (let i = 0; i < selectOption[arr[0]].children.length; i++) {
      if (selectOption[arr[0]].children[i].value === submitData.city) {
        arr[1] = i;
        break forEach;
      }
    }
    if (submitData.city) {
        forEach: for (let i = 0; i < selectOption[arr[0]].children.length; i++) {
            if (selectOption[arr[0]].children[i].value === submitData.city) {
                arr[1] = i;
                break forEach;
            }
        }
  }
  if (submitData.area) {
    forEach: for (let i = 0; i < selectOption[arr[0]].children[arr[1]].children.length; i++) {
      if (selectOption[arr[0]].children[arr[1]].children[i].value === submitData.area) {
        arr[2] = i;
        break forEach;
      }
    }
    if (submitData.area) {
        forEach: for (let i = 0; i < selectOption[arr[0]].children[arr[1]].children.length; i++) {
            if (selectOption[arr[0]].children[arr[1]].children[i].value === submitData.area) {
                arr[2] = i;
                break forEach;
            }
        }
    }
    if (submitData.road) {
        forEach: for (let i = 0; i < selectOption[arr[0]].children[arr[1]].children[arr[2]].children.length; i++) {
            if (selectOption[arr[0]].children[arr[1]].children[arr[2]].children[i].value === submitData.road) {
                arr[3] = i;
                break forEach;
            }
        }
    }
    return arr;
  }
  // if (submitData.road) {
  //   forEach: for (let i = 0; i < selectOption[arr[0]].children[arr[1]].children[arr[2]].children.length; i++) {
  //     if (selectOption[arr[0]].children[arr[1]].children[arr[2]].children[i].value === submitData.road) {
  //       arr[3] = i;
  //       break forEach;
  //     }
  //   }
  // }
  return arr;
};
// 判断附件打开形式
const openFiles = (type, url, urls) => {
    let visible = false;
    if (type === '22_00017-3') {
        wx.previewImage({
            current: url,
            urls: urls,
  let visible = false;
  if (type === '22_00017-3') {
    wx.previewImage({
      current: url,
      urls: urls,
    });
    visible = true;
  } else if (['22_00017-4', '22_00017-5', '22_00017-6', '22_00017-9'].includes(type)) {
    showLoading();
    wx.downloadFile({
      url: url,
      success: function (res) {
        const filePath = res.tempFilePath;
        wx.openDocument({
          filePath: filePath,
          complete: () => {
            hideLoading();
          },
        });
        visible = true;
    } else if (['22_00017-4', '22_00017-5', '22_00017-6', '22_00017-9'].includes(type)) {
        showLoading();
        wx.downloadFile({
            url: url,
            success: function (res) {
                const filePath = res.tempFilePath;
                wx.openDocument({
                    filePath: filePath,
                    complete: () => {
                        hideLoading();
                    },
                });
            },
        });
        visible = true;
    } else {
        showToast({
            title: '抱歉!您所点击的附件暂不支持查看'
        });
        visible = false;
    }
    return visible;
      },
    });
    visible = true;
  } else {
    showToast({
      title: '抱歉!您所点击的附件暂不支持查看'
    });
    visible = false;
  }
  return visible;
};
// 校验登录'login' and 实名'realName' and 'all'
const userTest = (type, direction) => {
    const app = getApp();
    if (!app.globalData.token && (type === 'login' || type === 'all')) {
        showModal({
            content: '抱歉您未登录,是否前往登录?',
            success: (res) => {
                if (res.confirm) {
                    wx.navigateTo({
                        url: '../../pages/login/index',
                    });
                }
            },
        });
        return false;
    }
    let realStatus = wx.getStorageSync('userInfo')?.realStatus;
    if (realStatus !== 1 && (type === 'realName' || type === 'all')) {
        if (direction !== 'bottom') {
            showModal({
                content: '检测到您未进行实名认证,该操作需先进行实名认证,是否前往认证?',
                success: (res) => {
                    if (res.confirm) {
                        wx.navigateTo({
                            url: '../../pages/realNameAuthentication/index',
                        });
                    }
                },
            });
  const app = getApp();
  if (!app.globalData.token && (type === 'login' || type === 'all')) {
    showModal({
      content: '抱歉您未登录,是否前往登录?',
      success: (res) => {
        if (res.confirm) {
          wx.navigateTo({
            url: '../../pages/login/index',
          });
        }
        return false;
      },
    });
    return false;
  }
  let realStatus = wx.getStorageSync('userInfo')?.realStatus;
  if (realStatus !== 1 && (type === 'realName' || type === 'all')) {
    if (direction !== 'bottom') {
      showModal({
        content: '检测到您未进行实名认证,该操作需先进行实名认证,是否前往认证?',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '../../pages/realNameAuthentication/index',
            });
          }
        },
      });
    }
    return true;
    return false;
  }
  return true;
};
// 地址栏截取
function getQueryString(href, name) {
    let result = href.match(new RegExp('[?&]' + name + '=([^&]+)', 'i'));
    if (!result || result.length < 1) {
        return null;
    }
    return decodeURI(result[1]);
  let result = href.match(new RegExp('[?&]' + name + '=([^&]+)', 'i'));
  if (!result || result.length < 1) {
    return null;
  }
  return decodeURI(result[1]);
}
// 清除字符串中的空格,用于判断是否为空
function verifyEmpty(value) {
    return value?.replace(/\s+/g, '');
  return value?.replace(/\s+/g, '');
}
module.exports = {
    moment,
    url,
    request,
    commonRequest,
    isDebug,
    baseUrl,
    version,
    province,
    showToast,
    errorModal,
    showModal,
    showLoading,
    hideLoading,
    timeFormat,
    getMsgTime,
    loginOutClearData,
    mobileRegExp,
    sleep,
    getBusinessId,
    changeLocation,
    getLocationIndex,
    openFiles,
    userTest,
    getQueryString,
    verifyEmpty,
  moment,
  url,
  request,
  commonRequest,
  isDebug,
  baseUrl,
  version,
  province,
  showToast,
  errorModal,
  showModal,
  ellipsis,
  showLoading,
  hideLoading,
  timeFormat,
  getMsgTime,
  loginOutClearData,
  mobileRegExp,
  sleep,
  getBusinessId,
  changeLocation,
  getLocationIndex,
  openFiles,
  userTest,
  getQueryString,
  verifyEmpty,
};