<template>
  <div class="w-full h-full flex flex-col">
    <div class="flex-1 overflow-y-auto">
      <van-form ref="vanFormRef" show-error :show-error-message="false" label-align="left" input-align="right"
        class="bg-white" @submit="onSubmit">
        <van-field v-model="vantFormVal.taskName" name="taskName" rows="2" label="任务名称" maxlength="100" required
          show-word-limit type="textarea" placeholder="请输入" />
        <van-field v-model="vantFormVal.priority" name="priority" label="优先级" placeholder="请选择" is-link readonly
          required @click="showSelectionBox('priority', fixedFieldPriority)">
          <template #input v-if="vantFormVal.priority || vantFormVal.priority == 0">
            {{ vantFormVal.priorityName }}
          </template>
        </van-field>
        <van-field v-model="vantFormVal.taskType" name="taskType" label="任务类型" placeholder="请选择" is-link readonly
          @click="showSelectionBox('taskType', fixedFieldTaskType)" class="resetStyles">
          <template #input v-if="vantFormVal.taskType || vantFormVal.taskType == 0">
            {{ vantFormVal.taskTypeName }}
          </template>
        </van-field>
        <!-- 客户选择 -->
        <template v-if="vantFormVal.taskType == 0">
          <van-field v-model="vantFormVal.customId" name="customId" label="客户" placeholder="请选择" is-link readonly
            @click="showSelectionBox('customId', allCustomersList)" class="resetStyles">
            <template #input v-if="vantFormVal.customId">
              {{ vantFormVal.customIdName }}
            </template>
          </van-field>
        </template>
        <!-- 商机选择 -->
        <template v-if="vantFormVal.taskType == 1">
          <van-field v-model="vantFormVal.businessOpportunityId" name="businessOpportunityId" label="商机"
            placeholder="请选择" is-link readonly class="resetStyles"
            @click="showSelectionBox('businessOpportunityId', allBusinessOpportunities)">
            <template #input v-if="vantFormVal.businessOpportunityId">
              {{ vantFormVal.businessOpportunityIdName }}
            </template>
          </van-field>
        </template>
        <!-- 销售订单选择 -->
        <template v-if="vantFormVal.taskType == 2">
          <van-field v-model="vantFormVal.orderId" name="orderId" label="销售订单" placeholder="请选择" is-link readonly
            class="resetStyles" @click="showSelectionBox('orderId', allSalesOrdersList)">
            <template #input v-if="vantFormVal.orderId">
              {{ vantFormVal.orderIdName }}
            </template>
          </van-field>
        </template>
        <!-- 线索选择 -->
        <template v-if="vantFormVal.taskType == 3">
          <van-field v-model="vantFormVal.clueId" name="clueId" label="线索" placeholder="请选择" is-link readonly
            class="resetStyles" @click="showSelectionBox('clueId', allCluesList)">
            <template #input v-if="vantFormVal.clueId">
              {{ vantFormVal.clueIdName }}
            </template>
          </van-field>
        </template>
        <van-field v-model="vantFormVal.contactsId" name="contactsId" label="联系人" placeholder="请选择" is-link readonly
          :disabled="contactDisabled"
          v-if="fixedFieldTaskType.find(v => v.value == (vantFormVal.taskType || '1'))?.show" class="resetStyles"
          @click="showSelectionBox('contactsId', allContactsList)">
          <template #input v-if="vantFormVal.contactsId">
            {{ vantFormVal.contactsIdName }}
          </template>
        </van-field>
        <van-field v-model="vantFormVal.executorId" name="executorId" label="执行人" placeholder="请选择" is-link readonly
          class="resetStyles" @click="showSelectionToBox('executorId')">
          <template #input v-if="vantFormVal.executorIdName && vantFormVal.executorIdName.length > 0">
            <TranslationComponent :openId="vantFormVal.executorIdName" />
          </template>
        </van-field>
        <van-field name="isRepeat" label="重复提醒" class="resetStyles">
          <template #input>
            <van-switch v-model="vantFormVal.isRepeat" size="small" />
          </template>
        </van-field>
        <!-- 重复提醒 -->
        <template v-if="vantFormVal.isRepeat">
          <van-field v-model="vantFormVal.repeatType" name="repeatType" label="重复类型" placeholder="请选择" is-link readonly
            class="resetStyles" @click="showSelectionBox('repeatType', fixedFieldRepetitiveType)">
            <template #input v-if="vantFormVal.repeatType">
              {{ vantFormVal.repeatTypeName }}
            </template>
          </van-field>
          <template v-if="[0, 1, 2, 3, '0', '1', '2', '3'].includes(vantFormVal.repeatType)">
            <van-field v-model="vantFormVal.repeatDesignSameday" type="digit" name="repeatDesignSameday" label="每"
              class="resetStyles" v-if="vantFormVal.repeatType == 3">
              <template #input>
                <van-stepper v-model="vantFormVal.repeatDesignSameday" :min="0" button-size="1.2rem" theme="round"
                  integer class="mr-2" />
              </template>
              <template #extra> 天 </template>
            </van-field>
            <van-field name="endType" label="结束" class="resetStyles">
              <template #input>
                <van-radio-group v-model="vantFormVal.endType" direction="horizontal" class="flex flex-col"
                  @change="radiogroupChange">
                  <van-radio name="1"><span
                      :class="vantFormVal.endType == 1 ? 'themeTextColor' : ''">永不</span></van-radio>
                  <van-radio name="2" class="mt-3">
                    <van-stepper v-model="vantFormVal.repeatEndCount" :disabled="vantFormVal.endType != 2" :min="0"
                      button-size="1.2rem" theme="round" integer class="mr-2" />
                    次数以后
                  </van-radio>
                  <van-radio name="3" class="mt-3">
                    <div class="flex items-center">
                      <van-field label="日期" is-link readonly :disabled="vantFormVal.endType != 3" class="selectField"
                        placeholder="请选择" @click="vantFormVal.endType == 3 && showDatePickerBox('repeatEndDate')">
                        <template #input v-if="vantFormVal.repeatEndDate">
                          {{ vantFormVal.repeatEndDate }}
                        </template>
                      </van-field>
                      以后
                    </div>
                  </van-radio>
                </van-radio-group>
              </template>
            </van-field>
          </template>
          <template v-if="[4, '4'].includes(vantFormVal.repeatType)">
            <div class="flex items-center justify-between px-8 pt-3">
              <div>自定义日期</div>
              <div><van-icon name="add-o" class="ml-2 themeTextColor" size="1.3rem" @click="addCustomeDateItem()" />
              </div>
            </div>
            <van-cell-group inset class="additionalCoAuthorship">
              <template v-for="(item, index) in customeDate">
                <van-cell :title="`第${index + 1}次重复在`">
                  <template #default>
                    <div class="flex items-center justify-end">
                      <van-stepper v-model="item.value" :min="0" button-size="1.2rem" theme="round" integer
                        class="mr-2" />
                      天后
                      <van-icon name="delete-o" class="ml-2 text-[red]" size="1.3rem"
                        @click="deleteCustomeDateItem(index)" />
                    </div>
                  </template>
                </van-cell>
              </template>
            </van-cell-group>
          </template>
        </template>


        <van-field label="开始时间" name="startDate" is-link readonly class="resetStyles" placeholder="请选择"
          @click="showDatePickerBox('startDate')">
          <template #input v-if="vantFormVal.startDate">
            {{ vantFormVal.startDate }}
          </template>
        </van-field>
        <van-field label="结束时间" name="endDate" is-link readonly class="resetStyles" placeholder="请选择"
          @click="showDatePickerBox('endDate')">
          <template #input v-if="vantFormVal.endDate">
            {{ vantFormVal.endDate }}
          </template>
        </van-field>
        <div></div>
      </van-form>
      <CustomerForm ref="formFormRef" :formJson="formJson" :formValue="formVal"></CustomerForm>
    </div>
    <div class="mar-20px ">
      <van-button type="primary" @click="onSubmit" class="w-full">
        {{ Object.keys(formVal).length > 0 ? '确定修改' : '确定添加' }}
      </van-button>
    </div>

    <!-- 选择器 -->
    <div>
      <!-- 下拉框选择 -->
      <van-popup v-model:show="showSelectionFlag" destroy-on-close position="bottom" :style="{ height: '80%' }">
        <PullDownSelector :show-element="showSelectionFlag" :options="showSelectionArray" :doYouNeedTranslation="false" @change="selectChange" />
      </van-popup>

      <van-popup v-model:show="showSelectionToFlag" destroy-on-close position="bottom" :style="{ height: '80%' }">
        <PullDownSelector :show-element="showSelectionToFlag" :value="showSelectionToValue" @change="selectChange" :multiple-choice="true" />
      </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>
    </div>
  </div>
