<template>
  <Page title="访客计划详情">
    <template v-slot:headerRight>
      <div class="themeTextColor" v-if="detailedData.finishState == 0" @click="visitorEditor">编辑</div>
    </template>
    <template v-slot:body>
      <!-- 头部 -->
      <div class="planDetailsHead">
        <div class="w-full flex items-center justify-between">
          <div class="text-size-in font-bold text-[#474A56]">{{ detailedData.planName }}</div>
          <div :class="`labelTag ${detailedData.finishState == 0 ? 'toBeCompleted' : 'completed'}`">{{ ['未完成',
            '已完成'][detailedData.finishState] }}</div>
        </div>
        <div class="w-full mt-4">拜访目的：{{ detailedData.visitGoalName }}</div>
        <div class="w-full mt-4">拜访时间： {{ detailedData.visitTime }}</div>
        <div class="line"></div>
        <div class="w-full flex items-center">
          <van-icon name="user-circle-o" class="text-size-in mr-2" />
          客户:
          <div class="ml-2 themeTextColor decoration-auto underline" @click="jumpToCustomerDetails()">{{
            detailedData.customName }}</div>
        </div>
      </div>

      <!-- 主体 -->
      <van-cell-group>
        <van-cell title="计划名称" :value="detailedData.planName" />
        <van-cell title="客户姓名" :value="detailedData.customName" />
        <van-cell title="负责人" :value="detailedData.inchargerName" />
        <van-cell title="拜访目的" :value="detailedData.visitGoalName" />
        <van-cell title="拜访时间" :value="detailedData.visitTime" />
        <van-cell title="提醒" :value="detailedData.remindTypeName" />
        <van-cell title="提醒时间" :value="detailedData.remindTime" v-if="detailedData.remindType == -1" />
        <van-cell title="备注" :value="detailedData.remark" />
      </van-cell-group>
      <div class="h-10"></div>

      <!-- 弹窗 -->
      <van-popup v-model:show="showContacts" closeable position="bottom" round>
        <div class="newModuleAdded relative">
          <div class="text-size-large text-[#474A56] absolute topTitle">联系人号码</div>
          <div class="flex flex-col overflow-y-auto boxLxr">
            <template v-for="item in contactList">
              <a :href="`tel:+${item.phone}`">
                <div class="bg-[#F8F8FA] flex justify-between items-center px-6 py-4 mb-3 rounded">
                  <div class="w-3/12">{{ item.name }}</div>
                  <div class="flex-1">{{ item.phone }}</div>
                  <van-icon name="phone" color="#075985" size="1.4rem" />
                </div>
              </a>
            </template>
          </div>
        </div>
      </van-popup>

      <van-popup v-model:show="showDelay" closeable position="bottom" round>
        <div class="newModuleAdded relative">
          <div class="text-size-large text-[#474A56] absolute topTitle">{{ delayRestartText }}时间</div>
          <div class="flex flex-col overflow-y-auto h-52">
            <div class="flex-1">
              <div class="px-6 py-4 bg-[#F8F8FA] flex justify-between items-center mt-2" @click="showDatePicker = true">
                <div>选择时间</div>
                <div class="flex items-center">
                  {{ showDelayData }}
                  <van-icon name="arrow" size="1.2rem" class="ml-2" />
                </div>
              </div>
            </div>
            <van-button type="primary" :disabled="!showDelayData" @click="delayTimeEvent()">保存</van-button>
          </div>
        </div>
      </van-popup>

      <van-popup v-model:show="showDatePicker" destroy-on-close position="bottom" :style="{ height: '50%' }">
        <van-date-picker v-model="showDatePickerVal" @confirm="showPickerConfirm" @cancel="showDatePicker = false" />
      </van-popup>

      <van-popup v-model:show="timeShowPicker" destroy-on-close position="bottom" :style="{ height: '50%' }">
        <van-time-picker v-model="currentTime" title="选择时间" @confirm="timeConfirm" />
      </van-popup>
    </template>

    <template v-slot:footer v-if="detailedData.finishState == 0">
      <div class="w-full flex justify-between layout">
        <div class="footerBtnLeft layouts" @click="showContactsCli()">
          <div class="imgClss">
            <img src="/src/assets/image/lianxir.png" alt="">
          </div>
          联系人
        </div>
        <div class="footerBtnRight layouts" @click="delayRestart('DELAY')">
          <div class="imgClss">
            <img src="/src/assets/image/yanqi.png" alt="">
          </div>
          延期
        </div>
        <div class="coverWithWhite"></div>
        <div class="bigCircle" @click="completeThePlan()">
          <div class="imgClss">
            <img src="/src/assets/image/wanc.png" alt="">
          </div>
          完成
        </div>
      </div>
    </template>

    <template v-slot:footer v-if="detailedData.finishState != 0">
      <div class="w-full flex justify-between layout">
        <div class="footerBtnTwoLeft layoutsTwo" @click="showContactsCli()">
          <div class="imgClss">
            <img src="/src/assets/image/lianxir.png" alt="">
          </div>
          联系人
        </div>
        <div class="footerBtnTwoLeft layoutsTwo" @click="delayRestart('RESTART')">
          <div class="imgClss">
            <img src="/src/assets/image/chongqi.png" alt="">
          </div>
          重启
        </div>
      </div>
    </template>
  </Page>
