<template>
  <h-view id="setting" class="public-style" title="设置">
    <h-header :proportion="[5,1,1]" class="bar-custom">
      <div slot="left" class="h-header-btn">
        <img src="@/assets/userBind/arrow.png" @click="$routeGo()">
        <span>设置</span>
      </div>
    </h-header>
    <h-content>
      <div class="setting">
        <list-item :item-height="66" class="list">
          <item @click.native="imgUploadShow(app_user_id)">
            <div slot="name" style="color:#656464;">修改头像</div>
            <div class="arrow_right"><img src="@/assets/myinfo/arrow_right.png"></div>
          </item>
        </list-item>
        <list-item :item-height="50" class="list">
          <!-- <item v-if="bpId!=='undefined'" v-show="user_bp_type!='MANAGER'" @click.native="changePageHead()">
            <div slot="name" style="color:#656464;">修改信息</div>
            <div class="arrow_right"><img src="@/assets/myinfo/arrow_right.png"></div>
          </item> -->
          <item v-if="user_bp_type!='MANAGER'" @click.native="changeRole()">
            <div slot="name" style="color:#656464;">角色切换</div>
            <div class="arrow_right"><img src="@/assets/myinfo/arrow_right.png"></div>
          </item>
          <item v-if="user_bp_type!='MANAGER'" @click.native="resetPwd()">
            <div slot="name" style="color:red;">修改密码</div>
            <div class="arrow_right"><img src="@/assets/myinfo/arrow_right.png"></div>
          </item>
          <item @click.native="updateVersion()">
            <div slot="name" style="color:#656464;width:100%;display:flex;white-space:nowrap;align-items:center;">版本更新&nbsp;&nbsp;&nbsp;
              <div v-if="version > currentVersion" class="updateSign">NEW</div>
            </div>
            <div slot="right-icon" style="float:right;color:#383F45;opacity:0.4;">当前版本&nbsp;&nbsp;{{ currentVersion }}</div>
          </item>
          <!-- <item v-if="user_bp_type!='MANAGER'" @click.native="unBind()">
            <div slot="name" style="color:#656464;">解除绑定</div>
            <div class="arrow_right"><img src="@/assets/myinfo/arrow_right.png"></div>
          </item> -->
        </list-item>
      </div>
    </h-content>
    <role-switch
      v-show="roleSwitchFlag"
      ref="roleSwitchRoleList"
      :roleList="roleList"
      @roleConfirm="roleConfirm"
      @roleCancle="roleCancle"
    />
  </h-view>
</template>

