<template>
  <div class="mobile-container">
    <van-nav-bar left-text="返回"
      left-arrow
      @click-left="clickBack()"
      fixed
      placeholder>
    </van-nav-bar>
    <div>
      <van-form @submit="onSubmit"
        ref="myForm">
        <van-cell-group inset>
          <van-field v-model="form.storeName"
            is-link
            label="选择门店"
            required
            :rules="[{ required: true, message: '请选择门店' }]"
            @click="selStoreName">
            <template #input>
              <div class="custom-input">
                <input type="text"
                  class="van-field__control"
                  readonly
                  :value="form.storeName"
                  name="storeName"
                  placeholder="点击选择门店">
                <p v-if="form.storeName && !planId">{{ form.storeAddr }} - {{ form.storeCode }}</p>
              </div>
            </template>
          </van-field>
          <van-field :modelValue="parseTime(form.date, '{y}-{m}-{d}')"
            is-link
            readonly
            name="date"
            label="活动日期"
            placeholder="点击选择时间"
            required
            :rules="[{ required: true, message: '请选择日期' }]"
            @click="selCalendar" />
          <PickerCalendar v-model:show="showCalendar"
            :default-date="form.date"
            :min-date="planMinDate"
            setNextMaxMonth
            :setNowMaxMonth="!!planId"
            type="single"
            @confirm="confirmCalendar" />
          <van-field v-model="form.pattern"
            is-link
            readonly
            name="pattern"
            label="活动计划"
            placeholder="请选择计划名称"
            required
            :rules="[{ required: true, message: '请选择计划' }]"
            @click="selPattern" />
          <van-field v-model="form.employeeName"
            is-link
            readonly
            name="employeeName"
            label="归属人"
            placeholder="请选择归属人"
            required
            :disabled="isCityManager"
            :rules="[{ required: true, message: '请选择归属人' }]"
            @click="selEmployee" />
          <van-field :modelValue="form.inTime.join(':')"
            is-link
            readonly
            name="inTime"
            label="上班打卡时间"
            placeholder="请选择时间"
            required
            :rules="[{ required: true, message: '请选择时间' }]"
            @click="selInTime" />
          <van-field :modelValue="form.noonOutTime.join(':')"
            is-link
            readonly
            :disabled="!form.inTime.length"
            name="noonOutTime"
            label="午休开始时间"
            placeholder="请选择时间"
            :rules="[{ message: '请选择午休开始时间' }]"
            @click="showNoonOutTimePicker = true" />
          <van-field :modelValue="form.noonInTime.join(':')"
            is-link
            readonly
            :disabled="!form.noonOutTime.length"
            name="noonInTime"
            label="午休结束时间"
            placeholder="请选择时间"
            :rules="[{ message: '请选择午休结束时间', validator: validatorNoonInTime }]"
            @click="showNoonInTimePicker = true" />
          <van-field :modelValue="form.outTime.join(':')"
            is-link
            readonly
            :disabled="!form.inTime"
            name="outTime"
            label="下班打卡时间"
            placeholder="请选择时间"
            required
            :rules="[{ required: true, message: '请选择时间' }]"
            @click="showOutTimePicker = true" />
          <van-field v-model="form.temWlSct"
            readonly
            name="temWlSct"
            label="是否有试吃台"
            placeholder="是否有试吃台"
            required
            :rules="[{ validator: validatorTemWlSct, message: '请选择是否有试吃台' }]"
            :error-message="errorTemWlSctMessage">
            <template #input>
              <van-radio-group v-model="form.temWlSct"
              @change="validatorTemWlSct"
                direction="horizontal">
                <van-radio icon-size="16px"
                  name="有">有</van-radio>
                <van-radio icon-size="16px"
                  name="无">无</van-radio>
              </van-radio-group>
            </template>
          </van-field>

          <van-field v-model="form.prdClass"
            is-link
            readonly
            name="prdClass"
            label="活动品项"
            placeholder="请选择活动品项"
            required
            :rules="[{ validator: validatorPrdClass, message: '请选择活动品项' }]"
            :error-message="errorPrdClassMessage"
            @click="selPrdClass">
          </van-field>
          <!-- <van-field v-model="form.salary"
            readonly
            name="salary"
            label="工资"
            placeholder="请输入工资"
            required
            :rules="[{ validator: validatorSalary, message: '请输入工资' }]"
            :error-message="errorSalaryMessage">
            <template #input>
              <van-stepper v-model="form.salary"
                integer
                :min="0"
                :default-value="0" />
            </template>
          </van-field>
          <van-field v-model="form.incidentals"
            readonly
            name="incidentals"
            label="杂费"
            placeholder="请输入工资"
            required
            :rules="[{ validator: validatorIncidentals, message: '请输入工资' }]"
            :error-message="erroIncidentalMessage">
            <template #input>
              <van-stepper v-model="form.incidentals"
                integer
                :min="0"
                :default-value="0" />
            </template>
          </van-field> -->
        </van-cell-group>
        <div style="margin: 16px;">
          <van-button round
            block
            type="primary"
            native-type="submit">
            {{ planId ? '修改' : '创建' }}计划
          </van-button>
          <van-button round
            block
            style="margin-top: 10px;"
            @click="reset">
            <van-icon name="replay" /> 重置表单
          </van-button>
        </div>
      </van-form>
    </div>
    <!-- 选择归属人 -->
    <PickerBelong v-model:show="showEmployeePicker"
      @confirm="confirmEmployee" />
    <!-- 通用选择器 -->
    <PickerSearch v-model:show="showPicker"
      :columns="columns"
      :searchShow="showPickerSearch"
      @search="search"
      @cancel="showPicker = false"
      @confirm="confirm" />
    <!-- 上班时间选择 -->
    <van-popup v-model:show="showInTimePicker"
      destroy-on-close
      position="bottom">
      <van-time-picker v-model="form.inTime"
        :formatter="formatterTime"
        @confirm="onConfirmInTime"
        @cancel="showInTimePicker = false"
        title="选择时间" />
    </van-popup>
    <!-- 午休开始时间选择 -->
    <van-popup v-model:show="showNoonOutTimePicker"
      destroy-on-close
      position="bottom">
      <van-time-picker v-model="form.noonOutTime"
        :formatter="formatterTime"
        :min-time="noonOutTimeMinTime"
        @confirm="onConfirmNoonOutTime"
        @cancel="showNoonOutTimePicker = false"
        title="选择时间" />
    </van-popup>
    <!-- 午休结束时间选择 -->
    <van-popup v-model:show="showNoonInTimePicker"
      destroy-on-close
      position="bottom">
      <van-time-picker v-model="form.noonInTime"
        :formatter="formatterTime"
        :min-time="noonInTimeMinTime"
        @confirm="onConfirmNoonInTime"
        @cancel="showNoonInTimePicker = false"
        title="选择时间" />
    </van-popup>
    <!-- 下班时间选择 -->
    <van-popup v-model:show="showOutTimePicker"
      destroy-on-close
      position="bottom">
      <van-time-picker v-model="form.outTime"
        :min-time="outTimeMinTime"
        :formatter="formatterTime"
        @confirm="onConfirmOutTime"
        @cancel="showOutTimePicker = false"
        title="选择时间" />
    </van-popup>
  </div>
