<template>
  <div class="hostList">
    <div>
      <div style="display: flex;">
        <el-select v-model="searchForm.country" filterable placeholder="选择国家" size="large" style="width: 240px">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <div></div>
        <el-date-picker v-model="searchForm.time" type="date" value-format="YYYYMMDD" placeholder="选择查询时间" size="large"
          style="margin-left: 50px;" />

        <el-button class="serch-button" style="margin-left: 50px;" type="primary" @click="serch">查询</el-button>
        <el-button class="put-button" :disabled="tableData.length == 0" type="primary"
          @click="exportList">导出Excel数据</el-button>
        <el-button v-if="userInfo.userType == 3" class="put-button" type="primary"
          @click="dialogFormVisible = true">分配给指定员工</el-button>
        <el-button @click="filterdialogVisible = true" style="width: 50px;" class="put-button" type="primary"><img
            style="height: 30px;" src="@/assets/filter.png"></el-button>
      </div>

      <div class="hostTable center-justify">
        <el-table ref="multipleTableRef" :data="tableData" stripe v-loading="loading" height="500"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="35" />
          <el-table-column fixed prop="hostId" label="主播id" width="160">
            <template #default="scope">
              <div class="hostIdText" @click="openHTML(scope.row.hostId)"> {{ scope.row.hostId }}</div>

            </template>
          </el-table-column>
          <!-- <el-table-column prop="hostName" label="主播名字" min-width="160">
            <template #default="scope">
              {{ scope.row.hostName }}
            </template>
          </el-table-column> -->
          <el-table-column prop="hostlevel" label="等级" width="120">
            <template #default="scope">
              {{ scope.row.hostlevel }}
            </template>
          </el-table-column>
          <el-table-column v-for="label in labelList" :key="label.paramCode" :prop="label.paramCode"
            :label="label.paramCodeMeaning" width="120">
            <template v-if="label.paramCode != 'createDt'" #default="scope">
              <el-popover v-if="!(label.paramCode == 'hostcoins' || label.paramCode == 'ysthostcoins')"
                placement="bottom" :width="600" trigger="hover">
                <div style="height: 300px;">
                  <component :is="EChartsComponent" v-if="isPopoverVisible[`${scope.row.hostId}-${label.paramCode}`]"
                    :title="label.paramCodeMeaning" :id="scope.row.hostId" :dataType="label.paramCode"
                    :time="searchForm.time"></component>
                </div>
                <template #reference>
                  <span @mouseover="openPopover(scope.row.hostId, label.paramCode)"
                    @mouseout="closePopover(scope.row.hostId, label.paramCode)">
                    {{ scope.row[label.paramCode] }}
                  </span>
                </template>
              </el-popover>

              <el-popover v-else placement="bottom" :width="500" trigger="hover">
                <div style="height: 300px;">
                  <component :is="EChartsComponent" v-if="isPopoverVisible[`${scope.row.hostId}-${label.paramCode}`]"
                    :title="label.paramCodeMeaning" :id="scope.row.hostId" :dataType="label.paramCode"
                    :time="searchForm.time">
                  </component>
                </div>
                <template #reference>
                  <!-- 鼠标移入时开启 -->

                  <span @mouseover="openPopover(scope.row.hostId, label.paramCode)"
                    @mouseout="closePopover(scope.row.hostId, label.paramCode)">
                    {{ scope.row[label.paramCode] }}
                  </span>
                </template>
              </el-popover>
            </template>
          </el-table-column>

          <el-table-column fixed="right" label="操作" width="120">
            <template #default="scope">

              <el-popover placement="top-start" :width="200" trigger="hover" :content="scope.row.comment">
                <template #reference>
                  <el-button @click="openComment(scope.row)" link type="primary" size="small">维护情况</el-button>
                </template>
              </el-popover>


              <select @change="handleSelectChange($event, scope.row)" v-model="scope.row.useable" class="m-2"
                placeholder="Select" size="small" style="width: 70px">
                <option label="未转化" value="N" />
                <option label="已转化" value="Y" />
              </select>

              <el-dialog :modal="false" v-model="commentVisible" title="维护情况" align-center>
                <el-input maxlength="80" v-model="commentInfo" placeholder="请输入维护情况" clearable show-word-limit />
                <template #footer>
                  <span class="dialog-footer">
                    <el-button @click="commentVisible = false">取消</el-button>
                    <el-button type="primary" @click="uphostcomment()">
                      提交
                    </el-button>
                  </span>
                </template>
              </el-dialog>

            </template>
          </el-table-column>
          <!-- <el-table-column label="操作">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <el-button type="primary" @click="getTkhostdetail(scope.row.hostId)">查看</el-button>
              </div>
            </template>
          </el-table-column> -->
        </el-table>
      </div>
      <div class="center-justify" style="margin-top: 30px;">
        <el-pagination v-model:current-page="page" v-model:page-size="pageSize" background
          layout="sizes, prev, pager, next" :total="total" :page-sizes="[10, 20, 50, 100]"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>



    <el-dialog v-model="dialogFormVisible" title="分配主播" align-center>
      <el-select v-model="staffValue" filterable placeholder="Select" style="width: 240px">
        <el-option v-for="item in staffOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="allocation">
            分配
          </el-button>
        </span>
      </template>
    </el-dialog>


    <el-dialog v-model="filterdialogVisible" width="800px">
      <el-row :gutter="20">
        <el-col :span="8">
          <label>选择筛选条件</label>
          <el-select v-model="searchForm.dataType" filterable placeholder="筛选条件" style="width: 240px">
            <el-option v-for="item in filterOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-col>
        <el-col :span="8">
          <div v-if="!(searchForm.dataType == 'InvitationType')"><label>最小值</label></div>
          <div v-else><label>普票/金票</label></div>

          <el-input v-show="!(searchForm.dataType == 'InvitationType')" type="number" v-model="searchForm.dataStart"
            placeholder="请输入最小值" />
          <el-select v-show="(searchForm.dataType == 'InvitationType')" v-model="searchForm.dataStart" filterable
            placeholder="请选择" style="width: 240px">
            <el-option v-for="item in [{ label: '普票', value: '1' }, { label: '金票', value: '2' }]" :key="item.value"
              :label="item.label" :value="item.value" />
          </el-select>
        </el-col>
        <el-col :span="8">
          <div v-show="!(searchForm.dataType == 'InvitationType')"><label>最大值</label></div>

          <el-input v-show="!(searchForm.dataType == 'InvitationType')" type="number" v-model="searchForm.dataEnd"
            placeholder="请输入最大值" />
        </el-col>
      </el-row>

      <template #footer>
        <span class="dialog-footer">
          <!-- <el-button @click="filterdialogVisible = false">取消</el-button> -->
          <el-button type="primary" @click="filterdialogVisible = false">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>



  </div>
