<!--
 * @author wangzhuo
 * @date 2025年8月19日
 * @description 主归属人变更
-->
<template>
  <view class="con-body">
    <view class="con-bg">
      <!-- 头部 -->
      <customHeader ref="customHeaderRef" :title="'客户人员信息'" :leftFlag="true" :rightFlag="false">
      </customHeader>

      <!-- 高度来避免头部遮挡 -->
      <view class="top-height" :style="{ paddingTop: navBarPaddingTop + 'px' }"></view>

      <!-- 正文内容 -->
      <view class="all-body">
        <!-- 搜索  @blur="blur" @focus="focus" @input="input" @cancel="cancel" @clear="clear"-->
        <view class="search">
          <uni-search-bar class="custom-search" radius="28" placeholder="请输入客户人员名称" clearButton="auto"
                          cancelButton="none" bgColor="#6FA2F8" textColor="#ffffff"
                          v-model="searchValue" @clear="clearSearchValue"
          />
        </view>

        <!-- 分页部分  top="68rpx" -->
        <mescroll-uni  ref="mescrollRef" @init="mescrollInit" @down="downCallback" @up="upCallback"
                      :up="upOption" :down="downOption" :fixed="false" textColor="#ffffff" bgColor="#ffffff"
                      class="scroll-h" :class="{'loading-scroll':cssFlag}"
        >
          <block v-for="(item, index) in list" :key="index">
            <view class="white-bg margin-bottom20"
                  @touchstart="handleTouchStart(item)"
                  @touchend="handleTouchEnd"
                  v-if="item && item.auditStatus !== '办事处审核通过'"
            >
              <view class="report-list">
                <view class="w-b-title title" @dblclick.stop="handleDetail(item)">
                  {{ item.cusName }}
                  <!--<view v-if="item.nodeCode" class="r-right btn-edit" @click.prevent="handleCopyInfo(item)"> 复制信息 </view>-->
                </view>
                <view class="r-list">
                  <view class="r-left">客户人员名称</view>
                  <view class="r-right">{{ item.userName }}</view>
                </view>
                <view class="border-bottom"></view>

                <view class="r-list">
                  <view class="r-left">性别</view>
                  <view class="r-right">{{ item.sex }}</view>
                </view>
                <view class="border-bottom"></view>

                <view class="r-list">
                  <view class="r-left">手机号</view>
                  <view class="r-right">{{ item.mobilePhone || item.iphone }}</view>
                </view>
                <view class="border-bottom"></view>

                <view class="r-list">
                  <view class="r-left">部门</view>
                  <view class="r-right">{{ item.userDept }}</view>
                </view>
                <view class="border-bottom"></view>

                <view class="r-list">
                  <view class="r-left">业务员认定等级</view>
                  <view class="r-right">{{ item.salesmanThinkLevel }}</view>
                </view>

                <!--<view v-if="item.systemThinkLevel" class="r-list">
                  <view class="r-left">系统认定等级</view>
                  <view class="r-right">{{ item.systemThinkLevel }}</view>
                </view>-->

              </view>
            </view>
          </block>
        </mescroll-uni>
      </view>
    </view>
  </view>
</template>

<script setup>
import {ref, onMounted, watch} from 'vue'
import customHeader from '@/components/customHeader.vue'
import MescrollUni from 'mescroll-uni/mescroll-uni.vue';
import {getNavBarPaddingTop} from '@/utils/system.js'
import {SearchForAllPerson} from "@/api/crm/customer/getCustomer"
import {submissionOfChangeOfMainOwner} from "@/api/crm/customer/updateCustomer"

// 获取导航栏高度用于内容区域padding
const navBarPaddingTop = ref(0);
onMounted(() => {
  navBarPaddingTop.value = getNavBarPaddingTop() * 2;
})
// 搜索内容
let searchValue = ref(null);
// 分页
const mescrollRef = ref(null);
// 防抖计时
let timerId = null;
// 查询搜索跳转
let handleSearch = () => {
  // 防抖搜索    console.log(searchValue.value)
  if (timerId) clearTimeout(timerId);
  timerId = setTimeout(async () => {

    // let res = await getList(1, upOption.value.page.size)
    await downCallback(mescrollRef.value.mescroll);
    clearTimeout(timerId);
    timerId = null;
  }, 500)
}

watch(searchValue, (newValue, oldValue) => {
  handleSearch()
})
let clearSearchValue = () => {
  searchValue.value = '';
}
// 查询列表
let list = ref([]);

const upOption = ref({
  page: {num: 0, size: 10},
  noMoreSize: 5,
  empty: {tip: '~ 空空如也 ~'},
  textLoading: '加载中...',
  textNoMore: '已经到底了'
});

const downOption = ref({
  auto: true,
  textInOffset: '下拉刷新',
  textOutOffset: '释放更新',
  textLoading: '刷新中...'
});

let cssFlag = ref(false);//控制样式
const mescrollInit = (mescroll) => {
  cssFlag.value = true;
  mescrollRef.value = mescroll;
};

