<template>
  <page-header-wrapper>

    <div class="div-box">
      <a-card style="box-sizing:border-box;">
        <div class="div-top">
          <div class="modal-div">
            <!-- 码牌列表 -->
            <div class="modal-div1">

              <div class="search">
                <a-input v-model:value="vdata.searchData.qrcId" class="rate-input" placeholder="搜索名称D" />
                <a-button type="primary" @click="reqTableDataFunc"><template #icon><search-outlined /></template>查询</a-button>
                <a-button style="margin-left: 8px" @click="() => vdata.searchData = {} "><reload-outlined />重置</a-button>

                <div class="div-top-title-tio2" @click="getState">
                  <a-button type="link" style="color: #808080 ;"><left-outlined />返回列表页</a-button>
                </div>
              </div>
              <div class="list-table">
                <JeepayTable  ref="infoTable"  :initData="false" :reqTableDataFunc="reqTableDataFunc"  :tableColumns="tableColumns" :searchData="vdata.searchData"  rowKey="qrcId" scrollX="100%" >
                  <template #topBtnSlot>
                    <a-button  type="primary" :loading="vdata.btnLoading" @click="addFunc"><plus-outlined />扫码授权</a-button>
                  </template>
                  <template #bodyCell="{ column, record }">
                    <template v-if="column.key === 'extraJson'">
                      <a :href="record.url" target="_blank"> <img  width="50" height="50" :src="record.thumbUrl" alt=""></a>

                    </template>
                    <template v-if="column.key === 'name'">
                      <div class="my-tooltip-title-box">{{record.name }}</div>
                    </template>
                    <template v-if="column.key === 'choiceFlag'">
                      <JeepayTableColState :state="record.choiceFlag" :showSwitchType="true" :onChange="(state) => { return updateState(record.id, state)}" />
                    </template>

                    <template v-if="column.key == 'op'">
                      <!-- 操作列插槽 -->
                      <a-button  type="link"  style="color: red" @click="delFunc(record.id)">删除</a-button>
                    </template>
                  </template>
                </JeepayTable>
              </div>
            </div>
          </div>
        </div>
      </a-card>
    </div>


    <a-modal
        v-model:visible="vdata.visibleAdd"
        :footer="null"
        @cancel="handleCancel"
        style="top: 35% !important;"
        wrap-class-name="full-modal"
        width="330px"
        title="视频号授权"
        :maskClosable="false"
    >
      <div class="modal-body" style="padding: 0 24px !important;">
        <div >
          <img
              v-if="vdata.scanCodeUrl"
              :src="vdata.scanCodeUrl"
              alt=""
              style=" height: 250px;    text-align: center;width: 100%;"
          >
          <div class="zfb-wx" style="margin: 10px 0">
            <span style="color: grey">请打开微信扫码（确保视频号已实名认证）</span>
          </div>
        </div>
        <!--        <a-button-->
        <!--            type="primary"-->
        <!--            class="cancel"-->
        <!--            size="large"-->
        <!--            block-->
        <!--            @click="vdata.visibleAdd = false"-->
        <!--        >-->
        <!--          取消扫码-->
        <!--        </a-button>-->
      </div>

    </a-modal>

    <SybVideo ref="sybVideoref"  ></SybVideo>
  </page-header-wrapper>
</template>

<script lang="ts" setup>
import {
  API_URL_MCH_QR_CODE_LIST,
  req,
  $qrcShellViewByQrc,
  API_URL_PRODUCT_LIST,
  API_URL_PACKAGE_LIST,
  API_URL_MCH_VIDEO_DATA_LIST,
  $getMchSphVideoTask, $getMchSphVideoAuthTask, $getMainUserInfo, $deleteMchVideo, $getMchChoiceFlag
} from '@/api/manage'
import {reactive, ref, defineExpose, nextTick, getCurrentInstance, defineEmits} from 'vue'

// 导入全局函数
const { $viewerApi,$infoBox } = getCurrentInstance()!.appContext.config.globalProperties

const sybVideoref = ref()

// 定义向父组件 通讯 func
const emit = defineEmits(['itemRender'])

const tableColumns = ref([
  { key: 'name', title: '名称',dataIndex: 'name', align: 'center'},
  { key: 'extraJson', title: '视频地址',dataIndex: 'name' },
  { key: 'choiceFlag', dataIndex: 'choiceFlag', title: '是否使用'},
  { key: 'createTime', dataIndex: 'createTime', title: '创建日期' },
  { key: 'op', title: '操作',  fixed: 'right', align: 'center' }
])

// 当前 table 组件
const infoTable = ref()