</template>

<script setup>
import { ref } from "vue";
import { showConfirmDialog } from 'vant';
import { useLifecycle } from "@hooks/useCommon.js";
import { OBTAIN_DETAILS_OF_THE_VISIT_PLAN, POSTPONE_THE_VISIT_PLAN, COMPLETE_THE_VISIT_PLAN, OBTAIN_CUSTOMER_DETAILS } from "@hooks/useApi"
import useToast from "@hooks/useToast"
import requests from "@common/requests";
import useRouterStore from "@store/useRouterStore.js";
import dayjs from "dayjs";
import { routingInfos } from "@utility/generalVariables.js";
import useFixedData from "@store/useFixedData.js";
import PullDownSelector from "@components/common/pullDownSelector.vue";

const router = useRouterStore();
const { toastText, toastSuccess, toastFail, toastLoading } = useToast()
const detailedData = ref({});
const showContacts = ref(false);
const showDelay = ref(false)
const showDatePicker = ref(false)
const timeShowPicker = ref(false)
const showDatePickerVal = ref(dayjs().format("YYYY-MM-DD").split('-'))
const showDelayData = ref('')
const currentTime = ref('')
const contactList = ref([]);
const delayRestartText = ref('')

function delayRestart(type = 'DELAY') {
  const textType = { 'DELAY': '延期', 'RESTART': '重启' }
  delayRestartText.value = textType[type]
  showDelay.value = true
  showDelayData.value = ''
}

function visitorEditor() {
  router.navigateTo({
    pathName: 'addEditorVisitor',
    success: () => {
      router.emit('addEditorVisitorParameter', {
        row: JSON.stringify(detailedData.value || {}),
        date: JSON.stringify(detailedData.value.visitTime || {})
      })
    }
  })
}

function jumpToCustomerDetails() {
  const routerInfo = routingInfos['customer']
  requests.post(OBTAIN_CUSTOMER_DETAILS, { id: detailedData.value.customId }).then(res => {
    router.navigateTo({
      pathName: 'details',
      success: () => {
        router.emit('detailParameter', {
          routerInfo: JSON.stringify(routerInfo || {}),
          parameter: JSON.stringify(res.data || {})
        })
      }
    })
  })
}

function showContactsCli() {
  if (!((contactList.value || []).length)) {
    toastText('该联系人无号码')
    return
  }
  showContacts.value = true
}