</template>

<script setup>
import { ref, onActivated, computed } from 'vue';
import { useLifecycle } from '@hooks/useCommon.js';
import { fixedFieldTaskType, fixedFieldPriority, fixedFieldRepetitiveType } from '@utility/defaultData.js';
import { GET_ALL_CUSTOMERSLIST, GET_ALL_BUSINESS_OPPORTUNITIES, GET_SALES_ORDER_LIST, GET_OBTAIN_ALL_CLUES, GET_CONTACTS_WITH_MORE_I_DS, TASK_ADD_EDIT, MODIFY_TASK } from "@hooks/useApi";
import requests from "@common/requests";
import useToast from "@hooks/useToast"
import dayjs from 'dayjs';
import PullDownSelector from '@components/common/pullDownSelector.vue'
import CustomerForm from '@components/common/formForm/formView.vue'
import TranslationComponent from '@components/common/translationComponent.vue';
import useRouterStore from "@store/useRouterStore.js";

const router = useRouterStore()
const { toastText, toastSuccess, toastFail, toastLoading } = useToast()
const props = defineProps({
  formJson: { required: true },
  formValue: { required: true },
});

const formFormRef = ref(null)
const vantFormVal = ref({
  taskType: 0,
  taskTypeName: '客户',
  endType: '1',
  repeatEndCount: 0,
  repeatType: 0,
  repeatTypeName: '每天'
})
const formVal = ref({})
const allBusinessOpportunities = ref([])
const allCustomersList = ref([])
const allCluesList = ref([])
const allSalesOrdersList = ref([])
const allContactsList = ref([])
const showSelectionFlag = ref(false)
const showSelectionFiled = ref([])
const showSelectionArray = ref([])
const showDatePicker = ref(false)
const showDatePickerVal = ref(dayjs().format("YYYY-MM-DD").split("-"))
const showDatePickerFiled = ref('')
const customeDate = ref([])
const showSelectionToFlag = ref(false)
const showSelectionToValue = ref([])
const taskTypeFiled = ['customId', 'businessOpportunityId', 'orderId', 'clueId']

