<template>
  <div class="mobile-container">
    <van-nav-bar right-text="搜索"
      @click-right="showSearch = true"
      placeholder
      fixed />
    <!-- 计划列表 -->
    <van-pull-refresh v-model="refreshLoading"
      :pull-distance="100"
      @refresh="onRefresh">
      <van-list v-model:loading="loading"
        :finished="finished"
        :immediate-check="false"
        finished-text="没有更多了"
        @load="onLoad">
        <van-cell-group inset>
          <van-cell v-for="item in planList"
            :key="item.id"
            :title="item.storeName"
            :to="`/promotion_detail/${item.id}`">
            <template #label>
              <p class="employee">{{ item.employeeName }}</p>
              <p v-if="item.planStatus === 0">未执行</p>
              <p v-else
                class="plan-go">执行</p>
            </template>
            <template #value>
              <span>{{ item.pattern }}</span>
              <p>{{ parseTime(item.date, '{y}-{m}-{d} (周{a})') }}</p>
            </template>
          </van-cell>
        </van-cell-group>
      </van-list>
    </van-pull-refresh>

    <van-popup v-model:show="showSearch"
      position="right"
      :style="{ height: '100vh' }">
      <!-- 快捷时间 -->
      <van-field readonly
        label="快捷时间"
        placeholder="选择时间">
        <template #input>
          <van-button size="small"
            type="primary"
            v-for="item in pickerOptions"
            @click="pickerBtn(item)">{{ item.text }}</van-button>
        </template>
      </van-field>
      <!-- 开始时间 -->
      <van-field v-model="query.activityStartDate"
        is-link
        readonly
        name="datePicker"
        label="开始时间"
        placeholder="点击选择时间"
        @click="startShowPicker = true"
        :formatter="formatterStartDate">
      </van-field>
      <van-popup v-model:show="startShowPicker"
        destroy-on-close
        position="bottom"
        teleport="body">
        <van-date-picker v-model="activityStartDatePicker"
          @confirm="onStartConfirm"
          @cancel="startShowPicker = false" />
      </van-popup>
      <!-- 结束时间 -->
      <van-field v-model="query.activityEndDate"
        is-link
        readonly
        name="datePicker"
        label="结束时间"
        placeholder="点击选择时间"
        @click="endShowPicker = true"
        :formatter="formatterEndDate" />
      <van-popup v-model:show="endShowPicker"
        destroy-on-close
        position="bottom"
        teleport="body">
        <van-date-picker v-model="activityEndDatePicker"
          @confirm="onEndConfirm"
          @cancel="endShowPicker = false" />
      </van-popup>
      <!-- 活动类型 -->
      <van-field v-model="query.planStatus"
        is-link
        readonly
        label="活动状态"
        placeholder="选择活动状态"
        @click="planStatusShowPicker = true">
      </van-field>
      <van-popup v-model:show="planStatusShowPicker"
        destroy-on-close
        teleport="body"
        position="bottom">
        <van-picker :model-value="planStatusStr"
          :columns="planColumns"
          @cancel="planStatusShowPicker = false"
          @confirm="onPlanConfirm" />
      </van-popup>
      <!-- 归属人 -->
      <van-field v-model="query.employeeId"
        is-link
        readonly
        label="归属人"
        placeholder="选择归属人"
        :disabled="cityManagerPrivilege"
        @click="employeeIdShowPicker = true">
      </van-field>
      <van-popup v-model:show="employeeIdShowPicker"
        destroy-on-close
        teleport="body"
        position="bottom">
        <van-picker :model-value="planStatusStr"
          :columns="employeeIdColumns"
          @cancel="employeeIdShowPicker = false"
          @confirm="onEmployeeConfirm">
          <template #title>
            <van-search v-model="searchEmployeeName"
              placeholder="搜索归属人"
              @update:model-value="onSearch" />
          </template>
        </van-picker>
      </van-popup>
      <!-- 终端名 -->
      <van-field v-model="query.storeNameLike"
        label="终端名"
        placeholder="请输入终端名"
        @update:model-value="searchByStoreName"
        clearable />
      <!-- 重置按钮 -->
      <van-button icon="replay"
        class="reset"
        block
        @click="resetFn">重置</van-button>
    </van-popup>


    <!-- 测试 url 参数用 -->
    <!-- <div>
      <p class="my-p">{{ url }}</p>
      <button @click="copy">复制 URL</button>
    </div> -->
  </div>
