scanAuthCtrl.js 14.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
;
(function (angular) {
  function scanAuthCtrl($scope, $http, wechatauthService, $q, $uibModal, $timeout, toaster) {
    $scope.isDefault = true
    // 默认小程序-参数
    $scope.defaultOptions = {
      appId: '',
      appName: '',
      merchantId: '',
      // 开通状态(1:待完善商户信息;2:已开通公版;3:自注册私有;4:代注册私有)
      openStatus: '',
      remark: '',
      weappQrcode: '',
      weappTitle: ''
    }
    // 记录当前task
    $scope.active_task = 999,
      // 保存当前商户信息
      $scope.merchant_auth = {}
    // task 的配置信息
    oTask = {
      el: '#tasks',
      data: [{
          title: '扫码授权',
          description: ''
        },
        {
          title: '注册小程序',
          description: ''
        },
        {
          title: '填写资料',
          description: ''
        },
        {
          title: '完善资料',
          description: ''
        }
      ],
      dataOrder: ['title', 'line']
    }
    /**
    	步骤1  (step 0)公众号扫码授权
     */
    $scope.notice = {
      toOpen: 'wechat/auth/pc',
      submit: function () {
        ask($scope.notice.toOpen)
      }
    }
    /**
    	步骤2 (step 1)公众号扫码授权
     */
    $scope.register = {
      toOpen: 'wechat/fastregister/auth/pc',
      submit: function () {
        ask($scope.register.toOpen)
      }
    }
    /**
    	步骤3  (step 2)填写资料,提交审核
     */
    $scope.completeInfo = {
      checkName,
      checked: false,
      success: false,
      checking: false,
      errors: {
        nickname: '',
        headImageUrl: '',
        licenseUrl: ''
      },
      beforeUpload,
      upload,
      model: {
        nickname: '',
        headImageUrl: '',
        licenseUrl: '',
        namingOtherStuffFirstUrl: '',
        namingOtherStuffSecondUrl: ''
      },
      submitted: false,
      submit: ($invalid) => {
        $scope.completeInfo.submitted = true
        if ($invalid) return
        checkName().then(_r => {
          if (_r) {
            const __p = $scope.completeInfo.model
            __request('wxConsummate', __p).then(function (result) {
              if (result) {
                loadTask()
              }
            })
          }
        })
      }
    }
    /**
    	步骤4  (step 3) 完善商户资料
     */
    $scope.merchant = {
      model: {
        name: '', // 商户全称
        shortName: '', // 商户简称
        address: '', // 商户地址
        telphone: '', // 商户联系电话
        businessHours: '', // 营业时间
        mainSaleVehicle: [], // ['宝马', '奔驰', '奥迪'], // 主营车辆(数量不超过10个)
        mainBusiness: ['保养', '维修', '清洗', '钣喷'], // ['保养', '维修', '清洗', '钣喷'], // 主营业务(项目不超过10个)
        area: '', // 区
        province: '', // 省
        city: '', // 市
        lat: '', // 纬度(高德坐标)
        lng: '', // 经度(高德坐标)
        oAddr: null,
        carBrandList: [],
        openTime: '09:00',
        closeTime: '18:00'
      },
      submitted: false,
      submit: function ($invalid, isDefault = false) {
        $scope.merchant.submitted = true
        if ($invalid) return
        if ($scope.timeShowError) return
        var _p = angular.copy($scope.merchant.model)
        _p.businessHours = `${_p.openTime}-${_p.closeTime}`
        _p.isGeneralEdition = isDefault
        delete _p.oAddr
        delete _p.carBrandList
        delete _p.openTime
        delete _p.closeTime
        if (_p.province && !_p.city && '北京市天津市上海市重庆市'.indexOf(_p.province) != -1) {
          _p.city = _p.province
        }
        __request('merchantConsummate', _p).then(function (result) {
          if (result) {
            loadTask()
            alerter('提交成功', 'success')
          }
        })
      },
      openChooseBrands: () => open('biz/wechatauth/view/choose/chooseBrands.html', 'chooseBrands', {
        'request': __request,
        'carBrandList': $scope.merchant.model.carBrandList
      }, chooseBrandsCallBack),
      openChooseServices: () => open('biz/wechatauth/view/choose/chooseServices.html', 'chooseServices', {
        'mainBusiness': $scope.merchant.model.mainBusiness,
        'alerter': alerter
      }, (aServices) => $scope.merchant.model.mainBusiness = aServices),
      openChooseAddress: () => open('biz/wechatauth/view/choose/chooseAddress.html', 'chooseAddress', {
        oAddress: $scope.merchant.model.oAddr,
        'alerter': alerter
      }, (oAddr) => {
        const {
          city,
          province,
          district,
          address,
          position
        } = $scope.merchant.model.oAddr = oAddr
        $scope.merchant.model.city = city
        $scope.merchant.model.province = province
        $scope.merchant.model.area = district
        $scope.merchant.model.lat = position.lat
        $scope.merchant.model.lng = position.lng
        $scope.merchant.model.address = address // concatAddr(province,city,district,address)
      }, 'lg')
    }
    $scope.timeShowError = false
    $scope.$watch('merchant.model.openTime', function (newValue) {
      $scope.timeShowError = new Date("2019/01/01 " + newValue) >= new Date("2019/01/01 " + $scope.merchant.model.closeTime)
    })
    $scope.$watch('merchant.model.closeTime', function (newValue) {
      $scope.timeShowError = new Date("2019/01/01 " + $scope.merchant.model.openTime) >= new Date("2019/01/01 " + newValue)
    })
    var regPhone = /^[\d-,:;"~#()——,:;“”、()\*\|\/\\]*$/
    $scope.$watch("merchant.model.telphone", function (newValue, oldValue) {
      if (regPhone.test(newValue)) {
        $scope.merchant.model.telphone = newValue ? newValue.slice(0, 12) : newValue
      } else {
        $scope.merchant.model.telphone = newValue ? oldValue : newValue
      }
    })
    $scope.$watch('merchant_auth', function (now) {
      var {
        merchantInfo
      } = angular.copy(now)
      if (!merchantInfo) return
      const {
        merchantName,
        shortName,
        address,
        phone,
        businessHours,
        mainSaleVehicle,
        mainBusiness,
        areaName,
        provinceName,
        cityName,
        carBrandList,
        lat,
        lng
      } = merchantInfo
      $scope.merchant.model = angular.extend($scope.merchant.model, {
        name: merchantName,
        shortName,
        address,
        telphone: phone,
        businessHours,
        mainSaleVehicle,
        mainBusiness,
        area: areaName,
        province: provinceName,
        city: cityName,
        carBrandList: carBrandList,
        lat,
        lng
      })
      $scope.merchant.model.oAddr = {
        city: cityName,
        province: provinceName,
        district: areaName,
        position: {
          lat,
          lng
        },
        address
      }
      if (carBrandList && carBrandList.length) {
        $scope.merchant.model.mainSaleVehicle = carBrandList.map(function (item) {
          return {
            brandId: item.brandId,
            brandName: item.brandName,
            brandLogo: item.brandLogo
          }
        })
      }
      if (businessHours && businessHours.indexOf('-') != -1) {
        var _aHours = businessHours.split('-')
        $scope.merchant.model.openTime = _aHours[0]
        $scope.merchant.model.closeTime = _aHours[1]
      }
    }, true)
    /**
    	统一处理错误信息
     */
    function alerter(message, type) {
      swal({
        type: type || 'error',
        title: '',
        text: message || '',
        showConfirmButton: false,
        timer: 1500
      }, function () {
        swal.close()
      })
    }
    /**
    	统一处理弹窗
     */
    function open(url, controller, defaultData, result, size) {
      $uibModal.open({
        templateUrl: url,
        controller,
        size: size || 'md',
        resolve: {
          data: () => {
            return {
              defaultData
            }
          }
        }
      }).result.then(result)
    }
    // before文件上传
    function beforeUpload(file) {
      const __model = file.getAttribute('model')
      const __size = file.getAttribute('size')
      const __sizeError = file.getAttribute('sizeError')
      $scope.completeInfo.errors[__model] = ''
      const __oFile = file.files[0]
      if (__size) {
        if (__oFile.size / 1024 / 1024 < __size) {
          upload(__oFile, __model)
        } else {
          $scope.completeInfo.errors[__model] = `错误原因: ${__sizeError}`
          $scope.$apply()
        }
      } else {
        upload(__oFile, __model)
      }
    }
    // 统一处理文件上传
    function upload(__oFile, __model) {
      $http({
        url: 'common/uploadImage',
        method: 'POST',
        headers: {
          'Content-Type': undefined
        },
        transformRequest: function () {
          var formData = new FormData()
          formData.append('file', __oFile)
          return formData
        }
      }).success(function (res) {
        if (res.returnCode == 0) {
          $scope.completeInfo.model[__model] = res.data
        } else {
          alerter(res.message)
        }
      })
    }
    $scope.namingOtherStuffShow = false
    $scope.namingTips = ''
    // 检测小程序昵称
    function checkName() {
      //   return new Promise(resolve => {
      $scope.completeInfo.checked = true
      $scope.completeInfo.checking = true
      // if (!$scope.completeInfo.model.nickname) {
      //   $scope.completeInfo.errors.nickname = '请输入名称'
      //   $scope.completeInfo.success = false
      //   $scope.$apply()
      //   resolve(false)
      //   return
      // }
      $scope.completeInfo.errors.nickname = ''
      var __q = $q.defer()
      __request('checkName', $.param({
        nickname: $scope.completeInfo.model.nickname
      }), true).then(function (result) {
        $scope.completeInfo.checking = false
        $scope.namingOtherStuffShow = result.data
        $scope.namingTips = result.message
        if (result.returnCode == '0') {
          $scope.completeInfo.success = true
          __q.resolve(true)
        } else {
          // alerter(result.message)
          $scope.completeInfo.success = false
          $scope.completeInfo.errors.nickname = result.message
          __q.resolve(false)
        }
        // $scope.$apply()
      })
      return __q.promise
      //   })
    }

    // 统一处理授权询问
    function ask(opUrl) {
      openWin(opUrl)
      swal({
          title: '提示',
          text: '<p>是否授权成功?</p>',
          // type: "warning",
          showCancelButton: true,
          confirmButtonText: '我已授权成功',
          cancelButtonText: '授权失败了',
          closeOnConfirm: false,
          closeOnCancel: false,
          customClass: 'layerBox',
          html: true
        },
        function (isConfirm) {
          if (isConfirm) {
            loadTask()
          }
          swal.close()
        })
    }
    // 新页面打开一个链接
    function openWin(url) {
      // 用于防止浏览器拦截的hack
      var tempwindow = window.open('_blank'); // 先打开页面
      tempwindow.location = url; // 后更改页面地址
    }
    // 统一处理创建task
    function creatTask(task) {
      oTask.active = task || $scope.active_task
      steps(oTask)
    }
    /**
     * step 步骤条与当前实际步骤(后端返回) 的映射关系表
     */
    const stepMap = {
      1: 0,
      2: 1,
      3: 2,
      4: 2,
      5: 3,
      6: 3
    }
    // 加载商户信息个当前task
    function loadTask() {
      __request('loadTask', {}).then(function (result) {
        // console.log(result)
        // 默认小程序
        $scope.defaultOptions = result.weappOpenSituation
        !$scope.defaultOptions.openStatus ? $scope.defaultOptions.openStatus = 1 : ''
        // 私有小程序
        $scope.merchant_auth = result
        $scope.active_task = result.authStatus - 1 // 4
        // $scope.$apply()
        if ($scope.active_task === 5) {
          __request('baseInfoGet', {
            appId: result.weAppId
          }).then(function (result) {
            $scope.merchant_auth = {
              ...$scope.merchant_auth,
              ...result
            }
          })
        }
        creatTask(stepMap[result.authStatus])
      })
    }

    function chooseBrandsCallBack(brands) {
      // $scope.merchant.model.mainSaleVehicle=brands.map(item=>item.id)
      $scope.merchant.model.mainSaleVehicle = $scope.merchant.model.carBrandList = brands.map(function (item) {
        return {
          brandId: item.id,
          brandName: item.name,
          brandLogo: item.logoUrl
        }
      })
    }
    // 统一处理接口请求
    function __request(action, params, special) {
      //   return new Promise(resolve => {
      var __q = $q.defer()
      wechatauthService[action](params, function (result) {
        if (special) {
          __q.resolve(result)
          return
        }
        if (result.returnCode == '0') {
          __q.resolve(result.data)
        } else {
          alerter(result.message)
          __q.resolve(false)
        }
      })
      return __q.promise
      //   })
    }
    // 下载小程序码
    $scope.handleCodePic = function (isDefault = false) {
      console.log('download..')
      open('biz/wechatauth/view/auth/codeDownload.html', 'codeDownload', {
        appId: isDefault ? $scope.merchant_auth.weappOpenSituation.appId : $scope.merchant_auth.weAppId,
        scene: isDefault ? 'merchantId=' + $scope.merchant_auth.merchantId : '',
        'request': __request
      })
    }
    $scope.handlePrivate = function () {
      $scope.isDefault = false
    }
    // 页面跳转
    $scope.activityFlag = false

    function checkPermission(pageTitle, data, name) {
      angular.forEach(data, function (e) {
        if (e.children) {
          checkPermission(pageTitle, e.children, name)
        } else {
          if (e.pageTitle == pageTitle) {
            $scope[name] = true
          }
        }
      })
    }
    $scope.jumpLink = function (name, target) {
      checkPermission(name, $scope.menuList, target)
      if ($scope[target]) {
        //跳往一件营销
        if (name === '活动列表') {
          localStorage.setItem('activitySatus', 'marketing.shopactivity.shoplist')
          // $scope.jumpActivity()
        } else if (name === '员工名片') {
          localStorage.setItem('staffStaus', 'system.userAdmin.employee')
        }
        localStorage.setItem('isNewWindow', 0)
        window.open('#/home/index', '_blank')
      } else {
        toaster.pop({
          type: 'error',
          body: '您暂未开通该服务,请联系客服处理',
          showCloseButton: true,
          timeout: 3000
        })
      }
    }
    // 页面初始化
    ;
    (function init() {
      loadTask()
    })()
  }
  angular.module('wechatauth')
    .controller('scanAuthCtrl', scanAuthCtrl)
})(angular)