<template>
  <Page :title='`${queryParameters.name}列表`'>
    <template v-slot:body>
      <div class="flex flex-col h-full">
        <!-- 搜索 -->
        <div class="mx-1 headerModeuleList">
          <van-search v-model.trim="searchVal" background="#F8F8F8" :placeholder="`请输入${queryParameters?.name}关键词`"
            @search="onRefresh(true)" @clear="onRefresh(true)">
            <template v-slot:left-icon>
              <van-icon name="search" class="themeTextColor font-bold" />
            </template>
          </van-search>
        </div>
        <!-- 主题内容 -->
        <div class="flex-1 overflow-y-auto">
          <template v-if="listData?.records && listData.records.length && !loadingList">
            <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
              <van-list v-model:loading="isLoading" :finished="finished" finished-text="没有更多了" @load="onLoad">
                <div v-for="item in listData.records" :key="item.id" @click="toDetail(item)">
                  <van-swipe-cell>
                    <div :class="`${item.needPin ? 'bg-slate-50' : 'bg-white'} px-5 py-5 flex items-center flex-row w-full listContent`">
                      <div class="listOfImages items-justify-center rounded-full overflow-hidden bg-[#FFEEEC]">
                        <img :src="queryParameters.homeImage" class="w-full h-full">
                      </div>
                      <div class="flex-1 h-full">
                        <!-- 商机 -->
                        <template v-if="queryParameters?.key == 'business'">{{ item.name }}</template>
                        <!-- 线索 -->
                        <template v-if="queryParameters?.key == 'thread'">{{ item.clueName }}</template>
                        <!-- 客户 -->
                        <template v-if="queryParameters?.key == 'customer'">{{ item.customName }}</template>
                        <!-- 联系人 -->
                        <template v-if="queryParameters?.key == 'contacts'">{{ item.name }}</template>
                        <!-- 任务 -->
                        <template v-if="queryParameters?.key == 'tasks'">{{ item.taskName }}</template>
                        <!-- 产品 -->
                        <template v-if="queryParameters?.key == 'product'">{{ item.productName }}</template>
                        <!-- 合同 -->
                        <template v-if="queryParameters?.key == 'contract'">{{ item.name }}</template>
                        <!-- 销售 -->
                        <template v-if="queryParameters?.key == 'order'">{{ item.orderName }}</template>
                      </div>
                    </div>
                    <template #right>
                      <div class="flex items-center h-full bg-white">
                        <template v-if="!item.inchargerName">
                          <div class="buttonCircle rounded-full" @click="claimAndClaim(item)" v-if="['business', 'thread', 
                          'customer'].includes(queryParameters?.key)">
                            <img src="/src/assets/image/claimAndClaim.png" class="w-full h-full">
                          </div>
                        </template>
                        <template v-if="item.inchargerName || item.ownerName">
                          <div class="buttonCircle rounded-full" @click="transfer(item)" v-if="['business', 'thread', 
                          'customer', 'contacts'].includes(queryParameters?.key)">
                            <img src="/src/assets/image/transfer.png" class="w-full h-full">
                          </div>
                        </template>
                        <template v-if="!item.needPin">
                          <div class="buttonCircle rounded-full" @click="topMounted(item)">
                            <img src="/src/assets/image/topMounted.png" class="w-full h-full">
                          </div>
                        </template>
                        <template v-if="item.needPin">
                          <div class="buttonCircle rounded-full" @click="noTopMounted(item)">
                            <img src="/src/assets/image/noTopMounted.png" class="w-full h-full">
                          </div>
                        </template>
                        <div class="buttonCircle rounded-full" @click="edit(item)">
                          <img src="/src/assets/image/edit.png" class="w-full h-full">
                        </div>
                        <div class="buttonCircle rounded-full" @click="deleteRow(item)">
                          <img src="/src/assets/image/delete.png" class="w-full h-full">
                        </div>
                      </div>
                    </template>
                  </van-swipe-cell>
                </div>
              </van-list>
            </van-pull-refresh>
          </template>
          <template v-else>
            <van-skeleton title :row="20" class="w-full h-full" />
          </template>
        </div>
      </div>

      <!-- 可拖拽添加 -->
      <DragBox>
        <div class="addButton" @click="toAddEditor()">
          <img src="/src/assets/image/add.png" class="w-full h-full" />
        </div>
      </DragBox>

      <!-- 转移弹窗 -->
      <van-dialog v-model:show="showDialog" :title="`转移${queryParameters?.name || ''}`" show-cancel-button
        @confirm="confirmTransfer" :before-close="dialogCloseBefo">
        <van-cell title="转移至" is-link @click="showSelect = true">
          <template #value>
            {{ dialogSelection.label }}
          </template>
        </van-cell>
        <div class="themeTextColor text-size-small pl-4 pt-2 pb-2">转移后，将看不到此{{ queryParameters?.name || '' }}</div>
      </van-dialog>

      <!-- select 选择器 -->
      <van-popup v-model:show="showSelect" destroy-on-close position="bottom" :style="{ height: '80%' }">
        <PullDownSelector @change="selectChange" />
      </van-popup>
    </template>
  </Page>
