<template>
  <JeepayWrapper>
    <!-- 顶部自定义导航栏 -->
    <JHeaderTitle title="码牌详情" :bgColor="header.bgColor" color="#fff" imgUrl="/static/iconImg/left-white.svg" />

    <!-- 码牌URL 码牌名字 ID 和编辑板块 -->
    <JEquipmentCode :info="data" @downUrl="downUrl" @editInfo="editInfo" />

    <!-- 码牌信息板块 -->
    <JMainCard wrapPd="30rpx 50rpx" bgColor="rgba(0,0,0,0.1)" pd="25rpx 0">
      <JInput
        name="码牌名"
        textColor="rgba(255, 255,255, 0.6)"
        :isBorder="true"
        size="30rpx"
        align="flex-start"
        :right="data.qrcAlias ? data.qrcAlias : '未命名'"
        pd="15rpx 40rpx"
      />
      <JInput name="码牌ID" textColor="rgba(255, 255,255, 0.6)" :isBorder="true" size="30rpx" :right="data.qrcId" pd="15rpx 40rpx" />
      <JInput
        name="码牌金额"
        textColor="rgba(255, 255,255, 0.6)"
        :isBorder="true"
        size="30rpx"
        :right="data.fixedFlag == 1 ? data.fixedPayAmount / 100 : '任意金额'"
        pd="15rpx 40rpx"
      />

      <JInput name="码牌状态" textColor="rgba(255, 255,255, 0.6)" :isBorder="true" size="30rpx" pd="15rpx 40rpx">
        <view style="color: #fff; maggin-right: 16rpx; font-size: 30rpx" class="dis-wrapper">
          {{ data.qrcState ? '启用' : '禁用' }}
          <switch :checked="data.qrcState" style="margin-left: 20rpx; transform: scale(1.2)" color="#BF80FF" @change="switchChange" />
        </view>
      </JInput>
    </JMainCard>
    <view class="title">绑定/划拨信息</view>
    <!-- 绑定商户 未绑定商户状态 -->
    <JMainCard wrapPd="30rpx 50rpx" bgColor="rgba(0,0,0,0.2)" pd="0" v-if="!data.bindState && data.isSelf">
      <JInput icon="/pageWork/static/images/bindMch.svg" @tap="bindMch" :isBorder="true" name="绑定至商户" textColor="#fff" size="33rpx" :img="true" />
    </JMainCard>
    <JMainCard wrapPd="0 50rpx" bgColor="rgba(0,0,0,0.2)" pd="0" v-if="!data.bindState && data.isSelf">
      <JInput icon="/static/iconImg/icon-assign.svg" @tap="selectedAgent.open()" :isBorder="true" name="划拨至代理" textColor="#fff" size="33rpx" :img="true" />
    </JMainCard>
    <template v-if="!data.isSelf">
      <JMainCard wrapPd="30rpx 50rpx" bgColor="rgba(0,0,0,0.1)" pd="0">
        <JInput name="代理商名称" textColor="rgba(255, 255,255, 0.6)" :isBorder="true" size="30rpx" :right="data.agentName" pd="15rpx 40rpx" />

        <JInput name="代理商号" textColor="rgba(255, 255,255, 0.6)" :isBorder="true" size="30rpx" :right="data.agentNo" pd="15rpx 40rpx" />

        <JInput
          bgColor="rgba(0,0,0,0.2)"
          icon="/static/iconImg/icon-takeBack.svg"
          @tap="refTakeBack.open('收回后代理商将无法使用该设备！')"
          :isBorder="true"
          name="收回"
          textColor="#fff"
          size="33rpx"
          :img="true"
        />

        <JInput
          bgColor="rgba(0,0,0,0.2)"
          icon="/static/iconImg/icon-assign.svg"
          @tap="refAgain.open('确认重新划拨吗？')"
          name="重新划拨"
          borderBg="#7737fe"
          textColor="#fff"
          size="33rpx"
          :img="true"
        />
      </JMainCard>
    </template>
    <!-- 绑定商户状态 -->
    <template v-if="data.bindState">
      <view class="bind-title">绑定信息</view>
      <JMainCard wrapPd="30rpx 50rpx" bgColor="rgba(0,0,0,0.1)" pd="0">
        <JInput name="商户" textColor="rgba(255, 255,255, 0.6)" :isBorder="true" size="30rpx" :right="data.mchName" pd="40rpx 40rpx 15rpx 40rpx" />

        <JInput name="用户号" textColor="rgba(255, 255,255, 0.6)" :isBorder="true" size="30rpx" :right="data.mchNo" pd="15rpx 40rpx" />

        <JInput name="门店" textColor="rgba(255, 255,255, 0.6)" :isBorder="true" size="30rpx" pd="15rpx 40rpx" :right="data.storeName" />

        <JInput name="门店ID" textColor="rgba(255, 255,255, 0.6)" :isBorder="true" size="30rpx" pd="15rpx 40rpx" :right="data.storeId" />

        <JInput name="应用名称" textColor="rgba(255, 255,255, 0.6)" :isBorder="true" size="30rpx" pd="15rpx 40rpx" :right="data.appName" />

        <JInput name="AppID" textColor="rgba(255, 255,255, 0.6)" :isBorder="true" size="30rpx" pd="15rpx 40rpx" :right="data.appId" />

        <JInput
          bgColor="rgba(0,0,0,0.2)"
          icon="/static/equipmentImg/bind.svg"
          @tap="unbinding.open('解绑后商户将无法使用该设备！')"
          :isBorder="true"
          name="解绑"
          textColor="#fff"
          size="33rpx"
          :img="true"
          v-if="entIdList.includes('ENT_DEVICE_QRC_RELIEVE')"
        />

        <JInput bgColor="rgba(0,0,0,0.2)" icon="/static/equipmentImg/bind-again.svg" @tap="bindMch" name="重新绑定" borderBg="#7737fe" textColor="#fff" size="33rpx" :img="true" />
      </JMainCard>

      <!-- 云喇叭设备列表 -->
      <JScroll :requestFun="$getDeviceList" :params="cloudParam" title="受支持的云喇叭列表">
        <template v-slot:default="{ info }">
          <JInput
            bgColor="rgba(0,0,0,0.2)"
            :icon="info.state == 1 ? '/static/equipmentImg/horn-white.svg' : '/static/equipmentImg/horn-close.svg'"
            :textColor="info.state == 1 ? '#fff' : 'rgba(255, 255, 255, 0.6)'"
            rightColor="rgba(255, 255, 255, 0.6)"
            :name="info.deviceName"
            borderBg="#7737fe"
            size="33rpx"
            :right="info.deviceNo"
          />
        </template>
      </JScroll>
    </template>

    <!-- 更改状态对话框 -->
    <jeepayConfirm ref="switchState" />
    <JDeletedTips ref="switchTips" @confirm="confirm" @cancel="cancel" />
    <JDeletedTips ref="unbinding" @confirm="unbound" />
    <JPopup ref="JPopupRef" dir="center" type="top">
      <view style="margin-top: 60rpx"></view>
      <JMainCard wrapPd="75rpx">
        <image :src="data.qrcodeUrl" mode="" class="down-url" />
      </JMainCard>
      <view class="down-btn" @tap.stop="downImg">
        保存至相册
        <image src="/static/equipmentImg/down.svg" mode=""></image>
      </view>
    </JPopup>
    <JDeletedTips ref="refTakeBack" @confirm="takeBack" />
    <JDeletedTips ref="refAgain" @confirm="selectedAgent.open()" />
    <SelectedAgent ref="selectedAgent" @confirm="again" />
  </JeepayWrapper>
