<template>
  <h-view id="my-bind-user" class="public-style" title="我绑定的用户">
    <h-header class="bar-custom">
      <div slot="left" class="h-header-btn" @click="$router.go(-1)">
        <img src="@/assets/userBind/arrow.png">
      </div>
      <div slot="center" class="top-word">我绑定的用户</div>
    </h-header>

    <scroll ref="scrollLists" :updateData="[prolists]" :pullUp="false">
      <div class="scroll-box">
        <div
          v-for="item of list"
          :key="item.bp_id"
          class="box"
          @click.stop="changePageHead(item)"
        >
          <div class="name">
            <img
              v-if="item.bp_class === 'NP'"
              src="../../assets/login/person.png"
              alt="自然人"
            >
            <img v-else src="../../assets/login/bank.png" alt="bank" >
            <span class="bp_name">{{ item.bp_name }}</span>
          </div>
          <div class="flag">
            <div @click.stop="face(item)">{{ item.bp_identity_name }}</div>
            <div
              :class="['normal', { unbind: item.bp_status === 'APPROVED' }]"
              @click.stop="doStatus(item)"
            >
              <!-- <span
                                style="font-size: .3rem;"
                            >{{ item.bp_status === 'APPROVED' ? '×' : '' }}</span>-->
              <img
                v-if="item.bp_status === 'APPROVED'"
                src="../../assets/login/cha.png"
                alt="cha"
              >
              {{ item.bp_status === 'APPROVED' ? ' 解绑' : item.bp_status === 'NEW' ? '待提交' : item.bp_status_n }}
            </div>
          </div>
        </div>
      </div>
    </scroll>

    <button class="submit" @click="$router.push('/user-bind')">
      <img src="../../assets/login/addUser.png" alt="自然人" > 添加新用户
    </button>

    <!-- 选项 -->
    <role-switch
      v-show="popSetectBox"
      ref="roleSwitchType"
      :roleList="type"
      @roleConfirm="typeConfirm"
      @roleCancle="popSetectBox = false"
    />
  </h-view>
</template>

<script>
import roleSwitch from './role-switch-component'