const contactDisabled = computed(() => {
  const taskType = vantFormVal.value?.taskType
  if (!taskType && taskType != 0) {
    return true
  }
  if (taskType == 0 && !vantFormVal.value.customId) {
    return true
  }
  if (taskType == 1 && !vantFormVal.value.businessOpportunityId) {
    return true
  }
  if (taskType == 2 && !vantFormVal.value.orderId) {
    return true
  }
  return false
})

function onSubmit() {
  formFormRef.value.getJsonData().then((res) => {
    const formValue = {
      ...formVal.value,
      ...vantFormVal.value,
      ...res.data,
      repeatDesignDay: customeDate.value.map(item => item.value).join(','),
      executorId: vantFormVal.value.executorId,
      isRepeat: vantFormVal.value.isRepeat ? 1 : 0
    }
    console.log('formValue', formValue)
    toastLoading('保存中')
    const url = formValue.id ? MODIFY_TASK : TASK_ADD_EDIT
    requests.post(url, { ...formValue }).then(() => {
      toastSuccess('保存成功')
      setTimeout(() => {
        router.navigateBack({
          success: () => {
            router.eventEmit('moduleListRefreshData', {})
          }
        })
      }, 2000)
    }).finally(() => {

    })
  })
}

function showPickerConfirm({ selectedValues }) {
  vantFormVal.value[showDatePickerFiled.value] = selectedValues.join('-')
  showDatePicker.value = false
}

function showDatePickerBox(filed) {
  const dateVal = vantFormVal.value[filed] ? vantFormVal.value[filed] : dayjs().format("YYYY-MM-DD")
  showDatePickerFiled.value = filed
  showDatePickerVal.value = dateVal.split("-")
  showDatePicker.value = true
}

function selectChange(value, label) {
  console.log(value, label)
  if (taskTypeFiled.includes(showSelectionFiled.value)) {
    const item = fixedFieldTaskType.find(item => item.value == vantFormVal.value.taskType)
    console.log(item, value,)
    if (item && item.show) {
      getContactData(showSelectionFiled.value, value)
    }
  }
  if (showSelectionFiled.value == 'repeatType') {
    vantFormVal.value = {
      ...vantFormVal.value,
      endType: 0,
      repeatEndCount: 0,
      repeatEndDate: null
    }
    customeDate.value = []
  }
  vantFormVal.value[showSelectionFiled.value] = Array.isArray(value) ? value.join(',') : value
  vantFormVal.value[`${showSelectionFiled.value}Name`] = label
  showSelectionFlag.value = false
  showSelectionToFlag.value = false
}

function showSelectionToBox(filed) {
  showSelectionFiled.value = filed
  showSelectionToValue.value = vantFormVal.value[filed] || []
  showSelectionToFlag.value = true
}

function showSelectionBox(filed, list = [], event) {
  if (taskTypeFiled.includes(filed)) {
    const fileds = taskTypeFiled.filter(item => item !== filed)
    fileds.forEach(item => {
      vantFormVal.value[item] = ''
      vantFormVal.value[`${item}Name`] = ''
    })
    vantFormVal.value.contactsId = ''
    vantFormVal.value[`contactsIdName`] = ''
  }
  showSelectionFiled.value = filed
  showSelectionArray.value = filed == 'executorId' ? [] : list
  showSelectionFlag.value = true
}

