<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
            readonly
            :disabled="!!planId"
            name="storeName"
            label="选择门店"
            placeholder="点击选择门店"
            required
            :rules="[{ required: true, message: '请选择门店' }]"
            @click="selStoreName" />
          <van-field v-model="form.date"
            is-link
            readonly
            :disabled="!!planId"
            name="date"
            label="活动日期"
            placeholder="点击选择时间"
            required
            :rules="[{ required: true, message: '请选择日期' }]"
            @click="selDate" />
          <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
            :rules="[{ required: true, message: '请选择归属人' }]"
            @click="selEmployee" />
          <van-field v-model="form.inTime"
            is-link
            readonly
            name="inTime"
            label="上班打卡时间"
            placeholder="请选择时间"
            required
            :rules="[{ required: true, message: '请选择时间' }]"
            @click="selInTime" />
          <van-field v-model="form.outTime"
            is-link
            readonly
            :disabled="!form.inTime"
            name="outTime"
            label="下班打卡时间"
            placeholder="请选择时间"
            required
            :rules="[{ required: true, message: '请选择时间' }]"
            @click="selOutTime" />
          <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>
    <PickerSearch v-model="showPicker"
      :columns="columns"
      :searchShow="showPickerSearch"
      @search="search"
      @confirm="confirm"></PickerSearch>
    <van-popup v-model:show="showDatePicker"
      destroy-on-close
      position="bottom">
      <van-date-picker v-model="selDateArr"
        @confirm="onConfirmDate"
        :min-date="minDate"
        :max-date="maxDate" />
    </van-popup>
    <van-popup v-model:show="showInTimePicker"
      destroy-on-close
      position="bottom">
      <van-time-picker v-model="inTime"
        :formatter="formatterTime"
        @confirm="onConfirmInTime"
        title="选择时间" />
    </van-popup>
    <van-popup v-model:show="showOutTimePicker"
      destroy-on-close
      position="bottom">
      <van-time-picker v-model="outTime"
        :min-time="minTime"
        :formatter="formatterTime"
        @confirm="onConfirmOutTime"
        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'
const myForm = ref({})
const { proxy } = getCurrentInstance();
const isCityManager = ref(userStore().promotionIdentity)
const form = reactive({})
const router = useRouter();
const route = useRoute()
const clickBack = () => {
  router.back()
}

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}")
  form.outTime = parseTime(res.data.planInfo.clockOutTime, "{h}:{i}")
  minTime.value = form.inTime + ":00"
}
if (planId) {
  init()
}

const errorSalaryMessage = ref('')
const erroIncidentalMessage = ref('')
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 () => {
  const data = userStore().employeeInfo
  for (const key in data) {
    form[key] = data[key]
  }
  if (planId) {
    const res = await updatePlanByWebAPI(form)
    proxy.$modal.msgSuccess(res.msg)
  } else {
    const res = await addPlanByWebAPI(form)
    proxy.$modal.msgSuccess(res.msg)
  }
  clickBack()
}

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


// 活动日期
const showDatePicker = ref(false)
const selDateArr = ref([])
const minDate = ref('')
const maxDate = ref('')
const selDate = () => {
  showDatePicker.value = true
  selDateArr.value = form.date ? form.date.split('-') : [new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate()]
  minDate.value = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate())
  // 最大值到下个月最后一天
  maxDate.value = new Date(new Date().getFullYear(), new Date().getMonth() + 2, 0)
}
const onConfirmDate = (value) => {
  showDatePicker.value = false
  form.date = value?.selectedValues.join('-')
}

// 选择计划
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 allBelongList = ref([]) // 所有归属人列表
const selEmployee = () => {
  isType.value = '归属人'
  showPicker.value = true
  showPickerSearch.value = true
  columns.value = allBelongList.value
}
const getBelongList = async () => {
  const res = await getChargeListAPI()
  allBelongList.value = res.data.map(item => ({
    text: item.name,
    value: item.employeeNo
  }))
  columns.value = allBelongList.value
  // 判断如果是城市经理，则设置默认归属人为自己
  if (isCityManager.value) {
    form.employeeName = userStore().employeeName
    form.employeeNo = userStore().employeeNo
  }
}
getBelongList()

// 上班打卡时间
const showInTimePicker = ref(false)
const inTime = ref([]) // 选择器里的时间
const selInTime = () => {
  showInTimePicker.value = true
  inTime.value = form.inTime ? form.inTime.split(":") : [new Date().getHours(), new Date().getMinutes()]
}
const onConfirmInTime = (value) => {
  showInTimePicker.value = false
  form.inTime = value.selectedValues.join(':')
  minTime.value = value.selectedValues.join(':') + ":00"
  form.outTime = ''
}

// 下班打卡时间
const showOutTimePicker = ref(false)
const outTime = ref([]) // 选择器里的时间
const minTime = ref([])
const selOutTime = () => {
  showOutTimePicker.value = true
  outTime.value = form.outTime ? form.outTime.split(":") : [new Date().getHours(), new Date().getMinutes()]
}
const onConfirmOutTime = (value) => {
  showOutTimePicker.value = false
  form.outTime = value.selectedValues.join(':')
}

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

// 重置表单
const reset = () => {
  myForm.value.resetValidation()
  errorSalaryMessage.value = ''
  erroIncidentalMessage.value = ''
  form.storeName = ''
  form.date = ''
  form.pattern = ''
  form.employeeName = ''
  form.inTime = ''
  form.outTime = ''
  form.salary = 0
  form.incidentals = 0
}

// 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)
  } else if (isType.value === '归属人') {
    // 模糊搜索
    columns.value = allBelongList.value.filter(item => item.text.includes(value))
  }
}
// 确认
const confirm = (value) => {
  if (isType.value === '门店') {
    const { selectedOptions } = value
    form.storeName = selectedOptions[0]?.text
    form.storeCode = selectedOptions[0]?.value
  } else if (isType.value === '计划') {
    const { selectedOptions } = value
    form.pattern = selectedOptions[0]?.text
  } else if (isType.value === '归属人') {
    const { selectedOptions } = value
    form.employeeName = selectedOptions[0]?.text
    form.employeeNo = selectedOptions[0]?.value
  }
}




</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;
  }
</style>