<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 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>
    <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="inTime"
        :formatter="formatterTime"
        @confirm="onConfirmInTime"
        @cancel="showInTimePicker = false"
        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"
        @cancel="showInTimePicker = 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({})
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}")
  form.outTime = parseTime(res.data.planInfo.clockOutTime, "{h}:{i}")
  minTime.value = form.inTime + ":00"

  editDealerId.value = res.data.planInfo.dealerId
}
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 () => {
  form.operNo = empInfo.empNo
  form.operName = empInfo.empName
  form.operId = empInfo.empId

  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 = 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 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
  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
  }
  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>