</template>

<script setup>
import { onLoad, onBackPress, onShow, onPageScroll } from '@dcloudio/uni-app'
import { ref, reactive, toRaw, nextTick } from 'vue'
import {
  $upDateQRcodeList,
  $getQRcode,
  $qrcodeBind,
  $getQRcodeDetail,
  $getMerList,
  $getMchStoreList,
  $getMchAppList,
  $getDeviceList,
  $qrCodeAllotORTakeBack,
} from '@/http/apiManager.js'
import { saveHeadImgFile } from '@/util/saveImg.js'
import jeepayConfirm from '@/components/jeepayConfirm/jeepayConfirm.vue'
import qrcode from '@/util/qrcode.js'
import JDeletedTips from '@/components/newComponents/JDeletedTips/JDeletedTips'
import JHeaderTitle from '@/components/newComponents/JHeaderTitle/JHeaderTitle.vue' // 导航栏
import JEquipmentCode from '@/components/newComponents/JEquipment/JEquipmentCode.vue' // 设备信息
import JPopup from '@/components/newComponents/JPopup/JPopup.vue' // 弹窗
import JMainCard from '@/components/newComponents/JMainCard/JMainCard.vue' // 卡片
import JInput from '@/components/newComponents/JInput/JInput.vue'
import JLine from '@/components/newComponents/JLine/JLine.vue'
import JScroll from '@/components/newComponents/JScroll/JScroll.vue'
import SelectedAgent from './components/SelectedAgent.vue'
// 获取用户信息
import storageManage from "@/util/storageManage.js"
const entIdList = ref( storageManage.userInfo().entIdList)
const JPopupRef = ref(null)
const switchState = ref(null) //
const data = reactive({})
const switchTips = ref(null) //切换状态弹窗
const unbinding = ref(null) //解绑确认弹窗
const refTakeBack = ref(null)
const refAgain = ref(null)
const selectedAgent = ref(null)
// 请求云喇叭列表的传参
const cloudParam = reactive({ deviceType: 1, mchNo: '' })

// 保存图片
const downUrl = () => JPopupRef.value.open('')

// 跳转至编辑页
const editInfo = () => {
  uni.navigateTo({ url: './editCode?id=' + data.qrcId })
}

onLoad((options) => {
  data.qrcId = options.id
})

onShow(() => {
  nextTick(() => {
    getDetail()
  })
})