</template>

<script setup>
// 指定当前组件的名字
defineOptions({
  name: 'Mobile_promotion'
})
import { parseTime } from '@/utils'
import { useDatePickerOptions } from '@/hooks'
import { getChargeListAPI, getPlanListAPI } from '@/api'
import store from '@/store'
const { recentPickerOptions: pickerOptions, thisYearDate } = useDatePickerOptions(0)
const router = useRouter()

// 城市经理状态为 true
const cityManagerPrivilege = computed(() => {
  return store.state?.value?.user?.userInfo?.privilegeId == 1
})

// const url = ref('')
// url.value = window.location.href
// 点击复制按钮复制字符串到剪切板
// const copy = () => {
//   const input = document.createElement('input');
//   input.value = url.value;
//   document.body.appendChild(input);
//   input.select();
//   document.execCommand('Copy');
//   document.body.removeChild(input);
//   alert('复制成功');
// }

// 搜索弹窗
const showSearch = ref(false)
// 搜索表单对象
const query = reactive({
  activityStartDate: '',
  activityEndDate: '',
  planStatus: '',
  employeeId: '', // 归属人
  storeNameLike: '', // 终端名
})
// 快捷时间
const pickerBtn = (item) => {
  let [startTime, endTime] = item.value()
  query.activityStartDate = parseTime(startTime)
  query.activityEndDate = parseTime(endTime)
  // 更新两个数组格式时间
  activityStartDatePicker[0] = startTime.getFullYear()
  activityStartDatePicker[1] = startTime.getMonth() + 1
  activityStartDatePicker[2] = startTime.getDate()
  activityEndDatePicker[0] = endTime.getFullYear()
  activityEndDatePicker[1] = endTime.getMonth() + 1
  activityEndDatePicker[2] = endTime.getDate()

  planList.value = []
  planQueryParams.pageNum = 1
  getPlanList()
}
// 开始时间
const startShowPicker = ref(false)
const activityStartDatePicker = [new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate()]
const onStartConfirm = (val) => {
  query.activityStartDate = val.selectedValues.join('-')
  startShowPicker.value = false
}
// 结束时间
const endShowPicker = ref(false)
const activityEndDatePicker = [new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate()]
const onEndConfirm = (val) => {
  query.activityEndDate = val.selectedValues.join('-')
  endShowPicker.value = false
}
// 活动类型( 执行 EXECUTION ，未执行 NOT_EXECUTION)
const planStatusShowPicker = ref(false)
const planStatusStr = ref([])
const planColumns = [
  {
    text: '未执行',
    value: 'NOT_EXECUTION'
  },
  {
    text: '执行',
    value: 'EXECUTION'
  }
]
const onPlanConfirm = (val) => {
  query.planStatus = val.selectedOptions[0].text
  planStatusStr.value = val.selectedValues
  planStatusShowPicker.value = false

  planList.value = []
  planQueryParams.pageNum = 1
  getPlanList()
}
// 归属人
const searchEmployeeName = ref('')
const employeeIdShowPicker = ref(false)
const employeeIdStr = ref([])
// 所有归属人
const employeeIdColumnsAll = ref([])
// 展示归属人
const employeeIdColumns = ref([

])
const onSearch = (val) => {
  employeeIdColumns.value = employeeIdColumnsAll.value.filter(item => {
    return item.text.includes(searchEmployeeName.value)
  })
}
const getEmployeeList = async () => {
  const res = await getChargeListAPI()
  employeeIdColumnsAll.value = res.data.map(item => {
    return {
      text: item.name,
      value: item.id,
      employeeNo: item.employeeNo,
      deptQcName: item.deptQcName,
      deptQcId: item.deptQcId
    }
  })
  employeeIdColumns.value = employeeIdColumnsAll.value
  // 城市经理-填充默认归属人
  if (cityManagerPrivilege.value) {
    query.employeeId = employeeIdColumnsAll.value.find(item => item.employeeNo === store.state.value.user.userInfo.userName)?.text
    employeeIdStr.value = employeeIdColumnsAll.value.find(item => item.employeeNo === store.state.value.user.userInfo.userName)?.value
  }
  getPlanList()
}
getEmployeeList()