// 下拉刷新
const downCallback = async (mescroll) => {
  try {
    uni.showLoading();
    cssFlag.value = true;
    setTimeout(async () => {
      // 重置页码为第一页
      const res = await getList(1, mescroll.size || upOption.page.size);
      list.value = res.list;
      cssFlag.value = false;
      // 正确传递 total 参数
      mescroll.endSuccess(res.list.length, res.total >= mescroll.size);
      uni.hideLoading();

    }, 500);
  } catch (error) {
    console.log(error)
    mescroll.endErr();
  }
}
// 上拉加载更多
const upCallback = async (mescroll) => {
  try {
    uni.showLoading();
    setTimeout(async () => {
      // 使用 mescroll 提供的页码和大小参数
      const res = await getList(mescroll.num, mescroll.size);
      if (mescroll.num === 1) {
        list.value = res.list;
      } else {
        list.value.push(...res.list);
      }
      // 正确判断是否还有更多数据
      mescroll.endSuccess(res.list.length, res.total >= mescroll.size);
      uni.hideLoading();
    }, 500);
  } catch (error) {
    console.log(error)
    mescroll.endErr();
  }
}

// 获取数据列表
const getList = (pageIndex, pageSize) => {
  return new Promise(async (resolve) => {
    let param = {
      pageNum: pageIndex,
      pageSize,
      searchContent: searchValue.value
    }

    let res = await SearchForAllPerson(param);
    resolve({
      list: res.rows,
      total: res.total
    });
  });
}

// 跳转到详情
let handleDetail = (item) => {
  uni.navigateTo({
    url: "/pages/business/CRM/customer/components/customerUserEdit",
    events: {},
    success(res) {
      res.eventChannel.emit('editCusData', {param: item, isAdd: false})
    }
  })
}

// 长按定时器ID
let touchTimerId = null;

// 开始触摸
let handleTouchStart = (item) => {
  touchTimerId = setTimeout(() => {
    // console.log(item, "长按客户人员项")
    handleChange(item)

    clearTimeout(touchTimerId);
  }, 1500)
}

// 结束触摸
let handleTouchEnd = () => {
  if (touchTimerId !== null) {
    clearTimeout(touchTimerId);
  }
}

// 变更主归属人
let handleChange = (item) => {

  uni.showModal({
    title: '是否将该客户人员主的归属人变更为自己？',
    editable: true,
    placeholderText: '请输入变更理由',
    success(res) {
      if (res.confirm) {
        if (res.content) {
          submissionOfChangeOfMainOwner({
            userId: item.userId,
            userName: item.userName,
            reasonForChange: res.content
          }).then(res => {
            if (res.code === 200) {
              uni.showToast({
                title: '操作成功'
              })
            } else {
              uni.showToast({
                title: '操作失败',
                icon: 'error'
              })
            }
          })
        } else {
          uni.showToast({
            title: '操作失败！变更原因不能为空',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 复制信息
let handleCopyInfo = (item) => {
  const {cusName, userName, sex, iphone, mobilePhone, jobTelphone, userDept, salesmanThinkLevel} = item;
  /*  item = JSON.stringify({
      '客户名称':item.cusName,
      '客户人员名称': item.userName,
      '性别': item.sex,
      '手机号': item.iphone || item.mobilePhone || item.jobTelphone,
      '部门': item.userDept,
      '业务员认定等级': item.salesmanThinkLevel}
    );
    console.log(item, '复制信息');*/
  uni.setClipboardData({
    data: `客户名称：${cusName}
客户人员名称：${userName}
性别：${iphone || mobilePhone || jobTelphone}
部门：${userDept}
业务员认定等级：${salesmanThinkLevel}`,
    success: function () {
      uni.showToast({
        title: '已复制到剪贴板',
        icon: 'none'
      })
    }
  });

}
</script>

<style lang="scss" scoped>
.all-body {
  /* #ifdef APP-PLUS */
  top: 150rpx;
  height: calc(100vh - 75px);
  /* #endif */
  /* #ifndef APP-PLUS */
  top: 120rpx;
  height: calc(100vh);
  /* #endif */
}


.search .btn-search {
  border: none;
  background: none;
  line-height: normal;
  color: #fff;
  line-height: 56rpx !important;
  padding: 10rpx 0 0;
  text-align: left;
  cursor: pointer;
}

.search .btn-search::after {
  display: none;
}

.scroll-h {
  /* #ifdef APP-PLUS */
  height: calc(100vh - 120px);
  /* #endif */
  /* #ifndef APP-PLUS */
  height: calc(100vh - 110px);
  /* #endif */
}

.white-bg {
  padding-bottom: 10rpx;

  .w-b-title {
    align-items: flex-start;
  }
}

.white-bg:hover {
  //background-color: #f1f1f1;
  background-color: #f1f1f1; /* Chrome, Safari, Opera */
  box-shadow: 0px 0px 5rpx white;
  //filter: rgba(237, 242, 250, 0.5);
}
</style>