import App from './App'
import uView from './uni_modules/vk-uview-ui';
import G from './utils/common.js';
import jobJS from './utils/job.js';
import Ajax from './utils/ajax.js';
import wyyx from './utils/wyyx.js';
import apiInfo from './api/index.js';
import Vue from 'vue';

import gListApply from './components/list/apply.vue';
import gListJob from './components/list/jobApply.vue';
import gListYiJob from './components/list/job.vue';
import gPanelCardNum from './components/panel/numCard.vue';
import gPanelPosterCard from './components/panel/posterCard.vue';
import gPanelFormItem from './components/panel/formItem.vue';
import gPanelCardInfo from './components/panel/infoCard.vue';
import gListBill from './components/list/bill.vue';
import gPanelImage from './components/panel/defaultImage.vue';
import gFixed from './components/fixed.vue';
import gFilter from './pages/home/child/filter.vue';
import gPanelDetailItem from './components/panel/detailItem.vue';
import gPanelFormSlot from './components/panel/formSlot.vue';
import gPanelTime from './components/panel/time.vue';
import gTabs from "./components/custom-tabs.vue";
import {
  createSSRApp
} from 'vue'

export function createApp () {
  const app = createSSRApp(App)
  app.component('g-list-apply', gListApply);
  app.component('g-tabs', gTabs);
  app.component('g-list-job', gListJob);
  app.component('g-panel-card-info', gPanelCardInfo);
  app.component('g-panel-form-item', gPanelFormItem);
  app.component('g-panel-card-num', gPanelCardNum);
  app.component('g-panel-poster-card', gPanelPosterCard);
  app.component('g-panel-time', gPanelTime);
  app.component('g-list-bill', gListBill);
  app.component('g-yi-list-job', gListYiJob);
  app.component('g-panel-image', gPanelImage);
  app.component('g-panel-fixed', gFixed);
  app.component('g-filter', gFilter);
  app.component('g-panel-detail-item', gPanelDetailItem);
  app.component('g-panel-form-slot', gPanelFormSlot);
  app.config.globalProperties.api = apiInfo;

  app.config.globalProperties.G = Object.assign(G, Ajax, jobJS, {
    /*
     * 检查token,获取最新登录者信息
     */
    checkToken () {
      return new Promise((resolve, reject) => {
        G.Get('/checkToken', '', (res) => {
          console.log('checkToken', res);
          G.Post("/assistant/circle/agency/checkUserTypeForAssistant", { 
            upAgencyId:uni.getStorageSync("miniApp-info").id 
          }, (fensiRes) => {
            console.log("isFans", fensiRes);
            res.isfensi = fensiRes;
            uni.setStorageSync("apply-userinfo", res)
            uni.setStorageSync("apply-uid", res.id)
            uni.setStorageSync('apply-userinfo-copy', JSON.stringify(res));
            uni.setStorageSync("apply-agencyId", res.user.agencyId); // 单独存储 -- 代理id，方便获取
            uni.setStorageSync("apply-supplierAccount", res.supplierAccount); // 单独存储 -- 是否是发单号，方便获取 0.不是发单号 1.是发单号
            if (res.agencyId == uni.getStorageSync("miniApp-info").id) {
              let _env = uni.getAccountInfoSync().miniProgram.envVersion;
              G.Get(apiInfo.user_getUserQRCode, { env: _env }, (userqrcode) => {
                uni.setStorageSync("user_qrcode", "https://daotian.matripe.com.cn" + userqrcode.qrcode); // 用户分享时候的二维码
              });
              G.Get(apiInfo.user_checkServicePermission, {}, (res) => {
                // console.log('userqrcodeuserqrcode', res);
                uni.setStorageSync("user_ServicePermission", res); // 用户是否是客服的判断
              });
            }
            if (res.agencyId) {
              G.Get('/yishoudan/agency/role/checkDeptAdmin', {}, (val) => {
                console.log('/yishoudan/agency/role/checkDeptAdmin', val);
                uni.setStorageSync("is_teamleader", val === true ? 1 : 0); // 是否是部门管理员的判断
              })
              G.Get(apiInfo.login_agencyInfo, {}, (aRes) => {
                console.log("获取团队信息:", aRes);
                uni.setStorageSync("agencyInfo", aRes.agency); // 1是创建者 2是普通成员
              });
            }

            G.Get(
              apiInfo.user_checkPermission,
              {},
              (rea) => {
                // console.log('rearearearearearea', rea);
                if (rea.hasPermission == true) {
                  uni.setStorageSync("HAS_PERMISSION", 1); // 1.有权限 2.无权限
                } else {
                  uni.setStorageSync("HAS_PERMISSION", 2); // 1.有权限 2.无权限
                }
                if (rea.member == true) {
                  uni.setStorageSync("IS_MINIAPP_MEMBER", true); // 1.有权限 2.无权限
                  if (rea.isCreatorOrAdmin == true) {
                    uni.setStorageSync("IS_MINIAPP_ADMIN", true); // 1.有权限 2.无权限
                  } else {
                    uni.setStorageSync("IS_MINIAPP_ADMIN", false); // 1.有权限 2.无权限
                  }
                } else {
                  uni.setStorageSync("IS_MINIAPP_MEMBER", false); // 1.有权限 2.无权限
                }
                resolve(res)
              },
              (err) => {
                if (err) {
                  uni.setStorageSync("HAS_PERMISSION", 2);
                  resolve(res)
                }
              }
            );
          });
        }, function fail (err) {
          // console.log(err);
          resolve(err)
        })
      })
    },
    getAgencyInfo (callback=()=>{}) {
      let that = this
      G.Get("/yishoudan/agency/getInfo", {}, (res) => {
        let obj = { ...res.agency, ...res.weixinConfig }
        for (let key in obj) {
          if (typeof obj[key] == "string" && obj[key].indexOf("http:") > -1) {
            obj[key] = obj[key].replace("http:", "https:");
          }
        }
        // console.log('objobjobjobj', obj);
        uni.setStorageSync("miniApp-info", obj);
        uni.setStorageSync("pgy-agency-id", res.agency.id);
        uni.setStorageSync("ai-name", res.agency.aiRobotName);
        uni.setStorageSync("ai-logo", res.agency.aiLogo);
				callback();
        // app.$forceUpdate();
      });
    },
    getServiceQRCode () {
      let that = this
      G.Get("/yishoudan/agency/teamsman/customService", {}, (res) => {
        uni.setStorageSync("CUSTOMSERVICE_INFO", res);
      });
    },
    /*
     * 新的检查token,获取最新登录者信息
     */
    checkTokenNew () {
      return new Promise((resolve, reject) => {
        G.Get('/appLoginByToken', '', (res) => {
          console.log('checkTokenNew', res);
          uni.setStorageSync("apply-userinfo", res)
          uni.setStorageSync('apply-userinfo-copy', JSON.stringify(res));
          uni.setStorageSync("apply-agencyId", res.user.agencyId); // 单独存储 -- 代理id，方便获取
          uni.setStorageSync("apply-supplierAccount", res.supplierAccount); // 单独存储 -- 是否是发单号，方便获取 0.不是发单号 1.是发单号
          G.Get(
            apiInfo.user_checkPermission,
            {},
            (rea) => {
              // console.log('rearearearearearea', rea);
              if (rea.hasPermission == true) {
                uni.setStorageSync("HAS_PERMISSION", 1); // 1.有权限 2.无权限
              } else {
                uni.setStorageSync("HAS_PERMISSION", 2); // 1.有权限 2.无权限
              }
              if (rea.member == true) {
                uni.setStorageSync("IS_MINIAPP_MEMBER", true); // 1.有权限 2.无权限
                if (rea.isCreatorOrAdmin == true) {
                  uni.setStorageSync("IS_MINIAPP_ADMIN", true); // 1.有权限 2.无权限
                } else {
                  uni.setStorageSync("IS_MINIAPP_ADMIN", false); // 1.有权限 2.无权限
                }
              } else {
                uni.setStorageSync("IS_MINIAPP_MEMBER", false); // 1.有权限 2.无权限
              }
              resolve(res)
            },
            (err) => {
              if (err) {
                uni.setStorageSync("HAS_PERMISSION", 2);
                resolve(res)
              }
            }
          );
        })
      })
    },
    getUUID () {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
        return (c === 'x' ? (Math.random() * 16) | 0 : 'r&0x3' | '0x8').toString(16)
      })
    },
    /**
    * 上传到oss
    */
    uploadImgToOss (callback = () => { }, customDir = '', type = 'default', $num = 1, $sourceType = ['album', 'camera']) {
      var that = this;
      G.uploadImage($num, (imgRes) => {
        uni.showLoading({
          title: '上传中...',
        })
        // console.log('imgRes', imgRes);
        let imgPath = JSON.parse(imgRes)[0]
        // console.log('imgPath', imgPath);
        G.Get(apiInfo.getOssInfo, { prefix: customDir }, ({ data }) => {
          // console.log('uploadImgToOssresresresres', data);
          const { policy, signature, accessid, dir, host } = data;
          let key = dir + that.getUUID()
          const formData = {
            "key": key + "_${filename}",
            "policy": policy,
            "OSSAccessKeyId": accessid,
            signature,
            "success_action_status": "200",
          };

          uni.uploadFile({
            url: host,
            filePath: imgPath,
            name: "file",

            formData: formData,
            success: function (res) {
              if (res.errMsg = "uploadFile:ok") {
                const imgUrl = `${host}/${key}_${imgPath.split('/').pop()}`;
                callback({
                  status: '上传成功',
                  image: imgUrl
                });
              }
              // console.log('resresresresresresres', res);
            },
            fail: function (res) { },
          });
        })
      })
    },
    /* 上传图片
     */
    uploadImg (callback = () => { }, type = 'default', $num = 1, $sourceType = ['album', 'camera']) {
      G.uploadImage($num, (imgRes) => {
        uni.showLoading({
          title: '上传中...',
        })
        uni.uploadFile({
          url: G.ajaxUrl + apiInfo.uploadImage,
          method: "post",
          filePath: JSON.parse(imgRes)[0],
          name: "uploadFile",
          header: Object.assign({
            Authorization: 'Bearer ' + uni.getStorageSync("apply-token")
          }, Ajax.setPublicParams()),
          formData: Ajax.setPublicParams(),
          success: function (res) {
            // console.log('resresresresresresres', res);
            let imageStr = ''
            imageStr = JSON.parse(res.data).data;

            if (type == 'idcard') {
              // 调用身份证识别
              uni.uploadFile({
                url: G.ajaxUrl + apiInfo.getIDcard,
                filePath: JSON.parse(imgRes)[0],
                name: 'uploadFile',
                header: Object.assign({
                  Authorization: 'Bearer ' + uni
                    .getStorageSync("apply-token")
                }, Ajax.setPublicParams()),
                formData: Ajax.setPublicParams(),
                success: (uploadFileRes) => {
                  let cardData = {
                    status: '上传成功',
                    image: imageStr,
                    info: JSON.parse(uploadFileRes.data)
                      .data
                  }
                  uni.hideLoading()
                  callback(cardData);
                }
              });
            } else {
              uni.hideLoading()
              callback({
                status: '上传成功',
                image: imageStr
              });
            }
          },
          fail: function (res) {
            // console.log('fail', res);
          },
        });
      }, $sourceType);
    },
    /* 通过相机上传图片
     */
    uploadImgByCamera (callback = () => { }, type = 'default', $num = 1, $sourceType = ['camera']) {
      G.uploadImage($num, (imgRes) => {
        uni.showLoading({
          title: '上传中...',
        })
        uni.uploadFile({
          url: G.ajaxUrl + apiInfo.uploadImage,
          method: "post",
          filePath: JSON.parse(imgRes)[0],
          name: "uploadFile",
          header: Object.assign({
            Authorization: 'Bearer ' + uni.getStorageSync("apply-token")
          }, Ajax.setPublicParams()),
          formData: Ajax.setPublicParams(),
          success: function (res) {
            // console.log('resresresresresresres', res);
            let imageStr = ''
            imageStr = JSON.parse(res.data).data;

            if (type == 'idcard') {
              // 调用身份证识别
              uni.uploadFile({
                url: G.ajaxUrl + apiInfo.getIDcard,
                filePath: JSON.parse(imgRes)[0],
                name: 'uploadFile',
                header: Object.assign({
                  Authorization: 'Bearer ' + uni
                    .getStorageSync("apply-token")
                }, Ajax.setPublicParams()),
                formData: Ajax.setPublicParams(),
                success: (uploadFileRes) => {
                  let cardData = {
                    status: '上传成功',
                    image: imageStr,
                    info: JSON.parse(uploadFileRes.data)
                      .data
                  }
                  uni.hideLoading()
                  callback(cardData);
                }
              });
            } else {
              uni.hideLoading()
              callback({
                status: '上传成功',
                image: imageStr
              });
            }
          },
          fail: function (res) {
            // console.log('fail', res);
          },
        });
      }, $sourceType);
    },
    /* 通过图库上传图片
      */
    uploadImgByAlbum (callback = () => { }, type = 'default', $num = 1, $sourceType = ['album']) {
      G.uploadImage($num, (imgRes) => {
        uni.showLoading({
          title: '上传中...',
        })
        uni.uploadFile({
          url: G.ajaxUrl + apiInfo.uploadImage,
          method: "post",
          filePath: JSON.parse(imgRes)[0],
          name: "uploadFile",
          header: Object.assign({
            Authorization: 'Bearer ' + uni.getStorageSync("apply-token")
          }, Ajax.setPublicParams()),
          formData: Ajax.setPublicParams(),
          success: function (res) {
            // console.log('resresresresresresres', res);
            let imageStr = ''
            imageStr = JSON.parse(res.data).data;

            if (type == 'idcard') {
              // 调用身份证识别
              uni.uploadFile({
                url: G.ajaxUrl + apiInfo.getIDcard,
                filePath: JSON.parse(imgRes)[0],
                name: 'uploadFile',
                header: Object.assign({
                  Authorization: 'Bearer ' + uni
                    .getStorageSync("apply-token")
                }, Ajax.setPublicParams()),
                formData: Ajax.setPublicParams(),
                success: (uploadFileRes) => {
                  let cardData = {
                    status: '上传成功',
                    image: imageStr,
                    info: JSON.parse(uploadFileRes.data)
                      .data
                  }
                  uni.hideLoading()
                  callback(cardData);
                }
              });
            } else {
              uni.hideLoading()
              callback({
                status: '上传成功',
                image: imageStr
              });
            }
          },
          fail: function (res) {
            // console.log('fail', res);
          },
        });
      }, $sourceType);
    },
    // 头像上传
    uploadFile ($file, callback = () => { }) {
      let that = this;
      uni.uploadFile({
        url: G.ajaxUrl + '/user/changeUserImgsrc',
        filePath: $file,
        name: 'uploadFile',
        header: Object.assign({
          Authorization: 'Bearer ' + uni.getStorageSync("apply-token")
        }, Ajax.setPublicParams()),
        formData: Ajax.setPublicParams(),
        success: (uploadFileRes) => {
          callback(JSON.parse(uploadFileRes.data).data.url);
        }
      });
    },
    /**
     *  上传临时文件(不需要选择图库) 
     */
    uploadTmpImg ($fileName, callback = () => { }) {
      uni.uploadFile({
        url: G.ajaxUrl + apiInfo.uploadImage,
        method: "post",
        filePath: $fileName,
        name: "uploadFile",
        header: Object.assign({
          Authorization: 'Bearer ' + uni.getStorageSync("apply-token")
        }, Ajax.setPublicParams()),
        formData: Ajax.setPublicParams(),
        success: function (res) {
          let imageStr = ''
          imageStr = JSON.parse(res.data).data;
          callback({
            status: '上传成功',
            image: imageStr
          });
        },
        fail: function (res) { },
      });
    },
    /**
     * 上传图片前需要裁剪的
     */
    cropBeforeUpload (options) {
      G.uploadImage(1, (res) => {
        uni.cropImage({
          src: JSON.parse(res)[0],
          cropScale: options.cropScale,
          success: (res) => {
            G.uploadTmpImg(res.tempFilePath, (res) => {
              options.success(res);
            });
          },
          fail: (err) => {
            options.fail(err);
          },
        });
      });
    },

    /* 上传媒体文件
     */
    uploadMedia (callback = () => { }, type = 'default', $num = 9) {
      G.uploadM($num, (imgRes) => {
        uni.showLoading({
          title: '上传中...',
        })

        // console.log('imgRes', imgRes)

        let args = Array.from(JSON.parse(imgRes));
        // console.log('args', args)
        // return
        let imgList = []
        args.forEach((item, index) => {
          // console.log('item,', item)
          uni.uploadFile({
            url: G.ajaxUrl + apiInfo.uploadImage,
            method: "post",
            filePath: item.tempFilePath,
            name: "uploadFile",
            header: Object.assign({
              Authorization: 'Bearer ' + uni.getStorageSync(
                "apply-token")
            }, Ajax.setPublicParams()),
            formData: Ajax.setPublicParams(),
            success: function (res) {
              // console.log('uploadFileRes', res)
              imgList.push(JSON.parse(res.data).data)
              if (imgList.length == args.length) {
                callback({
                  status: '上传成功',
                  imgList: imgList
                });
              }

            },
            fail: function (res) {
              // console.log('res', res)
            },
          });
        })
      });
    }
  });
	const globalObj = typeof globalThis !== 'undefined'
	    ? globalThis
	    : (typeof global !== 'undefined' ? global : window);
	app.use(uView)
	// 安全赋值：确保全局对象存在再赋值
	  if (globalObj) {
	    globalObj.$app = app; // 挂载 Vue 实例（避免和 uni 内置的 $app 冲突）
	    // 若需挂载 $app，需先初始化空对象再赋值
	    if (!globalObj.$app) {
	      globalObj.$app = {};
	    }
	    globalObj.$app.config = {
	      globalProperties: app.config.globalProperties
	    };
	  } else {
	    console.warn('全局对象获取失败，无法挂载 Vue 实例');
	  }
  app.config.globalProperties.G.getAgencyInfo()
  app.config.globalProperties.F = wyyx;
  app.use(uView)
  return {
    app
  }
}