</template>

<script setup>
// import { getToken, setToken, removeToken } from '@/utils/storage'
import { tkhostdata, dicts, tkhostdetail, downList, getStaffList, managerhosts, upholdinfo, getCountryinfo } from '@/api/account';
import { usePythonBridge, } from '@/utils/pythonBridge'
import { getUser } from '@/utils/storage'
import { ref, reactive, onMounted } from 'vue';
import EChartsComponent from '@/components/EChartsComponent.vue';
import { ElMessage, ElMessageBox } from 'element-plus'

const loading = ref(false)
//py方法
const { givePyAnchorId, exportToExcel } = usePythonBridge();

let num = ref(0)
//账号信息 
const userInfo = ref(getUser())
//主播列表DOM
const multipleTableRef = ref(null)

let labelList = ref([])
const tableData = ref([])
//选择国家
const searchForm = ref({
  country: '',
  time: new Date().toISOString().split('T')[0].replace(/-/g, ''),
  dataType: '',
  dataStart: '',
  dataEnd: '',
})

//员工选择列表
let staffOptions = ref([])
//筛选条件选择列表
let filterOptions = ref([])
//选择的员工
let staffValue = ref('')
//选择的主播列表
let selectHostList = ref([])
//分配弹窗是否弹出
let dialogFormVisible = ref(false)
//备注弹窗是否弹出
let commentVisible = ref(false)
//筛选弹窗是否弹出
let filterdialogVisible = ref(false)