function addCustomeDateItem() {
  customeDate.value.push({ value: null })
}

function deleteCustomeDateItem(index) {
  customeDate.value.splice(index, 1)
}

function radiogroupChange(val) {
  switch (val) {
    case 1:
      vantFormVal.value.repeatEndDate = ''
      vantFormVal.value.repeatEndCount = null
      break;
    case 2:
      vantFormVal.value.repeatEndDate = ''
      break;
    case 3:
      vantFormVal.value.repeatEndCount = null
      break;
    default:
      break;
  }
}

function getContactData(filed, value) {
  const urlType = {
    'customId': 'customerId',
    'businessOpportunityId': 'businessId',
    'orderId': 'salesId',
  }
  const url = `${GET_CONTACTS_WITH_MORE_I_DS}?${urlType[filed]}=${value}`
  requests.get(url).then(({ data = [] }) => {
    let list = data.map(item => {
      return {
        label: item.name,
        value: item.id,
      }
    })
    if (!list.length) {
      list = [{}]
    }
    allContactsList.value = list
  })
}

function getAllListData() {
  requests.post(GET_ALL_CUSTOMERSLIST, {}).then(res => {
    allCustomersList.value = res.data.map(item => {
      return {
        label: item.customName,
        value: item.id,
      }
    })
  })
  requests.post(GET_ALL_BUSINESS_OPPORTUNITIES, {}).then(res => {
    allBusinessOpportunities.value = res.data.map(item => {
      return {
        label: item.name,
        value: item.id,
      }
    })
  })
  requests.post(GET_SALES_ORDER_LIST, { pageIndex: -1, pageSize: -1 }).then(({ data }) => {
    allSalesOrdersList.value = (data.record || []).map(item => {
      return {
        label: item.orderName,
        value: item.id,
      }
    })
  })
  requests.post(GET_OBTAIN_ALL_CLUES, {}).then(res => {
    allCluesList.value = res.data.map(item => {
      return {
        label: item.clueName,
        value: item.id,
      }
    })
  })
}

function initializeData() {
  const row = props.formValue
  if (!row.id) {
    vantFormVal.value = {
      taskType: 0,
      taskTypeName: '客户',
      endType: '1',
      repeatEndCount: 0,
      repeatType: 0,
      repeatTypeName: '每天'
    }
    formVal.value = props.formValue
    customeDate.value = []
    return
  }

  const { id, taskName, priority, taskType, customId, customName, businessOpportunityId, businessOpportunityName, orderId, orderName, clueId, clueNme, contactsId, contactsName
    , taskExecutors, isRepeat, repeatType, repeatDesignSameday, endType, repeatEndCount, repeatEndDate, repeatDesignDay, executorId, startDate, endDate } = row
  vantFormVal.value = {
    id, taskName, priority, taskType, customId, businessOpportunityId, orderId, clueId, contactsId, executorId, repeatType, repeatDesignSameday, endType, repeatEndCount, repeatEndDate, startDate, endDate,
    isRepeat: isRepeat == 1 ? true : false,
    executorIdName: taskExecutors || [],
    contactsIdName: contactsName,
    clueIdNme: clueNme,
    orderIdName: orderName,
    customIdName: customName,
    businessOpportunityIdName: businessOpportunityName,
    priorityName: fixedFieldPriority.find(item => item.value == priority)?.label || '',
    taskTypeName: fixedFieldTaskType.find(item => item.value == taskType)?.label || '',
    repeatTypeName: fixedFieldRepetitiveType.find(item => item.value == repeatType)?.label || ''
  }

  const list = repeatDesignDay && repeatDesignDay.split(',') || []
  customeDate.value = (list || []).map(item => {
    return {
      value: item
    }
  })
  formVal.value = props.formValue
  if ((taskType || taskType == 0) && taskType != 3) {
    const filed = taskType == 0 ? 'customId' : taskType == 1 ? 'businessOpportunityId' : taskType == 2 ? 'orderId' : 'clueId'
    const value = taskType == 0 ? customId : taskType == 1 ? businessOpportunityId : taskType == 2 ? orderId : clueId
    if (value) {
      getContactData(filed, value)
    }
  }
}

useLifecycle({
  load: () => {
    initializeData()
    getAllListData()
  },
  init: () => {
    initializeData()
    getAllListData()
  }
});

onActivated(() => {

})
</script>

<style lang='scss' scoped>
.selectField {
  padding: 0;
  width: 12rem;
  margin-right: 4px;
}

.selectField :deep(.van-cell__title) {
  width: 4rem;
}

.additionalCoAuthorship {
  border-bottom: 1px solid #EBEDF0
}
</style>