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

    <JEquiCode bgImg="/static/equipmentImg/big-horn.svg" icon="/static/equipmentImg/horn-white.svg" :qrcAlias="params.deviceName" :qrcId="params.deviceId" @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" :right="params.deviceName" pd="15rpx 40rpx" />

      <JInput name="设备号" textColor="rgba(255, 255,255, 0.6)" :isBorder="true" size="30rpx" :right="params.deviceId" pd="15rpx 40rpx" />

      <JInput name="设备厂商" textColor="rgba(255, 255,255, 0.6)" :isBorder="true" size="30rpx" :right="providerObj[params.provider]" 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">
          {{ params.state ? '启用' : '禁用' }}
          <switch :checked="params.state" 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="!params.mchNo && params.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="params.isSelf && !params.mchNo">
      <JInput icon="/static/iconImg/icon-assign.svg" @tap="selectedAgent.open()" :isBorder="true" name="划拨至代理" textColor="#fff" size="33rpx" :img="true" />
    </JMainCard>
    <template v-if="!params.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="params.agentName" pd="15rpx 40rpx" />

        <JInput name="代理商号" textColor="rgba(255, 255,255, 0.6)" :isBorder="true" size="30rpx" :right="params.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="params.mchNo">
      <!-- <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="params.mchName" pd="15rpx 40rpx" />

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

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

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

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

        <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>

      <JMainCard wrapPd=" 0 50rpx 50rpx 50rpx" bgColor="rgba(0,0,0,0.1)" pd="0">
        <JInput bgColor="rgba(0,0,0,0.2)" @tap="storeOrCode" name="绑定至" :isBorder="true" textColor="#fff" size="33rpx" :right="data.bindCard ? '码牌' : '门店'" :img="true" />
      </JMainCard>

      <!-- 码牌列表 -->
      <view class="bind-title" v-if="data.bindCard">受支持的码牌设备</view>
      <view class="layout-code" v-if="data.bindCard">
        <scroll-view scroll-y="true" style="max-height: 424rpx">
          <view v-for="(item, index) in data.codeDataList" @click.stop="toDetail(item.deviceId)" :key="item.batchId">
            <!-- preStyle 预制主题色 img 图片 。根据 cardList存不存在对应的码牌ID进行切换 -->
            <JPreview
              v-bind="item.info"
              :borderNone="index === data.codeDataList.length - 1"
              :preStyle="data.cardList.includes(item.qrcId) ? 'two' : 'one'"
              :img="data.cardList.includes(item.qrcId) ? '/static/equipmentImg/code-white.svg' : '/static/equipmentImg/code-close.svg'"
            >
              <view @click.stop style="display: flex; align-items: center">
                <switch
                  :checked="data.cardList.includes(item.qrcId)"
                  :disabled="params.bindQrcId == item.qrcId"
                  style="margin-left: 10rpx"
                  color="#bf80ff"
                  @change="onChange($event, item)"
                  @tap="tipsInfo(item)"
                />
              </view>
            </JPreview>
          </view>
        </scroll-view>
      </view>
    </template>

    <JPopup ref="JPopupRef">
      <JMainCard pd="30rpx 0" wrapPd="30rpx">
        <JLine
          iconOn="/pageWork/static/images/store-code.svg"
          iconClose="/pageWork/static/images/code-store.svg"
          name="绑定至门店"
          :isBorder="true"
          :isSelect="!data.bindCard"
          @tap="changeBind(0)"
        />

        <JLine
          iconOn="/pageWork/static/images/store-code.svg"
          iconClose="/pageWork/static/images/code-store.svg"
          name="绑定至码牌"
          :isSelect="data.bindCard"
          @tap="changeBind(1)"
        />
        <view class="tiptext"> 绑定至门店将播报门店下所有设备的收款；绑定至码牌则仅播报受支持的码牌的收款。 </view>
      </JMainCard>

      <JButton pd=" 0 30rpx 30rpx 30rpx" color="#303030" bgColor="rgba(255,255,255,0.8)" pdTop="0" @HandleTouch="JPopupRef.close()">取消</JButton>
    </JPopup>
    <JDeletedTips ref="switchTips" @confirm="confirm" @cancel="cancel" />
    <JDeletedTips ref="unboundTips" @confirm="unbound" />
    <JDeletedTips ref="refTakeBack" @confirm="takeBack" />
    <JDeletedTips ref="refAgain" @confirm="selectedAgent.open()" />
    <SelectedAgent ref="selectedAgent" @confirm="again" />
  </JeepayWrapper>