</template>

<script setup>
import { ref, onActivated } from 'vue';
import { showConfirmDialog } from 'vant';
import { useLifecycle } from '@hooks/useCommon.js';
import { resetListData, getListFieldKey } from '@components/common/formForm/formCorrespondenceProcessing'
import useShowToast from '@hooks/useToast'
import { GET_CUSTOM_FORM_JSON } from '@hooks/useApi'
import requests from "@common/requests";
import useRouterStore from "@store/useRouterStore.js";
import useFixedData from "@store/useFixedData.js"
import useInfoStore from '@store/useInfoStore'
// import ElementLongPress from "@components/common/elementLongPress.vue";
import DragBox from '@components/common/dragBox.vue';

const TRANSFER = 'transfer';
const DELETE = 'delete';
const EDIT = 'edit';
const TOP_MOUNTED = 'topMounted';

const { toastSuccess, toastFail, toastText } = useShowToast()
const router = useRouterStore()
const fixedData = useFixedData()
const userInfo = useInfoStore()
const searchVal = ref()
const queryParameters = ref({})
const loadingList = ref(false)
const popUpWindowArray = ref([
  { text: '转移', event: TRANSFER, icon: '/src/assets/image/transfer.png', removeModule: ['contacts', 'tasks', 'product', 'contract', 'order'] },
  { text: '顶置', event: TOP_MOUNTED, icon: '/src/assets/image/topMounted.png', removeModule: [] },
  { text: '编辑', event: EDIT, icon: '/src/assets/image/edit.png', removeModule: [] },
  { text: '删除', event: DELETE, icon: '/src/assets/image/delete.png', removeModule: [] },
])
const showSelect = ref(false)
const showDialog = ref(false)
const refreshing = ref(false);
const isLoading = ref(false);
const finished = ref(false);
const listData = ref({
  records: [],
  pageIndex: 0,
  pageSize: 20,
  total: 0,
  totalPage: 0,
});
const excessiveData = ref({});
const dialogSelection = ref({});

// 按钮触发的事件： row 为当前点击的行数据， item 为当前点击的按钮
function longPress(row, item) {
  switch (item.event) {
    case EDIT:
      edit(row);
      break;
    case TRANSFER:
      transfer(row);
      break;
    case DELETE:
      deleteRow(row);
      break;
    case TOP_MOUNTED:
      topMounted(row);
      break;
    default:
      console.warn('未知的类型', item.event);
      break;
  }
}

// 编辑事件
function edit(row) {
  const formJson = fixedData.formJson[queryParameters.value.key] || []
  const formList = resetListData(formJson?.list)
  const filedObj = getListFieldKey(formList, row)
  let other = {}
  if (queryParameters.value.key == 'tasks') {
    other = { ...row }
  }
  toAddEditor({ ...other, ...filedObj, id: row.id })
}

// 转移事件
function transfer(row) {
  dialogSelection.value = {}
  excessiveData.value = row
  showDialog.value = true
}

function confirmTransfer() {
  if (!dialogSelection.value.label) {
    return toastText('请选择要转移的人员')
  }
  const { id } = excessiveData.value
  const { value } = dialogSelection.value
  requests.post(queryParameters?.value.transferInterface, { ids: id, inchargerId: value }).then((res) => {
    toastSuccess('转移成功')
    onRefresh(true)
    showDialog.value = false
  })
}

// 认领
function claimAndClaim(item) {
  const { id, name, clueName, customName } = item
  const userId = userInfo.userInfo.id
  showConfirmDialog({
    title: `认领${queryParameters.value.name}`,
    message: `确定认领【${name || clueName || customName}】${queryParameters.value.name}吗？`,
  }).then(() => {
    requests.post(queryParameters?.value.transferInterface, { ids: id, inchargerId: userId }).then((res) => {
      toastSuccess('认领成功')
      onRefresh(true)
    })
  })
}

// 删除事件
function deleteRow(row) {
  const { name = '', searchFiled = {}, deteleFiled = '' } = queryParameters.value
  showConfirmDialog({
    title: `删除${name}`,
    message: `确定删除【${row[searchFiled?.search]}】${name}吗？`,
  }).then(() => {
    requests.post(deteleFiled, { ids: row.id }).then((res) => {
      toastSuccess('删除成功')
      onRefresh(true)
    }).catch((err) => {
      toastFail(err.msg ? err.msg : '删除失败')
    })
  })
}