const getDetail = () => {
  $getQRcodeDetail(data.qrcId).then(({ bizData }) => {
    drawQRcode(bizData.qrUrl)
    Object.assign(data, bizData)
    cloudParam.mchNo = data.mchNo
  })
}

function drawQRcode(url) {
  if (url) {
    let params = url // 二维码参数
    var imgData = qrcode.drawImg(params, {
      typeNumber: 4, // 密度
      errorCorrectLevel: 'Q', // 纠错等级
      size: 175, // 白色边框
    })
    data.qrcodeUrl = imgData
  } else {
    data.qrcodeUrl = '../../static/img/nodata.jpg'
  }
}
let flag = undefined
// 切换状态
function switchChange(e) {
  flag = true
  data.qrcState = Number(e.detail.value)
  switchTips.value.open('确认修改？')
}
const confirm = () => {
  flag = false
  $upDateQRcodeList(data.qrcId, { qrcState: data.qrcState }).then(() => {
    uni.showToast({
      title: '修改成功',
      icon: 'success',
    })
  })
}
const cancel = () => {
  if (!flag) return
  data.qrcState = Number(!data.qrcState)
}
// 跳转至绑定页
const bindMch = () => {
  uni.navigateTo({ url: './publicBind?id=' + data.qrcId + '&tag=code&title=绑定码牌' })
}

// 监听页面滚动 用于给自定义导航栏换背景色
const header = reactive({ bgColor: 'transparent' })
onPageScroll((data) => {
  if (data.scrollTop > 20) {
    header.bgColor = '$primaryColor'
  } else {
    header.bgColor = 'transparent'
  }
})

// 解绑函数
function unbound() {
  $upDateQRcodeList(data.qrcId, { bindState: 0 }).then(({ bizData }) => {
    uni.showToast({
      icon: 'none',
      title: '解绑成功',
    })
    uni.navigateBack({
      delta: 1,
    })
  })
}

function downImg() {
  // #ifdef  APP-PLUS
  saveHeadImgFile(data.qrcodeUrl, 80)
    .then((success) => {
      uni.showToast({
        title: '保存成功',
      })
      setTimeout(function () {
        JPopupRef.value.close()
      }, 1500)
    })
    .catch((err) => {
      uni.showToast({
        icon: 'none',
        title: '保存失败',
      })
    })
  // #endif
  //#ifdef MP-WEIXIN
  downloadQR()
  //#endif
}

//#ifdef MP-WEIXIN
function downloadQR() {
  wx.getSetting({
    //获取权限
    success(res) {
      if (res.authSetting['scope.writePhotosAlbum']) {
        download(data.qrcUrl)
      } else {
        wx.authorize({
          scope: 'scope.writePhotosAlbum',
          success() {
            download(data.qrcodeUrl)
          },
        })
      }
    },
  })
}
function download(data) {
  const fileManager = wx.getFileSystemManager()
  const filePath = wx.env.USER_DATA_PATH + '/res.png'
  //这块是定义图片的名称，可自定义其他
  fileManager.writeFile({
    filePath: filePath,
    data: data.slice(22),
    encoding: 'base64',
    success: (res) => {
      wx.saveImageToPhotosAlbum({
        filePath: filePath,
        success: function (res) {
          //保存成功
          uni.showToast({
            title: '保存成功',
          })
        },
        fail: function (err) {
          console.log(err)
          //保存失败
          uni.showToast({
            icon: 'none',
            title: '保存失败',
          })
        },
      })
    },
    fail: (err) => {
      uni.showToast({
        icon: 'none',
        title: '保存失败',
      })
    },
  })
}
//#endif

const takeBack = () => {
  const params = {
    agentNo: data.agentNo,
    allotIds: data.qrcId,
    allotOrRecover: 'recover',
    allotType: 'select',
  }
  $qrCodeAllotORTakeBack(params).then((res) => {
    getDetail()
    uni.showToast({ title: '收回成功', icon: 'success' })
  })
}
// 重新划拨
const again = (e) => {
  const params = {
    agentNo: e.text,
    allotIds: data.qrcId,
    allotOrRecover: 'allot',
    allotType: 'select',
  }
  $qrCodeAllotORTakeBack(params).then((res) => {
    uni.showToast({ title: '划拨成功', icon: 'success' })
    selectedAgent.value.close()
    getDetail()
    data.isSelf = false
  })
}
</script>
<style lang="scss">
page {
  background: $primaryColor;
}
</style>
<style scoped lang="scss">
.down-url {
  width: 500rpx;
  height: 500rpx;
}
.down-btn {
  width: 500rpx;
  height: 110rpx;
  border-radius: 20rpx;
  background: rgba(255, 255, 255, 0.8);
  padding: 32rpx;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 0 auto;
  margin-top: -20rpx;
  image {
    width: 36rpx;
    height: 36rpx;
  }
}
.bind-title {
  margin-top: 20rpx;
  text-align: center;
  font-size: 33rpx;
  color: #ffffff;
}
.title {
  margin-top: 20rpx;
  font-size: 33rpx;
  font-weight: 500;
  text-align: center;
  color: #fff;
}
</style>