</template>

<script setup>
import { onLoad, onBackPress, onPageScroll, onShow } from '@dcloudio/uni-app'
import providerObj from '@/util/providerObj.js'
import { ref, reactive, toRaw, nextTick } from 'vue'
import { $unBind, $bindDevice, $getDeviceDetail, $updateDeviceDetail, $getQRcodeList, $allotORtakeBack } from '@/http/apiManager.js'
import JPopup from '@/components/newComponents/JPopup/JPopup.vue'
import JEquiCode from '@/components/newComponents/JEquipment/JEquiCode.vue' // 设备信息
import JHeaderTitle from '@/components/newComponents/JHeaderTitle/JHeaderTitle.vue' // 导航栏
import JEquipmentCode from '@/components/newComponents/JEquipment/JEquipmentCode.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 JButton from '@/components/newComponents/JButton/JButton.vue'
import JPreview from '@/components/newComponents/JPreview/JPreview.vue'
import JDeletedTips from '@/components/newComponents/JDeletedTips/JDeletedTips'
import SelectedAgent from './components/SelectedAgent.vue'
const data = reactive({
  state: false,
  radioShow: false, //控制绑定结果的显示
  cardList: [],
  bindCard: false, //绑定到码牌还是门店
  codeDataList: [], // 码牌信息列表
})
const params = ref({}) // 传参对象
const switchState = ref()
const switchStatePopup = ref()
const JPopupRef = ref(null) // 弹窗组件
const switchTips = ref(null)
const unboundTips = ref(null)
const refTakeBack = ref(null)
const refAgain = ref(null)
const selectedAgent = ref(null)
onLoad((options) => {
  data.deviceType = options.deviceType //设备类型 云喇叭=1
  data.deviceId = options.deviceId //设备编号
})

onShow(() => {
  nextTick(() => {
    getDetails()
  })
})
const getDetails = () => {
  $getDeviceDetail(data.deviceId).then(({ bizData }) => {
    params.value = bizData // 云喇叭详情
    bizData.bindType ? (data.bindCard = true) : (data.bindCard = false) // 绑定到码牌还是门店
    ;(data.cardList = bizData.qrcIdList ? bizData.qrcIdList : []), // 码牌列表
      (data.storeId = bizData.storeId)
    if (bizData.storeName) getCode(bizData.storeId) // 请求码牌列表
  })
}
// 请求码牌信息
const getCode = (storeId) => {
  $getQRcodeList({
    pageNumber: -1,
    qrcBelongType: 2,
    storeId,
  }).then(({ bizData }) => {
    bizData.records.forEach((item) => {
      item.info = {
        title: item.qrcAlias ? item.qrcAlias : '未命名',
        qrcId: item.qrcId,
      }
    })
    data.codeDataList = bizData.records // 保存码牌列表 用于页面渲染
  })
}

// 绑定至码牌还是门店
const storeOrCode = () => JPopupRef.value.open()

// 选择门店或则码牌
const changeBind = (val) => {
  params.value.bindType = Number(val) // 1绑定到码牌 或 0 绑定到门店
  Number(val) ? (data.bindCard = true) : (data.bindCard = false)

  // 如果选择绑定门店则发送请求
  if (!data.bindCard) {
    params.value.bindType = 0 // 绑定到门店传0
    $bindDevice(data.deviceId, params.value)
  } else {
    // 如果选择绑定到码牌，必须存在码牌ID才发送请求
    if (data.cardList.length > 0) {
      params.value.qrcIdList = data.cardList
      $bindDevice(data.deviceId, params.value)
    }
  }
  JPopupRef.value.close()
  // 绑定到码牌是要传入 码牌ID列表的，所以在下面的逻辑中，没开启或关闭一次码牌都要请求一次列表，如果是最后一个码牌，则不允许关闭
}