//备注信息
let commentInfo = ref('')
//备注信息主播
let commentHost = ref('')
//分页
let pageSize = ref(10)
let page = ref(1)
let total = ref(0)
//是否渲染
const isPopoverVisible = reactive({})


let options = ref([])

onMounted(() => {
  //获取字典
  getdictionary()
  //获取下级员工
  getStaff();
  //获取国家
  getCountry();
})

function serch() {

  getlist();
}

function exportList() {
  if (searchForm.value.dataType == 'InvitationType') {
    searchForm.value.dataEnd = searchForm.value.dataStart
  }
  exportToExcel({
    searchTime: searchForm.value.time,
    region: searchForm.value.country,
    dataType: searchForm.value.dataType == '' ? null : searchForm.value.dataType,
    dataStart: searchForm.value.dataStart == '' ? null : searchForm.value.dataStart,
    dataEnd: searchForm.value.dataEnd == '' ? null : searchForm.value.dataEnd,
    pageSize: pageSize.value,
    page: page.value,
    userId: userInfo.value.userId,
    userType: userInfo.value.userType
  })


  // //浏览器导出方法
  // downList('export/hostsinfo',
  //   {
  //     searchTime: searchForm.value.time,
  //     region: searchForm.value.country,
  //     pageSize: pageSize.value,
  //     page: page.value,
  //     userId: userInfo.value.userId,
  //     userType: userInfo.value.userType
  //   }
  // );

}
//分页每页条数
function handleSizeChange(val) {
  console.log(`${val} items per page`)
  getlist();

}
//分页页数
function handleCurrentChange(val) {
  console.log(`current page: ${val}`)
  getlist();

}
//选择行
function handleSelectionChange(data) {
  console.log(data)
  data.forEach(item => {
    selectHostList.value.push(item.hostId)
  })
  // multipleTableRef.value = data
  // console.log(multipleTableRef.value)

}
//获取主播列表
const getlist = () => {
  if (searchForm.value.dataType == 'InvitationType') {
    searchForm.value.dataEnd = searchForm.value.dataStart
  }



  loading.value = true
  console.log(searchForm.value)
  tkhostdata({
    searchTime: searchForm.value.time,
    region: searchForm.value.country,
    dataType: searchForm.value.dataType == '' ? null : searchForm.value.dataType,
    dataStart: searchForm.value.dataStart == '' ? null : searchForm.value.dataStart,
    dataEnd: searchForm.value.dataEnd == '' ? null : searchForm.value.dataEnd,
    pageSize: pageSize.value,
    page: page.value,
    userId: userInfo.value.userId,
    userType: userInfo.value.userType
  }).then(res => {
    loading.value = false
    total.value = res.total
    tableData.value = []
    res.records.forEach(item => {
      if (item.infoMap.InvitationType == '1') {
        item.infoMap.InvitationType = '普票'
      } else if (item.infoMap.InvitationType == '2') {
        item.infoMap.InvitationType = '金票'

      }
      console.log(item.infoMap)
      item = { ...item, ...item.infoMap }
      tableData.value.push(item)
    })
  })

}

function openComment(data) {
  console.log(data)
  commentInfo.value = data.comment
  commentHost.value = data.hostId
  commentVisible.value = true
}

//修改主播维护状态
function handleSelectChange(event, data) {

  upholdinfo({
    "hostId": data.hostId,
    "userId": userInfo.value.userId,
    "tenantId": userInfo.value.tenantId,
    // "comment": "我已经尽力维护，但是失败了",
    "useable": event.target.value
  }).then(res => {
    console.log(res)
  })
}