</template>

<script setup>
import { getPlanStoreListAPI, getChargeListAPI, addPlanByWebAPI, getPlanDetailAPI, updatePlanByWebAPI } from '@/api'
import userStore from '@/store/modules/user'
import { parseTime } from '@/utils'
import PickerBelong from '../components/PickerBelong'

const myForm = ref({})
const { proxy } = getCurrentInstance();
const empInfo = userStore().empInfo
const isCityManager = ref(userStore().promotionIdentity)
const form = reactive({
  inTime: [], // 上班时间
  noonOutTime: [], // 午休开始时间
  noonInTime: [], // 午休结束时间
  outTime: [] // 下班时间
})
const router = useRouter();
const route = useRoute()
const clickBack = () => {
  router.back()
}
const editDealerId = ref(null) // 变更计划的经销商 ID

const planId = route.params.planId
const init = async () => {
  // 编辑
  const res = await getPlanDetailAPI(planId)
  Object.keys(res.data.planInfo).forEach(o => {
    form[o] = res.data.planInfo[o]
  })
  form.date = parseTime(new Date(form.date), "{y}-{m}-{d}")
  form.inTime = parseTime(res.data.planInfo.clockInTime, "{h}:{i}").split(":")
  form.noonInTime = parseTime(res.data.planInfo.noonClockInTime, "{h}:{i}").split(":")
  form.noonOutTime = parseTime(res.data.planInfo.noonClockOutTime, "{h}:{i}").split(":")
  form.outTime = parseTime(res.data.planInfo.clockOutTime, "{h}:{i}").split(":")

  editDealerId.value = res.data.planInfo.dealerId
}
if (planId) {
  init()
}