export default {
  name: 'MyBindUser',
  components: {
    roleSwitch,
  },
  data () {
    return {
      prolists: [],
      list: JSON.parse(window.localStorage.getItem('bind-user-list')),

      // 对于绑定用户的一些操作相关
      popSetectBox: false,
      type: Object.freeze(
        [
          {
            bp_type: '0',
            bp_type_n: '修改信息',
          },
          {
            bp_type: '1',
            bp_type_n: '重新选择用户类型',
          },
        ]
      ),
      NowItem: {}, // 当前操作对象
    }
  },
  mounted () {
    this.getList()
  },
  methods: {
    // 未认证进行人脸 认证
    async face (item) {
      let vm = this
      let register = ['NP_NO', 'ORG_NO', 'ORG_L_NO', 'ORG_AUTH_NO']
      vm.showPopupList(item)
    },

    showPopupList (item) {
      let vm = this
      let popList = [{
        code: 'AUTH',
        code_name: '个人实名认证/企业认证',
      }, {
        code: 'FORGET',
        code_name: '忘记PIN码',
      }, {
        code: 'QUERY',
        code_name: '查询是否认证', // 查询sdk里是否有token和用户特征值
      }, {
        code: 'ACTIVE',
        code_name: '人工审核激活账户',
      }, {
        code: 'CLEAN',
        code_name: '清除缓存',
      }]
      vm.hlsPopup.selectList({
        list: popList,
        code: 'code',
        object: {},
        returnItem: (index, obj) => {
          vm.goAuthManage(obj.code, item)
        },
      })
    },
    goAuthManage (code, item) {
      debugger
      let vm = this
      if (code === 'AUTH') {
        if (item.bp_class === 'NP') {
          vm.registerNotary(item)
        } else {
          vm.orgRegisterNotary(item)
        }
      } else if (code === 'FORGET') {
        vm.forgetPINNotary(item)
      } else if (code === 'QUERY') {
        if (item.bp_class === 'NP') {
          vm.haveUser(item)
        } else {
          this.hlsPopup.showLongCenter('企业用户无需查询')
        }
      } else if (code === 'ACTIVE') {
        if (item.bp_class === 'NP') {
          vm.activeUserNotary(item)
        } else {
          this.hlsPopup.showLongCenter('企业用户无需查询')
        }
      } else if (code === 'CLEAN') {
        vm.clearUser(item)
      }
    },
    registerNotary (item) {
      let vm = this
      cordova.plugins.IdCardPlugin.registerNotary(
        function (suc) {
          hlsPopup.showLongCenter(suc.message)
          if (suc.code === 'NORMALREGISTER') {
            vm.updateSigningCode(item.bp_id, 'Y', '')
          } else if (suc.code === 'PERSONSERVICE') {
            vm.updateSigningCode(item.bp_id, 'N', '')
          }
        },
        function (reason) {
          hlsPopup.showLongCenter('错误信息:' + '【' + reason.code + '】' + reason.message)
        },
        item.id_card_no,
        item.bp_name,
        item.id_card_no,
        true
      )
    },
    orgRegisterNotary (item) {
      this.getOrgCertificationUrl(item.bp_id)
    },
    forgetPINNotary (item) {
      let vm = this
      cordova.plugins.IdCardPlugin.forgetPINNotary(
        function (suc) {
          hlsPopup.showLongCenter(suc.message)
          if (suc.code === 'SUCCESS') {
            vm.updateSigningCode(item.bp_id, 'Y', '')
          } else {
            vm.updateSigningCode(item.bp_id, 'N', '')
          }
        },
        function (reason) {
          hlsPopup.showLongCenter('错误信息:' + '【' + reason.code + '】' + reason.message)
        }
      )
      //
    },
    haveUser (item) {
      cordova.plugins.IdCardPlugin.haveUser(
        function (suc) {
          if (suc.code === 'SUCCESS') {
            if (suc.data.haveUser) {
              hlsPopup.showLongCenter('已认证')
            } else {
              hlsPopup.showLongCenter('未认证')
            }
          } else {
            hlsPopup.showLongCenter(suc.message)
          }
        },
        function (reason) {
          hlsPopup.showLongCenter('错误信息:' + '【' + reason.code + '】' + reason.message)
        },
        item.id_card_no
      )
    },
    activeUserNotary (item) {
      let vm = this
      cordova.plugins.IdCardPlugin.activeUserNotary(
        function (suc) {
          if (suc.code === 'SUCCESS') {
            vm.updateSigningCode(item.bp_id, 'Y', '')
          } else {
            hlsPopup.showLongCenter(suc.message)
          }
        },
        function (reason) {
          hlsPopup.showLongCenter('错误信息:' + '【' + reason.code + '】' + reason.message)
        },
        item.id_card_no
      )
    },
    clearUser (item) {
      cordova.plugins.IdCardPlugin.clearUser(
        function (suc) {
          if (suc.code === 'SUCCESS') {
            hlsPopup.showLongCenter(suc.message)
            let vm = this
            vm.updateSigningCode(item.bp_id, 'N', '')
          }
        }
      )
    },
    async getOrgCertificationUrl (bp_id) {
      let url = process.env.basePath + 'auth_company_noauth'
      let param = {
        'bp_id': bp_id,
      }
      hlsPopup.showLoading('请稍候')
      let res = await this.$post(url, param)
      this.hlsPopup.hideLoading()
      if (res.result.info.code === 0 && res.result.code !== 700) {
        let authUrl = res.result.info.data.authUrl
        cordova.plugins.IdCardPlugin.webSignNotary(
          function (suc) {
            hlsPopup.showLongCenter(suc.message)
          },
          function (reason) {
            hlsPopup.showLongCenter('错误信息:' + '【' + reason.code + '】' + reason.message)
          },
          authUrl
        )
      } else if (res.result.code === 700) {
        hlsPopup.showLongCenter(res.result.msg)
      } else {
        hlsPopup.showLongCenter(res.result.info.msg)
      }
    },
    // 获取个人认证url
    async getNpCertificationUrl (item) {
      let vm = this
      let url = process.env.basePath + 'auth_user_sign'
      let param = {
        phone: window.localStorage.user_phone,
        bp_id: item.bp_id,
      }
      hlsPopup.showLoading('请稍候')
      let res = await vm.$post(url, param)
      hlsPopup.hideLoading()
      if (res.info.code === 0 && res.info.data.authUrl) {
        hlsPopup.showLongCenter('电子签OPENID获取失败！')
      } else if (res.info.code === 0 && res.info.data.openId) {
        hlsPopup.showLongCenter('电子签OPENID获取成功！')
      } else {
        hlsPopup.showLongCenter(res.info.msg)
      }
    },
    updateSigningCode (bp_id, flag, code) {
      let vm = this
      let url = process.env.basePath + 'update_signing_code'
      let param = {
        bp_id: bp_id,
        signing_code_flag: flag,
        signing_code: code,
      }
      let res = vm.$post(url, param)
      if (res.result === 'S') {

      } else {
        hlsPopup.showLongCenter(res.info.message)
      }
    },
    // 针对 不同的 状态 去操作
    doStatus (item) {
      if (item.bp_type === 'MANAGER') {
        // 提示不能操作
        return
      }

      this.NowItem = item

      switch (item.bp_status) {
        // 待提交 拒绝或者被退回
        case 'NEW':
        case 'RETURN':
        case 'REJECT':
          this.popSetectBox = true
          break

          // 通过-->解绑
        case 'APPROVED':
          this.unBind(item)
          break

          // 审批中
        default:
          this.changePageHead(item)
      }
    },

    // 选项卡 策略
    typeConfirm (e) {
      this.popSetectBox = false

      // 是修改信息，还是 重新选择用户类型
      if (e.bp_type === '0') {
        this.changePageHead(this.NowItem)
      } else if (e.bp_type === '1') {
        this.unBind(this.NowItem)
      }
    },

    // 解绑，需要等待后端调整后使用
    unBind (item) {
      if (!Object.keys(item).length) return

      let vm = this
      hlsPopup.showConfirm({
        title: '提示',
        content: '确定解除绑定？',
        onConfirm: function (index) {
          if (index === 1) {
            let url = process.env.basePath + 'bp_unbind'
            let param = {
              master: {
                phone: window.localStorage.getItem('user_phone'),
                password: window.localStorage.getItem('password'),
                bp_id: item.bp_id,
              },
            }
            vm.hlsPopup.showLoading('请稍候')

            vm.hlsHttp.post(url, param).then(res => {
              vm.hlsPopup.hideLoading()
              if (res.result === 'S') {
                vm.hlsPopup.showLongCenter('解绑成功')
                // 重新查询一次 用户列表
                vm.getList(item.bp_id === JSON.parse(window.localStorage.getItem('now_user_bp_bind_id')).bp_id)
              } else {
                vm.hlsPopup.showLongCenter(res.message)
              }
            })
          }
        },
      })
    },

    // 获取用户列表，并缓存
    async getList (isNowBind) {
      let url = process.env.basePath + 'user_bp_query'
      let params = { app_user_id: window.localStorage.getItem('app_user_id') }

      try {
        hlsPopup.showLoading('请稍等')
        let query = await this.hlsHttp.post(url, params)

        if (query.result === 'S') {
          this.hlsPopup.hideLoading()

          // 自己添加认证文字
          let register = {
            NP_NO: '电签认证',
            NP_YES: '查询认证状态',
            ORG_YES: '查询认证状态',
            ORG_NO: '电签认证',
            ORG_L_NO: '电签认证',
            ORG_L_YES: '查询认证状态',
            ORG_AUTH_NO: '电签认证',
            ORG_AUTH_YES: '查询认证状态',
          }

          query.lists = query.lists.map(item => {
            item.bp_identity_name = register[item.bp_identity]
            return item
          })

          window.localStorage.setItem('bind-user-list', JSON.stringify(query.lists))
          if (isNowBind) window.localStorage.setItem('now_user_bp_bind_id', JSON.stringify(query.lists.length ? query.lists[0] : {}))

          this.list = query.lists
        } else {
          this.hlsPopup.hideLoading()
          this.hlsPopup.showLongCenter(res.message)
        }
      } catch (error) {
        this.hlsPopup.hideLoading()
      }
    },

    // 修改信息逻辑
    changePageHead (item) {
      if (!Object.keys(item).length) return

      if (item.bp_status === 'APPROVING') {
        this.hlsPopup.showLongCenter('您的绑定申请还在流程中')
        return
      };

      let params = {
        user_bp_name: item.bp_name,
        status: item.bp_status,
        isAGENT: item.bp_type === 'AGENT', // 是否为经销商
        isMultiRole: ['GUTA', 'TENANT', 'AGENT'].includes(item.bp_type), // 是否为 担保人/承租人 能否为多角色
        ...item || {},
      }

      let name = item.bp_class === 'NP' ? 'NPBaseInfo' : 'EnterpriseNew'

      this.$router.push({ name })
      window.localStorage.setItem('handleUser', JSON.stringify(params))
    },
  },
}
</script>