<script>
import roleSwitch from './role-switch-component'
import defaultImg from '../../assets/myInfo/1.png'
export default {
  components: {
    roleSwitch,
    defaultImg,
  },
  data () {
    return {
      upLoadObj: defaultImg, // 上传的图片
      currentVersion: process.env.currentVersion,
      app_user_id: window.localStorage.getItem('app_user_id'),
      user_bp_status: JSON.parse(window.localStorage.getItem("now_user_bp_bind_id")).bp_status,
      bp_id:  JSON.parse(window.localStorage.getItem("now_user_bp_bind_id")).bp_id,
      user_bp_name: JSON.parse(window.localStorage.getItem("now_user_bp_bind_id")).bp_name,
      user_bp_class: JSON.parse(window.localStorage.getItem("now_user_bp_bind_id")).bp_class,
      isMultiRole: JSON.parse(window.localStorage.getItem("now_user_bp_bind_id")).bp_type,
      roleSwitchFlag: false,
      user_bp_type: JSON.parse(window.localStorage.getItem("now_user_bp_bind_id")).bp_type,
      bp_type_n: '',
      version: '',
      version_url: '',
      update_content: '',
      multiRoleList: [],
      // multipleRole: JSON.parse(window.localStorage.getItem("now_user_bp_bind_id")).bp_type,
      bpId: window.localStorage.bp_id,

      nowBind: JSON.parse(window.localStorage.getItem('now_user_bp_bind_id')),
    }
  },
  computed: {
    roleList () {
      let roleObj = {'TENANT': '主承租人', 'GUTA': '担保人', 'FACTORY': '主机厂', 'AGENT': '经销商', 'OFFICE': '办事处', 'MANAGER': '业务经理'}
      let obj = {
        bp_type: this.user_bp_type,
        bp_type_n: roleObj[this.user_bp_type],
      }
      let arr = []
      if (this.multiRoleList.length > 0) {
        arr = [...this.multiRoleList]
      }
      arr.push(obj)
      return arr
    },
  },
  created () {
    this.getVersion()
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      // console.log(vm.currentVersion)
      vm.getVersion()
    })
  },
  methods: {
    // 选择角色后确定
    roleConfirm (role) {
      this.roleSwitchFlag = false
      // if (role.bp_type === 'TENANT') {
      //   window.localStorage.setItem('multipleRole', 'TENANT')
      //   this.multipleRole = 'TENANT'
      // } else if (role.bp_type === 'GUTA') {
      //   window.localStorage.setItem('multipleRole', 'GUTA')
      //   this.multipleRole = 'GUTA'
      // } else if (role.bp_type === 'AGENT') {
      //   window.localStorage.setItem('multipleRole', 'AGENT')
      //   this.multipleRole = 'AGENT'
      // }

      this.nowBind = { ...this.nowBind, bp_type: role.bp_type, bp_type_n: role.bp_type_n };
     
      window.localStorage.setItem('now_user_bp_bind_id', JSON.stringify(this.nowBind));

      // console.log('选择后的角色为：' + role)
    },
    // 选择角色后取消
    roleCancle () {
      this.roleSwitchFlag = false
    },
    resetPwd () {
      this.$router.push({
        name: 'PwdReset',
      })
    },
    updateVersion () {
      if (this.version > this.currentVersion) {
        if (vum.Platform.isAndroid()) {
          this.hote_update_version(
            this.update_content,
            this.version_url
          )
        }
      } else {
        this.hlsPopup.showLongCenter('您的版本是最新版')
      }
    },
    hote_update_version (content, url) {
      hlsPopup.showConfirm({
        title: '版本更新' + this.version,
        content: content,
        onConfirm: function (index) {
          if (index === 1) {
            hotpatch.updateNewVersion(url)
          }
        },
      })
    },
    // 版本更新
    getVersion () {
      let url = $config.basePath + 'version_update'
      let param = {}
      this.$post(url, param).then((res) => {
        if (res.result === 'S') {
          if (res.android_version_list.length !== 0) {
            this.version = res.android_version_list[0].app_version
            this.update_content = res.android_version_list[0].update_content
            this.version_url = res.android_version_list[0].version_url
          } else {
            this.version = res.ios_version_list[0].app_version
            this.update_content = res.ios_version_list[0].update_content
            this.version_url = res.android_version_list[0].version_url
          }
          // if (vum.Platform.isAndroid()) {
          //   this.version = res.android_version_list[0].update_content
          // } else if (vum.Platform.isIOS()) {
          //   this.version = res.ios_version_list[0].update_content
          // }
        }
      })
    },
    getMultipleRole () { 
      let url = process.env.basePath + 'bp_role_query'
      let param = {
        master: {
          bp_id: this.bp_id,
          bp_type: this.user_bp_type,
        },
      }
      this.hlsHttp.post(url, param).then((res) => {
        if (res.result === 'S') {
          this.multiRoleList = res.lists
        }
      })
    },
    unBind () {
      let vm = this
      hlsPopup.showConfirm({
        title: '提示',
        content: '确定解除绑定？',
        onConfirm: function (index) {
          if (index === 1) {
            // window.localStorage.clear()
            // vm.$router.push('/login')
            let myPhone = window.localStorage.getItem('user_phone')
            let myPassword = window.localStorage.getItem('password')
            let url = process.env.basePath + 'bp_unbind'
            let param = {
              master: {
                phone: myPhone,
                password: myPassword,
              },
            }
            vm.hlsPopup.showLoading('请稍候')
            vm.hlsHttp
              .post(url, param)
              .then(function (res) {
                vm.hlsPopup.hideLoading()
                if (res.result === 'S') {
                  vm.hlsPopup.showLongCenter('解绑成功')
                  if (window.localStorage.getItem('user_phone')) {
                    vm.userQuery()
                  }
                  // vm.flag = true
                  vm.approveBtn = false
                } else {
                  vm.hlsPopup.showLongCenter(res.message)
                }
              })
          }
        },
      })
    },
    userQuery () {
      // let vm = this
      // let url = $config.basePath + 'user_query'
      // let param = {
      //   phone: window.localStorage.getItem('user_phone'),
      // }
      // vm.hlsPopup.showLoading('请稍候')
      // vm.$post(url, param).then(function (res) {
      //   if (res.result === 'S') {
      //     if (res.info.user_bp_status === 'APPROVED') {
      //       vm.flag = false
      //     }
      //     window.localStorage.setItem('user_phone', res.info.user_phone)
      //     vm.user_bp_status = res.info.user_bp_status
      //     vm.user_bp_class = res.info.user_bp_class
      //     vm.bp_id = res.info.user_bp_id
      //     vm.bp_identity = res.info.bp_identity
      //     vm.app_user_id = res.info.app_user_id
      //     vm.user_bp_name = res.info.user_bp_name
      //     vm.user_bp_type = res.info.user_bp_type
      //     vm.user_phone = res.info.user_phone
      //     vm.bp_type_n = res.info.user_bp_type_n
      //     if (res.info.user_bp_type === 'TENANT') {
      //       window.localStorage.setItem('multipleRole', 'TENANT')
      //     } else if (res.info.user_bp_type === 'GUTA') {
      //       window.localStorage.setItem('multipleRole', 'GUTA')
      //     } else if (res.info.user_bp_type === 'AGENT') {
      //       window.localStorage.setItem('multipleRole', 'AGENT')
      //     }
      //     vm.watchBpStatus()
      //     vm.getHead()
      //     vm.getMultipleRole()
      //     if (vm.user_bp_type === 'AGENT') {
      //       vm.isAGENT = true
      //     } else {
      //       vm.isAGENT = false
      //     }
      //     if (vm.user_bp_type === 'GUTA' || vm.user_bp_type === 'TENANT' || vm.user_bp_type === 'AGENT') {
      //       vm.isMultiRole = true
      //     } else {
      //       vm.isMultiRole = false
      //     }
      //   } else {
      //     this.hlsPopup.showLongCenter(res.message)
      //   }
      // })

        let obj = JSON.parse(window.localStorage.getItem("now_user_bp_bind_id"));
        let user_bp_status =  obj.bp_status;
        let user_bp_class =  obj.bp_class;
        let bp_id =  obj.bp_id;
        let bp_identity =  obj.bp_identity;
        let bp_type =  obj.bp_type;
        let bp_name =  obj.bp_name;
        let bp_type_n =  obj.bp_type_n;

        let user_phone =  JSON.parse(window.localStorage.getItem("user_phone"));
        let app_user_id =  JSON.parse(window.localStorage.getItem("app_user_id"));

      if (user_bp_status === 'APPROVED') {
            vm.flag = false
          } 
          vm.user_bp_status = user_bp_status
          vm.user_bp_class = user_bp_class
          vm.bp_id = bp_id
          vm.bp_identity = bp_identity
          vm.app_user_id = app_user_id
          vm.user_bp_name = bp_name
          vm.user_bp_type = bp_type
          vm.user_phone = user_phone
          vm.bp_type_n = bp_type_n 

          vm.watchBpStatus()
          vm.getHead()
          vm.getMultipleRole()
          if (bp_type === 'AGENT') {
            vm.isAGENT = true
          } else {
            vm.isAGENT = false
          }
          if (bp_type === 'GUTA' || bp_type === 'TENANT' || bp_type === 'AGENT') {
            vm.isMultiRole = true
          } else {
            vm.isMultiRole = false
          }
    },
    // 查询头像
    getHead () {
      let vm = this
      let url = process.env.basePath + 'app_attment_query'
      let param = {
        master: {
          source_type: 'HLS_APP_USER',
          pkvalue: vm.app_user_id,
        },
      }
      hlsPopup.showLoading('请稍候')
      vm.$post(url, param).then(function (res) {
        vm.hlsPopup.hideLoading()
        if (res.result === 'S') {
          if (res.info) {
            vm.upLoadObj = process.env.filePath +
              'attachment_id=' +
              res.info.attachment_id +
              '&access_token=' +
              window.localStorage.access_token
          } else {
            vm.upLoadObj = defaultImg
          }
        } else {
          hlsPopup.showLongCenter(res.message)
        }
      })
    },
    // 监听用户状态
    watchBpStatus () {
      if (!this.bp_id && this.user_bp_status === 'NEW') {
        this.description = '用户绑定'
        this.approveBtn = false
        this.popSetect = false
      } else if (this.bp_id && this.user_bp_status === 'NEW') {
        this.description = '待提交'
        this.approveBtn = false
        this.popSetect = true// 是否弹出选择框
      } else if (this.bp_id && this.user_bp_status === 'APPROVED') {
        this.description = '解除绑定'
        this.approveBtn = true
        this.popSetect = false
      } else if (
        (this.bp_id && this.user_bp_status === 'RETURN') ||
        (this.bp_id && this.user_bp_status === 'REJECT')
      ) {
        this.description = '审核未通过'
        this.approveBtn = false
        this.popSetect = true// 是否弹出选择框
      } else {
        this.description = '审批中'
        this.approveBtn = false
        this.popSetect = false
      }
    },
    // 角色切换
    async changeRole () {
      let vm = this
      if (((this.user_bp_type === 'TENANT') || (this.user_bp_type === 'GUTA') || (this.user_bp_type === 'AGENT')) && (this.user_bp_status === 'APPROVED')) {
        await this.getMultipleRole()
        vm.$refs.roleSwitchRoleList.show()
      } else {
        hlsPopup.showLongCenter('您当前尚无可用角色')
      }
    },
    // 用户信息
    changePageHead () {
      let vm = this
      if (vm.bp_id) {
        if (vm.user_bp_status === 'NEW' || vm.user_bp_status === 'RETURN') {
          vm.flag = true
          if (vm.user_bp_class === 'NP') {
            vm.$router.push({
              name: 'NPBaseInfo',
              params: {
                bp_id: vm.bp_id,
                user_bp_name: vm.user_bp_name,
              },
            })
          } else {
            vm.$router.push({
              name: 'EnterpriseNew',
              params: {
                bp_id: vm.bp_id,
                user_bp_name: vm.user_bp_name,
                bp_class: vm.user_bp_class,
              },
            })
          }
        } else if (vm.user_bp_status === 'APPROVED') {
          vm.flag = false
          if (vm.user_bp_class === 'NP') {
            vm.$router.push({
              name: 'NPBaseInfo',
              params: {
                bp_id: vm.bp_id,
                user_bp_name: vm.user_bp_name,
                isAGENT: vm.isAGENT,
                status: 'APPROVED',
                isMultiRole: vm.isMultiRole,
              },
            })
          } else {
            vm.$router.push({
              name: 'EnterpriseNew',
              params: {
                bp_id: vm.bp_id,
                user_bp_name: vm.user_bp_name,
                isAGENT: vm.isAGENT,
                status: 'APPROVED',
                isMultiRole: vm.isMultiRole,
                bp_class: vm.user_bp_class,
              },
            })
          }
        } else if (
          vm.user_bp_status === 'REJECT'
        ) {
          vm.flag = true
          if (vm.user_bp_class === 'NP') {
            vm.$router.push({
              name: 'NPBaseInfo',
              params: {
                bp_id: vm.bp_id,
                isMultiRole: vm.isMultiRole,
                user_bp_name: vm.user_bp_name,
                status: 'APPROVED',
              },
            })
          } else {
            vm.$router.push({
              name: 'EnterpriseNew',
              params: {
                bp_id: vm.bp_id,
                isMultiRole: vm.isMultiRole,
                user_bp_name: vm.user_bp_name,
                bp_class: vm.user_bp_class,
                status: 'APPROVED',
              },
            })
          }
        } else if (vm.user_bp_status === 'APPROVING') {
          vm.flag = true
          vm.hlsPopup.showLongCenter('您的绑定申请还在流程中')
        }
      } else {
        vm.flag = true
        vm.$router.push({
          name: 'UserBind',
        })
      }
    },
    // 图片上传入口
    imgUploadShow (check_id) {
      let vm = this
      // vm.upload_list = []
      hlsPopup.showActionSheet({
        titleText: '请选择照片',
        buttonArray: ['拍照', '从相册取'],
        callback: index => {
          if (index === 0) {
            vm.imgUploadOpenCamera(check_id)
          } else {
            vm.imgUploadTakePicture(check_id)
          }
        },
      })
    },
    imgUploadOpenCamera (check_id) {
      let vm = this
      let obj = {
        pkvalue: check_id,
        source_type: 'HLS_APP_USER',
        picture: '',
        check_id: check_id,
        filePath: '',
        attachment_id: '',
        user_id: 1,
        fileName: '',
      }
      let cameraoptions = {
        quality: 100,
      }
      let success = function (imgdata) {
        obj.picture = hlsUtil.convertImageUrl(imgdata)
        obj.filePath = imgdata
        vm.upLoadObj = obj.picture
        vm.save_picture(obj)
      }
      let error = function () {
        hlsPopup.showLongCenter('请拍照')
      }
      hlsUtil.openCamera(cameraoptions, success, error)
    },
    imgUploadTakePicture (check_id) {
      let vm = this
      let obj = {
        pkvalue: check_id,
        source_type: 'HLS_APP_USER',
        picture: '',
        check_id: check_id,
        filePath: '',
        attachment_id: '',
        user_id: 1,
        fileName: '',
      }
      let cameraoptions = {
        quality: 100,
      }
      let success = function (imgUrl) {
        obj.picture = hlsUtil.convertImageUrl(imgUrl[0])
        obj.filePath = imgUrl[0]
        vm.upLoadObj = obj.picture
        console.log('$$$$$$$$$$$$$$$1' + imgUrl[0])
        // 拍完一张立马执行保存图片逻辑
        vm.save_picture(obj)
      }
      let error = function () {
        hlsPopup.showLongCenter('请选择图片')
      }
      vm.hlsUtil.takePicture(cameraoptions, success, error)
    },
    openCamera (ocrType, type) {
      let vm = this
      let cameraoptions = {
        quality: 60,
        width: 1843,
        height: 1382,
      }
      let success = function (imgdata) {
        if (!imgdata) {
          hlsPopup.showLongCenter('请拍照')
        }
      }
      let error = function () {
        hlsPopup.showLongCenter('请拍照')
      }
      hlsUtil.openCamera(cameraoptions, success, error)
    },
    takePicture (ocrType, type) {
      let vm = this
      var cameraoptions = {
        quality: 70,
        width: 1843,
        height: 1382,
        maxCount: 1,
      }
      let success = function (imgUrl) {
        if (imgUrl.length === 0) {
          hlsPopup.showLongCenter('请选择一张图片')
        }
      }
      let error = function () {
        hlsPopup.showLongCenter(error)
      }
      vm.hlsUtil.takePicture(cameraoptions, success, error)
    },
    save_picture (obj) {
      if (obj) {
        let success = function () {
          hlsPopup.showLongCenter('头像上传成功')
        }
        hlsUtil.fileUploadSvc(obj, success)
      } else {
        hlsPopup.hideLoading()
      }
    },
  },
}
</script>

<style lang="less">
#setting{
  .content{
    margin-top:0 ;
  }
  .updateSign {
  background: red;
  color: white;
  padding: 0 4px;
  border-radius: 3px;
  font-size: 8px;
  height: 18px;
  display: flex;
  align-items: center;
}
.arrow_right {
  display: flex;
  align-items: center;
  img {
    height: 20px;
  }
}
}
</style>