function completeThePlan() {
  showConfirmDialog({
    title: `完成访客计划`,
    message: `确定完成【${detailedData.value.planName}】访客计划吗？`,
  }).then(() => {
    requests.post(COMPLETE_THE_VISIT_PLAN, { planId: detailedData.value.id, }).then((res) => {
      toastSuccess('操作成功')
      getDetailData(detailedData.value)
    })
  })
}

function delayTimeEvent() {
  requests.post(POSTPONE_THE_VISIT_PLAN, { planId: detailedData.value.id, visitTime: showDelayData.value }).then(() => {
    toastSuccess(`操作成功`)
    getDetailData(detailedData.value)
    showDelay.value = false
  })
}

function getDetailData(row) {
  requests.post(OBTAIN_DETAILS_OF_THE_VISIT_PLAN, { planId: row.id }).then(({ data = [] }) => {
    detailedData.value = data
    contactList.value = data.contacts || []
  })
}

function showPickerConfirm({ selectedValues }) {
  const dates = selectedValues.join('-')
  const times = dayjs().format("hh:mm")
  showDelayData.value = `${dates} ${times}`
  currentTime.value = times.split(':')
  showDatePicker.value = false
  timeShowPicker.value = true
}

function timeConfirm({ selectedValues }) {
  const dates = dayjs(new Date(showDatePickerVal.value)).format("YYYY-MM-DD")
  showDelayData.value = `${dates} ${selectedValues.join(':')}`
  timeShowPicker.value = false
}

function processingDataSource(data) {
  const row = JSON.parse(data.row);
  detailedData.value = row || {}

  getDetailData(row)
}

useLifecycle({
  load: () => {
    console.log('开始执行')
    router.on("visitorDetailsParameter", (data) => {
      processingDataSource(data);
    });
  },
});
</script>

<style lang="scss" scoped>
.planDetailsHead {
  background: #ffa35919;
  padding: 14px 18px;
  margin: 10px;

  .toBeCompleted {
    background: rgba($color: #f38b3c, $alpha: 0.1);
    border-color: #f38b3c;
    color: #f38b3c;
  }

  .completed {
    background: rgba($color: #07c160, $alpha: 0.1);
    border-color: #07c160;
    color: #07c160;
  }

  .labelTag {
    font-size: 10px;
    padding: 3px 8px;
    border-radius: 4px;
    border: 1px solid;
  }

  .line {
    width: 100%;
    height: 1px;
    background-color: #E6D3C7;
    margin: 14px 0;
  }
}

.layout {
  height: 90px;
  position: relative;

  .layouts {
    width: 40%;
    height: 100%;
    background: #fff;
    box-shadow: 0px -2px 30px 0px #00000014;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }

  .layoutsTwo {
    width: 40%;
    height: 100%;
    background: #fff;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }

  .footerBtnLeft {
    border-top-right-radius: 25px;

    .imgClss {
      width: 30px;
      height: 30px;
      margin-bottom: 6px;
    }
  }

  .footerBtnTwoLeft {
    width: 50%;

    .imgClss {
      width: 30px;
      height: 30px;
      margin-bottom: 6px;
    }
  }

  .footerBtnRight {
    border-top-left-radius: 25px;

    .imgClss {
      width: 26px;
      height: 24px;
      margin-bottom: 9px;
    }
  }

  .coverWithWhite {
    width: 20%;
    background: #fff;
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    height: 70px;
    z-index: 1;
  }

  .bigCircle {
    width: 80px;
    height: 80px;
    ;
    border-radius: 50%;
    background: $themeColor;
    box-shadow: 0px -2px 30px 0px #00000014;
    position: absolute;
    bottom: 27px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 2;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;

    .imgClss {
      width: 25.5px;
      height: 25.5px;
      margin-bottom: 4px;
    }
  }
}

.newModuleAdded {
  padding: 45px 25px 45px 25px;
}

.topTitle {
  top: 14px;
}

.boxLxr {
  max-height: 180px;
}
</style>
