<template>
  <div class="flex flex-col h-full">
    <div class="bg-white info flex-1 overflow-y-auto cellnormall">
      <van-cell title="线索名称" :value="info.clueName" />
      <van-cell title="线索来源" :value="info.clueSourceValue" />
      <van-cell title="电话号码" :value="info.phone" />
      <van-cell title="邮箱" :value="info.email" />
      <van-cell title="客户行业" :value="info.customerIndustryValue" />
      <van-cell title="客户级别" :value="info.customerLevelValue" />
      <van-cell title="客户地址" :value="info.address" />
      <van-cell title="负责人">
        <template #default>
          <TranslationComponent :openId="info.inchargerName" />
        </template>
      </van-cell>
      <van-cell title="备注" :value="info.remark" />
    </div>
    <div class="bottomButton">
      <van-button type="primary" class="w-full block" v-if="info.inchargerName && info.isBo != 1"  @click="transformBusinessOpportunities()">线索转商机</van-button>
      <van-button type="warning" class="w-full block" v-if="info.inchargerName"  @click="showDialogCli()">转移线索</van-button>
      <van-button type="primary" class="w-full block" v-if="!info.inchargerName" @click="claimAndClaim()">认领线索</van-button>
      <van-button type="default" class="w-full block" v-permission="[routingInformation.jurisdiction.edit]" @click="jumpEdit()">编辑线索</van-button>
      <van-button type="danger" class="w-full block" v-permission="[routingInformation.jurisdiction.delete]" @click="deleteRow()">删除线索</van-button>
    </div>

    <!-- 转移弹窗 -->
    <van-dialog v-model:show="showDialog" :title="`转移线索`" 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">转移后，将看不到此线索了</div>
    </van-dialog>

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

<script setup>
import { ref } from 'vue';
import { showConfirmDialog } from 'vant';
import { useLifecycle } from '@hooks/useCommon.js';
import { TRANSFER_CLUES } from '@hooks/useApi'
import requests from "@common/requests";
import useShowToast from '@hooks/useToast'
import useInfoStore from '@store/useInfoStore'
import useRouterStore from "@store/useRouterStore.js";
import { routingInfos } from "@utility/generalVariables"
import { resetListData, getListFieldKey } from '@components/common/formForm/formCorrespondenceProcessing'
import useFixedData from "@store/useFixedData.js"

const fixedData = useFixedData()
const router = useRouterStore()
const userInfo = useInfoStore()
const { toastSuccess, toastFail, toastText } = useShowToast()
const props = defineProps({
  info: {
    type: Object,
    required: true,
    default: () => ({})
  }
})

const routingInformation = routingInfos['thread']
const showDialog = ref(false);
const showSelect = ref(false);
const dialogSelection = ref({});

function transformBusinessOpportunities() {
  const InfoJson = routingInfos['business']
  const formJson = fixedData.formJson[InfoJson.key] || []
  const formList = resetListData(formJson?.list)
  const filedObj = getListFieldKey(formList, props.info)
  const formVal = { ...filedObj, inchargerId: '', name: props.info?.clueName, clueId: props.info?.id }
  router.redirectTo({
    pathName: 'addEditor',
    success: () => {
      router.emit('addEditorParameter', {
        routerInfo: JSON.stringify(InfoJson),
        filedValue: JSON.stringify(formVal)
      })
    }
  })
}

function deleteRow() {
  const { name = '', searchFiled = {}, deteleFiled = '' } = routingInformation
  const row = props.info
  const foemVal = { [routingInformation.key == 'tasks' ? 'taskIds' : 'ids']: row.id }
  showConfirmDialog({
    title: `删除${name}`,
    message: `确定删除【${row[searchFiled?.search]}】${name}吗？`,
  }).then(() => {
    requests.post(deteleFiled, { ...foemVal }).then((res) => {
      toastSuccess('删除成功')
      router.navigateBack({
        success: () => {
          router.emit('moduleListDetailParameter', {
            row: JSON.stringify(routingInformation)
          })
        }
      })
    }).catch((err) => {
      toastFail(err.msg ? err.msg : '删除失败')
    })
  })
}

function jumpEdit() {
  const formJson = fixedData.formJson[routingInformation.key] || []
  const formList = resetListData(formJson?.list)
  const filedObj = getListFieldKey(formList, props.info)
  const formVal = { ...filedObj, id: props.info.id }

  router.navigateTo({
    pathName: 'addEditor',
    success: () => {
      router.emit('addEditorParameter', {
        routerInfo: JSON.stringify(routingInformation),
        filedValue: JSON.stringify(formVal)
      })
    }
  })
}

function listReloadData() {
  router.navigateBack({
    success: () => {
      router.eventEmit('moduleListRefreshData', {})
    }
  })
}
function confirmTransfer() {
  if(!dialogSelection.value.label) {
    return toastText('请选择要转移的人员')
  }

  requests.post(TRANSFER_CLUES, { ids: props.info.id, inchargerId: dialogSelection.value.value }).then((res) => {
    toastSuccess('转移成功')
    showDialog.value = false
    setTimeout(() => {
      listReloadData()
    }, 2000)
  })
}

function claimAndClaim() {
  showConfirmDialog({
    title: '认领线索',
    message: `确定认领【${props.info.clueName}】线索吗？`,
  }).then(() => {
    requests.post(TRANSFER_CLUES, { ids: props.info.id, inchargerId: userInfo.userInfo.id }).then((res) => {
      toastSuccess('认领成功')
      listReloadData()
      props.info.inchargerName = userInfo.userInfo.clueName
      showDialog.value = false
    })
  })
}

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

function showDialogCli() {
  dialogSelection.value = {}
  showDialog.value = true
}

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

  return true
}

useLifecycle({
  load: () => {
    // 添加加载逻辑
  }
});
</script>

<style lang='scss' scoped>
  .bottomButton {
    margin: 0 14px;
    padding-bottom: 30px;
    :deep(.van-button) {
      margin-bottom: 20px;
    }
  }
  .info {
    margin: 8px 14px 30px 14px;
    padding: 14px;
  }
</style>