<template>
  <div class="w-full h-full flex flex-col">
    <div class="bg-white info flex-1 overflow-y-auto">
      <van-cell title="任务名称" :value="infoData.taskName" />
      <van-cell title="优先级">
        <template #default>
          {{ fixedFieldPriority.find(subItem => subItem.value == infoData.priority)?.label || '' }}
        </template>
      </van-cell>
      <van-cell title="状态" :value="''">
        <template #default>
          <div :style="`color: ${fixedFieldTaskStatus.find(subItem => subItem.value == infoData.status)?.color}`">
            {{ fixedFieldTaskStatus.find(subItem => subItem.value == infoData.status)?.label || '' }}
          </div>
        </template>
      </van-cell>
      <van-cell title="执行人">
        <template #default>
          <TranslationComponent :openId="infoData.taskExecutors" />
        </template>
      </van-cell>
      <van-cell title="开始时间" :value="infoData.startDate" />
      <van-cell title="截至时间" :value="infoData.endDate" />
      <van-cell title="客户名称" :value="infoData.customName" v-if="infoData.customName" />
      <van-cell :title="`${businessLabel}名称`" :value="infoData.businessName" v-if="infoData.businessName" />
      <van-cell title="销售订单" :value="infoData.orderName" v-if="infoData.orderName" />
      <van-cell title="线索名称" :value="infoData.clueName" v-if="infoData.clueName" />
      <van-cell title="联系人名称" :value="infoData.contactsName" v-if="!infoData.clueId" />
      <van-cell title="联系人号码" :value="infoData.contactsPhone" v-if="!infoData.clueId" />
    </div>
    <div class="bottomButton">
      <van-button type="success" class="w-full block" @click="completeTheTask(2)"
        v-if="infoData.status != 2">完成任务</van-button>
      <!-- <van-button type="primary" class="w-full block" @click="completeTheTask(0)" v-if="infoData.status == 2">重启任务</van-button> -->
      <van-button type="primary" class="w-full block" @click="restartTask()"
        v-if="infoData.status == 2">重启任务</van-button>
      <van-button type="danger" class="w-full block" @click="deleteTask">删除任务</van-button>
    </div>

    <van-popup v-model:show="showDelay" 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 h-52">
          <div class="flex-1">
            <div class="px-6 py-4 bg-[#F8F8FA] flex justify-between items-center mt-2" @click="showDatePickerCli('showStartDelayData')">
              <div>选择开始时间</div>
              <div class="flex items-center">
                {{ showStartDelayData }}
                <van-icon name="arrow" size="1.2rem" class="ml-2" />
              </div>
            </div>
          </div>
          <div class="flex-1">
            <div class="px-6 py-4 bg-[#F8F8FA] flex justify-between items-center mt-2" @click="showDatePickerCli('showEndtDelayData')">
              <div>选择结束时间</div>
              <div class="flex items-center">
                {{ showEndtDelayData }}
                <van-icon name="arrow" size="1.2rem" class="ml-2" />
              </div>
            </div>
          </div>
          <van-button type="primary" :disabled="showEndtDelayData < todaySDate" @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" :min-date="timeJudgment" @cancel="showDatePicker = false" />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';
import { showConfirmDialog } from 'vant';
import { useLifecycle } from '@hooks/useCommon.js';
import { GET_TASK_DETAILS, TASK_OPERATION } from "@hooks/useApi"
import requests from "@common/requests";
import { fixedFieldPaymentStatus, fixedFieldPriority, fixedFieldTaskStatus, fixedFieldStatusArray } from "@utility/defaultData"
import useShowToast from '@hooks/useToast'
import { routingInfos } from "@utility/generalVariables"
import useInfoStore from '@store/useInfoStore'
import useFixedData from "@store/useFixedData.js"
import useRouterStore from "@store/useRouterStore.js";
import dayjs from 'dayjs';

const router = useRouterStore()
const fixedData = useFixedData()
const userInfo = useInfoStore()
const { toastSuccess, toastLoading, toastFail, toastText, clearToast } = useShowToast()
const props = defineProps({
  info: {
    type: Object,
    required: true,
    default: () => ({})
  }
})
const routingInformation = routingInfos['tasks']
const infoData = ref(props.info);
const timeout = ref(null);
const showDelay = ref(false);
const showDatePicker = ref(false);
const showDatePickerVal = ref([])
const todaySDate = dayjs(new Date()).format('YYYY-MM-DD')
const showStartDelayData = ref('');
const showEndtDelayData = ref('');
const showDateType = ref('');
const timeJudgment = ref(new Date())

const isExistBusiness = sessionStorage.getItem("isExistBusiness");
const businessLabel = isExistBusiness === "1" ? "商机" : "项目"; 

watch(() => props.info, (newValue) => {
  initializeData(newValue.id)
})

function showPickerConfirm({ selectedValues }) {
  const dates = selectedValues.join('-')
  if(showDateType.value == 'showStartDelayData') {
    showStartDelayData.value = dates
    showEndtDelayData.value = ''
  }

  if(showDateType.value == 'showEndtDelayData') {
    showEndtDelayData.value = dates
  }
  console.log(showStartDelayData.value)
  console.log(showEndtDelayData.value)
  showDatePicker.value = false
}

function showDatePickerCli(type) {
  showDateType.value = type
  const types = type == 'showStartDelayData' ? showStartDelayData.value : showEndtDelayData.value
  timeJudgment.value = type == 'showStartDelayData' ? new Date : new Date(showStartDelayData.value)
  showDatePickerVal.value = types.split('-')
  showDatePicker.value = true
}

function restartTask() {
  showStartDelayData.value = infoData.value.startDate ? infoData.value.startDate : dayjs().format("YYYY-MM-DD")
  showEndtDelayData.value = infoData.value.endDate ? infoData.value.endDate : dayjs().format("YYYY-MM-DD")
  showDelay.value = true
}
function delayTimeEvent() {
  const id = infoData.value.id
  requests.post(TASK_OPERATION, { id, status: 0, startDate: showStartDelayData.value, endDate: showEndtDelayData.value }).then(({ data }) => {
    toastSuccess('操作成功')
    showDelay.value = false
    getTaskDetails(id)
  })
}

function completeTheTask(status) {
  const id = infoData.value.id
  requests.post(TASK_OPERATION, { id, status }).then(({ data }) => {
    toastSuccess('操作成功')
    getTaskDetails(id)
  })
}

function deleteTask() {
  const { name = '', searchFiled = {}, deteleFiled = '' } = routingInformation
  const row = infoData.value
  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 getTaskDetails(id) {
  requests.post(GET_TASK_DETAILS, { id }).then(({ data }) => {
    infoData.value = data
  }).finally(() => {
    setTimeout(() => {
      clearToast()
    }, 200)
  })
}

function initializeData(id) {
  clearTimeout(timeout.value);
  toastLoading('加载中...', 0)
  timeout.value = setTimeout(() => {
    getTaskDetails(id)
  }, 100);
}

useLifecycle({
  load: () => {
    initializeData(props.info.id)
  },
  init: () => {
    initializeData(props.info.id)
  },
  unLoad: () => {
    clearTimeout(timeout.value);
  }
});
</script>

<style lang='scss' scoped>
.bottomButton {
  margin: 0 14px;
  padding-bottom: 30px;

  :deep(.van-button) {
    margin-bottom: 20px;
  }
}

.info {
  margin: 8px 14px 30px 14px;
}

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

.topTitle {
  top: 14px;
}

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