//更改主播维护备注

function uphostcomment() {
  upholdinfo({
    "hostId": commentHost.value,
    "userId": userInfo.value.userId,
    "tenantId": userInfo.value.tenantId,
    "comment": commentInfo.value,
  }).then(res => {
    console.log(res)
    serch()
    commentVisible.value = false
  })
}
//获取字典
const getdictionary = () => {
  dicts({
    paramType: "hostsdata",
    // page: 1,
    offset: 1,
    pageSize: 100
  }).then(res => {
    // labelList.value = res.records
    labelList.value = res
    console.log(labelList.value)
    labelList.value.forEach(item => {
      filterOptions.value.push({
        value: item.paramCode,
        label: item.paramCodeMeaning
      })
    })

  })

}

//获取国家
function getCountry() {
  getCountryinfo({}).then(res => {
    console.log(res)
    res.forEach(item => {
      options.value.push({ value: item.countryGroupName, label: item.countryGroupName })
    })
    console.log(options.value)
  })
}

//获取下级员工
const getStaff = () => {
  getStaffList({
    userId: userInfo.value.userId,
    userType: userInfo.value.userType,
    activeYn: userInfo.value.activeYn,
    tenantId: userInfo.value.tenantId,
  }).then(res => {
    console.log(res)
    res.forEach(item => {
      staffOptions.value.push({
        value: item.userId,
        label: item.userName
      })
    })
  })

}
//分配主播给员工
function allocation() {
  managerhosts({
    "manaId": userInfo.value.userId,
    "userId": staffValue.value,
    "tenantId": userInfo.value.tenantId,
    "hostIds": selectHostList.value
  }).then(res => {
    if (res) {
      dialogFormVisible.value = false

    }
  })
}


//获取主播信息
const getTkhostdetail = (id) => {
  tkhostdetail({
    hostId: id,
    // page: 1,
    searchTimeStart: '20250401',
    searchTimeEnd: '20250403'
  }).then(res => {

    console.log(labelList.value)

  })

}


function openPopover(hostId, paramCode) {

  isPopoverVisible[`${hostId}-${paramCode}`] = true;


}

function closePopover(hostId, paramCode) {

  // isPopoverVisible[`${hostId}-${paramCode}`] = false;
}


function openHTML(id) {
  givePyAnchorId(id)

}
</script>

<style lang="less">
.hostList {
  box-sizing: border-box;
  // height: 100vh;
  width: 100%;
  padding: 40px;

  /* 页面无法选中 */
  // -webkit-user-select: none;
  // -moz-user-select: none;
  // -ms-user-select: none;
  // user-select: none;

  .hostTable {
    width: 100%;
    padding: 40px 0;

    .hostIdText {
      text-decoration: underline;
      cursor: pointer;
      color: #0f0092;
    }
  }

  .serch-button {
    width: 80px;
    height: 47px;
    background: #E7CA92;
    border-radius: 10px;
    border: none;
  }

  .put-button {
    width: 132px;
    height: 47px;
    background: #E7CA92;
    border-radius: 10px;
    border: none;

  }
}

.el-dialog {

  --el-dialog-font-line-height: 50px;
  --el-dialog-width: 600px;
  --el-dialog-border-radius: 8px;
}

.center-line {
  display: flex;
  flex-direction: column;
  align-items: center;
  // justify-content: center;
}

.center-justify {
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.center-align {
  display: flex;
  justify-content: space-between;

}

.center-flex {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>

<style scoped>
::v-deep(.el-input__wrapper) {
  background-color: #F2FAF9;
  border: 1px solid #B7CEC5;
  height: 44px;
}

::v-deep(.el-select__wrapper) {
  background-color: #F2FAF9;
  border: 1px solid #B7CEC5;
  height: 48px;
}

::v-deep(.el-pagination.is-background .el-pager li.is-active) {
  background-color: #338F6A;
}
</style>