<template>
  <view class="con-body">
    <view class="con-bg">
      <!-- 头部 -->
      <customHeader ref="customHeaderRef" :title="'走访报告列表'" :leftFlag="true" :rightFlag="true">
        <template #right>
          <view class="head-right" @click="handleAdd">
            <uni-icons type="plus" size="24" color="#B7D2FF"></uni-icons>新增
          </view>
        </template>
      </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" />
          <button type="default" @click="handleSearch" size="mini" class="btn-search">查询</button>
        </view>

        <!-- 分页部分  -->
        <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 }">
          <view class="white-bg margin-bottom20" v-for="(item, index) in list" :key="index"
                @touchstart.prevent="touchstart(item)" @touchend.prevent="touchend">
            <view>
              <view class="report-list">
                <view class="title">客户：{{ item.cusName }}</view>
                <view class="r-list">
                  <view class="r-name">{{ item.visistCode }}</view>
                  <view @touchstart.stop="handleStatusTouchStart"
                        @touchend.stop="handleStatusTouchEnd" @click.stop="chooseStatus(item)">
                    <view v-if="item.status == '驳回'" class="r-right btn-orange" size="mini">
                      {{ item.status == '驳回' ? '再次提交' : item.status }}
                    </view>
                    <view v-else class="r-right btn-orange" size="mini">
                      {{ item.status }}
                    </view>
                  </view>

                </view>
                <view class="border-bottom"></view>
                <view class="r-list">
                  <view class="r-left">报告类型</view>
                  <view class="r-right">{{ item.visistType }}</view>
                </view>
                <view class="r-list" v-if="item.joinUser!=null">
                  <view class="r-left">我方领导</view>
                  <view class="r-right">{{ item.joinUser }}</view>
                </view>
                <view class="border-bottom"></view>
                <view class="r-list">
                  <view class="r-left">报告人</view>
                  <view class="r-right">{{ item.staffName }}</view>
                </view>
                <view class="border-bottom"></view>
                <view class="r-list">
                  <view class="r-left">报告日期</view>
                  <view class="r-right">{{ item.visistDate }}</view>
                </view>

              </view>
            </view>
          </view>
        </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 { getYsVisistList, removeVisist, updateStatus } from '../../../../api/crm/activity/activity';

// 获取导航栏高度用于内容区域padding
const navBarPaddingTop = ref(0);
onMounted(() => {
  navBarPaddingTop.value = getNavBarPaddingTop() * 2;
})

// 查询列表
let list = ref([]);

let searchValue = ref(null)

//监视查询的内容的变化
watch(searchValue, (newValue, oldValue) => {
  //变化了之后，重新查询内容
  var data = {
    pageNum: 1,
    pageSize: 10,
    searchContent: searchValue.value
  };
  getYsVisistList(data).then(res => {
    if (res.code === 200) {
      //设置列表数据
      list.value = res.rows;
    }
  })
})


// 查询搜索跳转
let handleSearch = () => {
  var data = {
    pageNum: 1,
    pageSize: 10,
    searchContent: searchValue.value
  };
  getYsVisistList(data).then(res => {
    if (res.code == 200) {
      //设置列表数据
      list.value = res.rows;
    } else {
      uni.showToast({
        icon: 'none',
        title: "请求失败",
      });
      list.value = null;
    }

  })
}

// 新增
let handleAdd = () => {
  uni.navigateTo({url: '/pages/business/CRM/marketActivity/visitorReportAdd'})
}


const mescrollRef = ref(null);
const upOption = ref({
  page: {num: 0, size: 10},
  noMoreSize: 5,
  empty: {
      tip: '~ 空空如也 ~',
      icon: "../../static/images/mescroll-empty.png"
  },
  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 {
    setTimeout(async () => {
      const res = await getVisitorReportList(1, upOption.value.page.size);
      cssFlag.value = false;
      list.value = res.list;
      mescroll.resetUpScroll();
    }, 500);
  } catch (error) {
    mescroll.endErr();
  } finally {
    setTimeout(async () => {
      mescroll.endSuccess();
    }, 500);
  }
}
// 上拉加载更多
const upCallback = async (mescroll) => {
  try {
    setTimeout(async () => {
      const res = await getVisitorReportList(mescroll.num, mescroll.size);
      if (mescroll.num === 1) {
        list.value = res.list;
      } else {
        list.value.push(...res.list);
      }
      mescroll.endBySize(res.list.length, res.total);
    }, 500);
  } catch (error) {
    mescroll.endErr();
  }
}

// 获取数据列表
const getVisitorReportList = (pageNum, pageSize) => {
  return new Promise(async (resolve) => {
    let param = {
      pageNum,
      pageSize
    }
    let res = await getYsVisistList(param);
    resolve({
      list: res.rows,
      total: res.total
    });
  });
}


let Loop = ref(0)
let now
const visistId = ref();
const cusName = ref();
const cusId = ref();
const status = ref()

function touchstart(item) {
  visistId.value = item.visistId
  cusName.value = item.cusName
  cusId.value = item.cusId
  status.value = item.status
  now = new Date();
  clearInterval(Loop.value); //再次清空定时器，防止重复注册定时器
  Loop.value = setTimeout(() => {
    uni.showModal({
      title: '删除',
      content: '请问要删除本条消息吗？',
      success: (res) => {
        if (res.confirm) {
          const data = {
            num: 1,
            pageSize: 10,
            status: "录入"
          };
          const parm = {
            visistId: item.visistId
          };
          removeVisist(parm).then(res => {
            if (res.code == 500) {
              uni.showToast({
                icon: 'none',
                title: "存在明细项，不能直接删除！",
              });
            } else {
              uni.showToast({
                title: "删除成功",
                duration: 2000
              });
            }
            // 刷新内容
            upCallback()
          });
        }
      }
    });
  }, 750);

}

function touchend() {
  let endDate = new Date();
  console.log('结束时间', endDate)
  let cha = endDate.getTime() - now.getTime();
  console.log(cha, 'casd')
  if (cha < 750) {
    uni.navigateTo({
      url: "/pages/business/CRM/marketActivity/visitorReportEnter?visistId=" + visistId.value + '&cusName=' + cusName.value + '&cusId=' + cusId.value + '&status=' + status.value
    })
  }
  clearInterval(Loop.value);
}

//点击状态按钮
function chooseStatus(item) {
  updateStatus(item).then(
      res => {
        if (res.code == 200) {
          uni.showToast({
            title: '提交成功',
            duration: 2000
          });
          setTimeout(function () {
            uni.navigateBack({
              success: () => {
              }
            })
          }, 500);
        } else {
          uni.showToast({
            title: res.msg,
            icon: 'none',
          });
        }
      },
      rej => {
      }
  );
}

//保留点击状态，关闭长按的冒泡
function handleStatusTouchStart(e) {
  // e.stopPropagation(); // 阻止冒泡
  // e.preventDefault();  // 阻止默认行为（如滚动）
}

function handleStatusTouchEnd(e) {
  // e.stopPropagation();
  // e.preventDefault();
}

</script>

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

.search {
  display: flex;
}

.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;
}

.search .custom-search {
  width: 80%;

}

.search .custom-search.uni-searchbar {
  padding-right: 0 !important;
}

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

.white-bg {
  padding-bottom: 10rpx;
}
</style>