const onEmployeeConfirm = (val) => {
  query.employeeId = val.selectedOptions[0].text
  employeeIdStr.value = val.selectedValues
  employeeIdShowPicker.value = false

  planList.value = []
  planQueryParams.pageNum = 1
  getPlanList()
}

// 计划列表
const planQueryParams = reactive({
  pageNum: 1,
  pageSize: 10
})
const planList = ref([])
const loading = ref(false)
const finished = ref(false)
const getPlanList = async () => {
  // 城市经理查自己，职能角色查所有（需要的是促销系统 id）
  if (cityManagerPrivilege.value) {
    // 城市经理 
    planQueryParams.employeeId = employeeIdColumnsAll.value.find(item => item.employeeNo === store.state.value.user.userInfo.userName)?.value
  } else {
    // 职能角色（走查询表单里的值）
    planQueryParams.employeeId = employeeIdColumns.value.find(item => item.text === query.employeeId)?.value
  }
  const res = await getPlanListAPI({
    ...planQueryParams,
    activityDate: [query.activityStartDate, query.activityEndDate],
    planStatus: planColumns.find(item => item.text === query.planStatus)?.value,
    storeName: query.storeNameLike,
  })
  planList.value = [...planList.value, ...res.data.records]
  finished.value = res.data.records.length === 0
  loading.value = false
}


const formatterStartDate = () => {
  return parseTime(query.activityStartDate, '{y}-{m}-{d}')
}
const formatterEndDate = () => {
  return parseTime(query.activityEndDate, '{y}-{m}-{d}')
}

const searchByStoreName = (val) => {
  query.storeNameLike = val
  planList.value = []
  planQueryParams.pageNum = 1
  getPlanList()
}

const onLoad = () => {
  loading.value = true
  planQueryParams.pageNum++
  getPlanList()
}

// 刷新 
const refreshLoading = ref(false)
const onRefresh = () => {
  refreshLoading.value = true
  setTimeout(() => {
    refreshLoading.value = false
    resetFn()
  }, 1000)
}

// 重置
const resetFn = () => {
  query.activityStartDate = ''
  query.activityEndDate = ''
  query.planStatus = ''
  query.employeeId = ''
  query.storeNameLike = ''
  planList.value = []
  planQueryParams.pageNum = 1
  getPlanList()
}

</script>

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

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

    .van-cell {
      margin-top: 10px;

      ::v-deep(.van-cell__title) {
        /* 强制一行显示 */
        /* white-space: nowrap; */
      }

      p {
        margin: 0;
      }
    }
  }

  .van-list {
    min-height: 100vh;
    /* overflow-x: hidden; */
  }

  .reset {
    margin-top: 20px;
  }

  ::v-deep(.van-field):first-of-type {
    .van-button {
      margin: 0 2.5px;
      padding: 0 5px;
      font-size: 12px !important;
    }

    .van-cell__right-icon:first-of-type {
      display: none;
    }
  }

  .plan-go {
    color: #39bb74;
  }

  ::v-deep(.employee) {
    margin-bottom: 5px !important;
  }

  ::v-deep(.van-popup--right) {
    width: 85% !important;
  }

  ::v-deep(.van-cell__label) {
    font-size: 14px !important;
  }

  .van-search {
    width: 60%;
  }
</style>