<style lang='less'>
#my-bind-user {
    background-color: rgb(242, 242, 242);
    .scrollContent {
        background-color: rgb(242, 242, 242);
    }

    .bp_name {
        width: 100%;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
    }

    .scroll-box {
        padding: 8px;

        .box {
            display: flex;
            // justify-content: space-between;

            width: 99.9%;
            height: 60px;
            padding: 0 15px 0 10px;
            background-color: #fff;
            border-radius: 8px;
            line-height: 60px;
            font-size: 14px;
            color: rgb(58, 58, 58);
            margin-bottom: 0.15rem;
            img {
                height: 20px;
                vertical-align: text-bottom;
            }

            .name {
                flex: 0 0 65%;
                width: 65%;
                display: flex;
                align-items: center;
            }
        }
    }

    .flag {
        display: flex;
        flex: 0 0 35%;
        width: 35%;
        flex-direction: column;
        justify-content: space-evenly;
        padding-left: .2rem;
        border-left: 1px transparent solid;
        border-image: linear-gradient(
                to bottom,
                #fff 10%,
                #f2f2f2 10%,
                #f2f2f2 50%,
                #f2f2f2 90%,
                #fff 90%
            )
            1 10;

        & > div {
            width: calc(99% - 0.2rem);
            text-overflow: ellipsis;
            overflow: hidden;
            white-space: nowrap;
            height: 20px;
            border-radius: 3px;
            border: 1px solid #1d3fff;
            line-height: 19.5px;
            text-align: center;
            font-size: 13px;
            padding: 0 4px;
            color: #1d3fff;
        }

        .normal {
            background-color: #1d3fff;
            color: white;
            display: flex;
            justify-content: center;
            align-items: center;

            img {
                height: 11px;
                margin-right: 3px;
            }
        }

        .unbind {
            background-color: rgb(255, 206, 206);
            color: red;
            border: 1px solid rgb(255, 206, 206);
        }
    }

    .submit {
        position: absolute;
        box-sizing: border-box;
        height: 35px;
        bottom: 10px;
        left: 50%;
        transform: translateX(-50%);
        color: white;
        padding: 6px 40px;
        font-size: 85%;
        border-radius: 20px;
        background-color: #1d3fff;
        img {
            height: 18px;
            vertical-align: text-bottom;
        }
    }

    .content {
        position: absolute;
        top: 0;
    }

    .scrollContent {
        //padding-top: 1.92rem;
        padding-bottom: 20px;
    }
}

.platform-ios {
    #query {
        .scrollContent {
            padding-top: 2.32rem;
        }
    }
}

// iPhoneX适配
@media (device-width: 375px) and (device-height: 812px) and (-webkit-min-device-pixel-ratio: 3) {
    .platform-ios {
        #query {
            .scrollContent {
                padding-top: 2.72rem;
            }
        }
    }

    #my-bind-user .submit {
        bottom: 44px;
    }
}

// iPhoneXR适配
@media (device-width: 414px) and (device-height: 896px) {
    .platform-ios {
        #query {
            .scrollContent {
                padding-top: 2.72rem;
            }
        }
    }

    #my-bind-user .submit {
        bottom: 44px;
    }
}
</style>