const errorSalaryMessage = ref('')
const erroIncidentalMessage = ref('')
const errorNoonInTimeMessage = ref('')
const errorTemWlSctMessage = ref('')
const errorPrdClassMessage = ref('')
// 校验午休结束时间
const validatorNoonInTime = (value, obj) => {
  console.log(form.noonOutTime.length > 0, '午休结束判断该')
  if (form.noonOutTime.length > 0) {
    if (!value) {
      errorNoonInTimeMessage.value = '请选择午休结束时间'
      return false
    } else if (value <= form.noonOutTime) {
      errorNoonInTimeMessage.value = '午休结束时间必须大于午休开始时间'
      return false
    }
  } else {
    errorNoonInTimeMessage.value = ''
    return true
  }
}
// 校验试吃台
const validatorTemWlSct = (value, obj) => {
  if (!value) {
    errorTemWlSctMessage.value = obj?.message
    return false
  } else {
    errorTemWlSctMessage.value = ''
    return true
  }
}
// 校验活动品项
const validatorPrdClass = (value, obj) => {
  if (!value) {
    errorPrdClassMessage.value = obj.message
    return false
  } else {
    errorPrdClassMessage.value = ''
    return true
  }
}

// 校验工资
const validatorSalary = (value, obj) => {
  if (value <= 0) {
    errorSalaryMessage.value = obj.message
    return false
  } else {
    errorSalaryMessage.value = ''
    return true
  }
}
// 校验杂费
const validatorIncidentals = (value, obj) => {
  if (value <= 0) {
    erroIncidentalMessage.value = obj.message
    return false
  } else {
    erroIncidentalMessage.value = ''
    return true
  }
}

const onSubmit = async () => {
  form.operNo = empInfo.empNo
  form.operName = empInfo.empName
  form.operId = empInfo.empId
  const obj = {
    ...form,
    inTime: form.inTime.join(":"),
    noonOutTime: form.noonOutTime.join(":"),
    noonInTime: form.noonInTime.join(":"),
    outTime: form.outTime.join(":"),
  }

  if (planId) {
    const res = await updatePlanByWebAPI(obj)
    showNotify({ type: 'success', message: res.msg })
  } else {
    const res = await addPlanByWebAPI(obj)
    showNotify({ type: 'success', message: res.msg })
  }

  clickBack()
}

// 选择门店
const selStoreName = async () => {
  isType.value = '门店'
  showPicker.value = true
  await getStoreList()
  showPickerSearch.value = true
  searchPlaceholder.value = '搜索门店名称'
}
// 获取门店列表
const getStoreList = async (storeName) => {
  const res = await getPlanStoreListAPI({
    storeNameVague: storeName,
    dealerId: editDealerId.value
  })
  columns.value = res.data.map(item => ({
    text: item.storeName,
    value: item.storeCode,
    storeAddr: item.storeAddr
  }))
}

// 活动日期
const showCalendar = ref(false)
const selCalendar = () => {
  showCalendar.value = true
}
const confirmCalendar = (value) => {
  form.date = value
  showCalendar.value = false
}
const planMinDate = computed(() => {
  // 如果当前是城市经理，只能创建下个月计划，否则是今日到下月末
  if (isCityManager.value) {
    const date = new Date()

    // 编辑：只能明天到当月月底
    if (planId) {
      date.setDate(date.getDate() + 1)
      return date
    }

    // 新增：只能下个月一整月
    date.setMonth(date.getMonth() + 1)
    date.setDate(1)
    return date
  } else {
    // 如果是变更计划，则选择明天以后的日期
    const date = new Date()
    return date
  }
})

// 活动计划
const selPattern = () => {
  isType.value = '计划'
  showPicker.value = true
  showPickerSearch.value = false
  searchPlaceholder.value = '搜索计划名称'
  columns.value = [
    { text: '单点 CP', value: '单点 CP' },
    { text: '常规 MINI 秀', value: '常规 MINI 秀' },
    { text: '校园活动', value: '校园活动' },
  ]
}

// 归属人
const showEmployeePicker = ref(false)
const selEmployee = () => {
  if (!isCityManager.value) {
    showEmployeePicker.value = true
  }
}
onMounted(() => {
  // 如果当前是城市经理，自动填入归属人信息
  if (isCityManager.value) {
    form.employeeName = empInfo.empName
    form.employeeNo = empInfo.empNo
    form.employeeId = empInfo.empId
  }
})


// 上班打卡时间
const showInTimePicker = ref(false)
const selInTime = () => {
  showInTimePicker.value = true
  form.inTime = [new Date().getHours(), new Date().getMinutes()]
}
const onConfirmInTime = (value) => {
  form.inTime = [...value.selectedValues]
  // 下个选择时间器，最小选择时间，分钟往后增加 1
  value.selectedValues[1] = value.selectedValues[1] * 1 + 1
  if (value.selectedValues[1] < 10) {
    value.selectedValues[1] = '0' + value.selectedValues[1]
  }
  noonOutTimeMinTime.value = value.selectedValues.join(':') + ":00"
  outTimeMinTime.value = value.selectedValues.join(':') + ":00"
  showInTimePicker.value = false
}