// 响应式数据
const vdata :any = reactive ({
  visibleAdd:false,
  btnLoading:false,
  timeoutID:"" as any,
  userInfo:{} as any,
  scanCodeUrl:"",
  visible: false,
  searchData: {},
  selectRecordIdList: [],
  productId:"" as any,
})


async function reqTableDataFunc(params: any) {

  let res = await req.list(API_URL_MCH_VIDEO_DATA_LIST, params);
  var records = res.records;
  for (let i = 0; i < res.records.length; i++) {
    let extraJson  = JSON.parse(res.records[i]["extra"]);
    console.log(extraJson.url,'urlurlurl')
    console.log(extraJson.desc,'extraJson')
    console.log(extraJson.desc.media[0].url,'extraJson')
    console.log(extraJson,'extraJson')
    res.records[i]['extraJson'] = extraJson
    res.records[i]['url'] = extraJson.url
    res.records[i]['name'] = extraJson.url
    res.records[i]['thumbUrl'] = extraJson.desc.media[0].thumbUrl
    // res.records[i]['choiceFlag'] = parseInt(res.records[i].choiceFlag)
  }
  console.log(res,'extraextraextra')
  return res;
}
// 表格搜索
function searchFunc () {
  nextTick(() => {
    infoTable.value.refTable(true)
  })
}


function  updateState (recordId, currState) { // 【更新状态】

  $getMchChoiceFlag(recordId,{choiceFlag:currState}).then((res) => {
    if (currState != res.choiceFlag) {
      $infoBox.message.success("状态已更新");
      searchFunc(); // 更新列表
    } else {
      $infoBox.message.info("状态无变化");
    }
  });
}

// 选择完毕
// function okFunc(){
//   emit('selectFinishFunc',  vdata.selectRecordIdList)
// }
function getVideo(url){

  sybVideoref.value.show(url)

}
function handleCancel(e) {
  clearTimeout(vdata.timeoutID);
  vdata.visibleAdd = false;
}
// 显示
function  show (productId) {

  getMainUserInfo()

  nextTick(() => {
    searchFunc()
  })
  vdata.visible = true
}

function close(){
  vdata.visible = false
}
function getMainUserInfo(){
  $getMainUserInfo().then(res => {
    vdata.userInfo = res
  })
}
// 显示二维码图片
function showQrImgFunc(recordId){
  $qrcShellViewByQrc(recordId).then((res) => {
    $viewerApi({images: [res]})
  })
}
function addFunc(){
  vdata.btnLoading = true
  //登陆
  $getMchSphVideoTask({mchNo:vdata.userInfo.mchNo}).then((res) => {
    getMchSphVideoAuthTask(res.task_id)
  }).catch((error) => {
    vdata.btnLoading = false
  })
}

//获取授权状态
function getMchSphVideoAuthTask(task_id){
  $getMchSphVideoAuthTask(task_id).then((res) => {
    console.log(res,'resres')
    if(res.status == 0){
      vdata.timeoutID =   setTimeout(() => {
        getMchSphVideoAuthTask(task_id)
      }, 1000)
    }else if(res.status == 1){
      vdata.btnLoading = false
      clearTimeout(vdata.timeoutID);
      vdata.scanCodeUrl = res.qr_code_image
      vdata.visibleAdd = true
      vdata.timeoutID = setTimeout(() => {
        getMchSphVideoAuthTask(task_id)
      }, 1000)
    }else{
      vdata.btnLoading = false
      vdata.visibleAdd = false
      vdata.scanCodeUrl = ''
      $infoBox.message.success('授权成功')
      searchFunc()
    }
  }).catch((error) => {
    // setTimeout(() => {
    //   getMchSphVideoAuthTask(task_id)
    // }, 1000)
  })
}
function delFunc(recordId){
  $infoBox.confirmDanger('确认删除？', '', () => {
    $deleteMchVideo(recordId).then((res) => {
      $infoBox.message.success('删除成功')
      searchFunc()
    })
  },() => {
  })
}
function getState(){

  emit('itemRender',{'table':'detail','productId':vdata.productId,'type':6})
}
// 定义对外输出函数
defineExpose( { show, close } )
</script>

<style scoped lang="less">
.modal-div {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  margin:0 20px 30px 20px;

  .modal-div1 {
    width: 100%
  }

  .list-table {
    border-top: 1px solid #ddd;
    border-radius: 6px;
  }
}

.search {

  display: flex;
  margin: 15px 20px;
  .rate-input {

    width: 200px;
    margin-right: 10px;
  }
}
.div-top-title-tio2{
  position: absolute;
  right: 0;
}
</style>