// 顶置事件
function topMounted(row) {
  requests.post(queryParameters?.value.topMountedInterface, { ids: row.id }).then((res) => {
    toastSuccess('顶置成功')
    onRefresh(true)
  })
}

function noTopMounted(row) {
  requests.post(queryParameters?.value.cancelTheTopMountedInterface, { ids: row.id }).then((res) => {
    toastSuccess('取消顶置成功')
    onRefresh(true)
  })
}

function toDetail(item) {
  router.navigateTo({
    pathName: 'details',
    success: () => {
      router.emit('detailParameter', {
        routerInfo: JSON.stringify(queryParameters.value),
        parameter: JSON.stringify(item)
      })
    }
  })
}

function toAddEditor(value) {
  router.navigateTo({
    pathName: 'addEditor',
    success: () => {
      router.emit('addEditorParameter', {
        routerInfo: JSON.stringify(queryParameters.value),
        filedValue: JSON.stringify(value)
      })
    }
  })
}

function onRefresh(flag = false) {
  finished.value = false;
  isLoading.value = true;
  listData.value.pageIndex = 1;
  fetchListData(flag);
}

function onLoad() {
  isLoading.value = true;
  listData.value.pageIndex++
  fetchListData()
}

async function fetchListData(flag = false) {
  console.log(listData.value.totalPage, listData.value.pageIndex)
  if (
    // 如果总页数小于等于现页数，并且不是第一次加载， 或者正在加载数据 直接跳出不请求
    listData.value.totalPage < listData.value.pageIndex &&
    listData.value.pageIndex !== 1
  ) {
    finished.value = true;
    return;
  }
  const res = await getListData(flag)
  if (res.code === 'ok') {
    const list = res.data.data || res.data.records || res.data.record
    const total = res.data.total

    if (refreshing.value) {
      refreshing.value = false;
    }
    isLoading.value = false;
    listData.value.records = (
      listData.value.pageIndex === 1 ? [] : listData.value.records
    ).concat(list || [])

    listData.value.totalPage = Math.ceil(total / listData.value.pageSize)
    listData.value.total = +total
  }
}

async function getListData(flag = false) {
  const url = queryParameters.value.listUrl
  if (flag) {
    loadingList.value = true
  }
  const res = await requests.post(url, {
    pageIndex: listData.value.pageIndex,
    pageSize: listData.value.pageSize,
    pageFrom: listData.value.pageSize,
    [queryParameters.value?.searchFiled?.search]: searchVal.value
  }).finally(() => {
    if (flag) {
      loadingList.value = false
    }
  })
  return res
}

function reloadListData(data) {
  queryParameters.value = JSON.parse(data.row || '{}')
  refreshing.value = false
  isLoading.value = false
  finished.value = false
  listData.value = { records: [], pageIndex: 0, pageSize: 20, total: 0, totalPage: 0 }
  popUpWindowArray.value = popUpWindowArray.value.filter(item => !item.removeModule.includes(queryParameters.value?.key))
  if (!fixedData.formJson[queryParameters.value.key]) {
    getFormJson(queryParameters.value)
  }
  onLoad()
}

function getFormJson(info = {}) {
  requests.get(`${GET_CUSTOM_FORM_JSON}/${info.key}`).then(res => {
    const { data = [] } = res
    fixedData.updateState({
      formJson: {
        ...fixedData.formJson,
        [info.key]: JSON.parse(data[0].config)
      }
    })
  })
}

function selectChange(value, label) {
  dialogSelection.value = {
    value, label
  }
  showSelect.value = false
}

function dialogCloseBefo(val) {
  if (val == 'confirm' && showDialog.value) {
    return false
  }

  return true
}

useLifecycle({
  load: () => {
    router.on('moduleListDetailParameter', (data) => {
      reloadListData(data)
    })
  }
});


</script>

<style lang='scss' scoped>
.buttonCircle {
  width: 37px;
  height: 37px;
  margin-left: 10px;

  &:last-child {
    margin-right: 10px;
  }
}

.addButton {
  width: 60px;
  height: 60px;
}


.listContent {
  border: 1px solid #F6F6FA;

  .listOfImages {
    width: 40px;
    height: 40px;
    margin-right: 10px;
  }
}

.headerModeuleList :deep(.van-search__content) {
  background: #fff !im\portant;
  height: 42px;
  align-items: center;
  border-radius: 6px;
}
</style>