// 午休开始时间
const showNoonOutTimePicker = ref(false)
const noonOutTimeMinTime = ref("00:00:00") // 最小时间范围
const onConfirmNoonOutTime = (value) => {
  showNoonOutTimePicker.value = false
  form.noonOutTime = [...value.selectedValues]
  // 下个选择时间器，最小选择时间，分钟往后增加 1
  value.selectedValues[1] = value.selectedValues[1] * 1 + 1
  if (value.selectedValues[1] < 10) {
    value.selectedValues[1] = '0' + value.selectedValues[1]
  }
  noonOutTimeMinTime.value = value.selectedValues.join(':') + ":00"
  noonInTimeMinTime.value = value.selectedValues.join(':') + ":00"
  outTimeMinTime.value = value.selectedValues.join(':') + ":00"
}

// 午休结束时间
const showNoonInTimePicker = ref(false)
const noonInTimeMinTime = ref("00:00:00") // 最小时间范围
const onConfirmNoonInTime = (value) => {
  showNoonInTimePicker.value = false
  form.noonInTime = [...value.selectedValues]
  // 下个选择时间器，最小选择时间，分钟往后增加 1
  value.selectedValues[1] = value.selectedValues[1] * 1 + 1
  if (value.selectedValues[1] < 10) {
    value.selectedValues[1] = '0' + value.selectedValues[1]
  }
  outTimeMinTime.value = value.selectedValues.join(':') + ":00"
}

// 下班打卡时间
const showOutTimePicker = ref(false)
const outTimeMinTime = ref("00:00:00")
const onConfirmOutTime = (value) => {
  showOutTimePicker.value = false
  form.outTime = [...value.selectedValues]
}

const formatterTime = (type, option) => {
  if (type === 'hour') {
    option.text += ' 时';
  }
  if (type === 'minute') {
    option.text += ' 分';
  }
  return option;
};

// 活动品项
const selPrdClass = () => {
  isType.value = '品项'
  showPicker.value = true
  showPickerSearch.value = false
  searchPlaceholder.value = '搜索品项名称'
  columns.value = [
    { text: '老品', value: '老品' },
    { text: '黑鸭', value: '黑鸭' },
    { text: '散称', value: '散称' },
  ]
  errorPrdClassMessage.value = ''
}

// 重置表单
const reset = () => {
  myForm.value.resetValidation()
  errorSalaryMessage.value = ''
  erroIncidentalMessage.value = ''
  errorTemWlSctMessage.value = ''
  errorPrdClassMessage.value = ''
  form.storeName = ''
  form.date = ''
  form.pattern = ''
  form.employeeName = ''
  form.inTime = []
  form.noonOutTime = []
  form.noonInTime = []
  form.outTime = []
  form.temWlSct = ''
  form.prdClass = ''
  // form.salary = 0
  // form.incidentals = 0
  editDealerId.value = null
}

// Picker 选择器
const showPicker = ref(false) // 是否展示选择器
const showPickerSearch = ref(true) // 是否展示搜索
const searchPlaceholder = ref('') // 搜索框提示文字
const columns = ref([]) // 选择器列数据
const isType = ref('') // 0: 门店 1: 计划 2: 归属人
// 搜索
const search = (value) => {
  if (isType.value === '门店') {
    getStoreList(value)
  }
}
// 确认
const confirmEmployee = (value) => {
  const { selectedOptions } = value
  form.employeeName = selectedOptions[0]?.text
  form.employeeNo = selectedOptions[0]?.employeeNo
  form.employeeId = selectedOptions[0]?.value
  showEmployeePicker.value = false
}
const confirm = (value) => {
  if (isType.value === '门店') {
    const { selectedOptions } = value
    form.storeName = selectedOptions[0]?.text
    form.storeCode = selectedOptions[0]?.value
    form.storeAddr = selectedOptions[0]?.storeAddr
  } else if (isType.value === '计划') {
    const { selectedOptions } = value
    form.pattern = selectedOptions[0]?.text
  } else if (isType.value === '品项') {
    const { selectedOptions } = value
    form.prdClass = selectedOptions[0]?.text
  }
  showPicker.value = false
}

</script>

<style scoped
  lang="scss">
  .mobile-container {
    background: #f5f5f5;
    min-height: 100vh;
    padding-top: 20px;

    .van-cell-group {
      background: #f5f5f5;
    }

    /* 左侧文字宽度 */
    --van-field-label-width: 100px !important;

    .custom-input {
      display: flex;
      flex-direction: column;

      p {
        font-size: 12px;
        margin: 0;
        color: #757474;
      }
    }
  }
</style>