//码牌开启关闭, 一开始所有的码牌都是关闭的 ,勾一项开一项, 如果只剩最后一个开启的，那么就不允许在关闭了，必须开一个。
const onChange = (e, item) => {
  if (e.detail.value) {
    data.cardList.includes(item.qrcId) ? undefined : data.cardList.push(item.qrcId) // 防止重复添加
  } else {
    let index = data.cardList.indexOf(item.qrcId)
    data.cardList.splice(index, 1)
  }

  params.value.qrcIdList = data.cardList
  $bindDevice(data.deviceId, params.value) // 发送新的请求，同时加入所开启的码牌
}
let flag = undefined
// 切换喇叭状态
function switchChange(e, item) {
  flag = true
  params.value.state = Number(e.detail.value)
  switchTips.value.open('确认修改吗？')
}
const confirm = () => {
  flag = false
  $updateDeviceDetail(data.deviceId, { state: params.value.state }).then(() => {
    uni.showToast({
      title: '修改成功',
      icon: 'success',
    })
  })
}
const cancel = (val) => {
  if (!flag) return
  params.value.state = Number(!params.value.state)
}
// 跳转至绑定页
const bindMch = () => {
  uni.navigateTo({ url: './publicBind?id=' + data.deviceId + '&tag=device&title=云喇叭绑定' })
}

// 跳转至编辑信息
const editInfo = () => {
  uni.navigateTo({
    url: './editHorn?id=' + data.deviceId,
  })
}

// 解绑函数 打开提示弹窗
function unbound() {
  $unBind(params.value.deviceId).then(({ bizData }) => {
    uni.showToast({
      icon: 'none',
      title: '解绑成功',
    })
    uni.navigateBack({
      delta: 1,
    })
  })
}
const takeBack = () => {
  const data = {
    agentNo: params.value.agentNo,
    allotDeviceIds: params.value.deviceId,
    allotOrRecover: 'recover',
    allotType: 'select',
  }
  $allotORtakeBack(data).then((res) => {
    getDetails()
    uni.showToast({ title: '收回成功', icon: 'success' })
  })
}
// 重新划拨
const again = (e) => {
  const data = {
    agentNo: e.text,
    allotDeviceIds: params.value.deviceId,
    allotOrRecover: 'allot',
    allotType: 'select',
  }
  $allotORtakeBack(data).then((res) => {
    uni.showToast({ title: '划拨成功', icon: 'success' })
    getDetails()
    selectedAgent.value.close()
  })
}
// 监听页面滚动 用于给自定义导航栏换背景色
const header = reactive({ bgColor: 'transparent' })
onPageScroll((data) => {
  if (data.scrollTop > 20) {
    header.bgColor = '$primaryColor'
  } else {
    header.bgColor = 'transparent'
  }
})
const tipsInfo = (val) => {
  if (params.value.bindQrcId == val.qrcId) {
    uni.showToast({ title: '平台下发码牌 不能修改状态', icon: 'none' })
  }
}
</script>

<style lang="scss">
page {
  background: $primaryColor;
}
</style>
<style scoped lang="scss">
.bind-title {
  margin-top: 20rpx;
  text-align: center;
  font-size: 33rpx;
  color: #ffffff;
}
.tiptext {
  margin: 10rpx 30rpx 0;
  border-radius: 10rpx;
  background: #f2f2f2;
  padding: 20rpx;
  box-sizing: border-box;
  font-size: 27rpx;
  line-height: 46rpx;
}
.layout-code {
  margin: 30rpx 50rpx;
}
.title {
  margin-top: 20rpx;
  font-size: 33rpx;
  font-weight: 500;
  text-align: center;
  color: #fff;
}
</style>
