<template>
  <div class="mobile-container">
    <van-nav-bar right-text="搜索"
      left-text="新增计划"
      @click-left="$router.push('/m/promotion_plan_editing')"
      @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-swipe-cell v-for="item in planList"
            :key="item.id">
            <van-cell :title="item.storeName"
              :to="`/m/promotion_plan_detail/${item.id}`">
              <template #label>
                <p class="employee">{{ item.employeeName }}</p>
                <p :class="{ 'plan-go': item.planStatus === 1 }">
                  {{ getPromotionActiveStatus(item.planStatus).label }}
                </p>
              </template>
              <template #value>
                <span>{{ item.pattern }}</span>
                <p>{{ parseTime(item.date, '{y}-{m}-{d} (周{a})') }}</p>
              </template>
            </van-cell>
            <template #right>
              <van-button square
                type="success"
                text="编辑"
                @click="editPlan(item)" />
              <van-button square
                type="danger"
                text="删除"
                @click="deletePlan(item)" />
            </template>
          </van-swipe-cell>
        </van-cell-group>
      </van-list>
    </van-pull-refresh>

    <!-- 搜索组件 -->
    <PlanSearch v-model:show="showSearch"
      :planColumns="planColumns"
      :allEmpolyeeList="allEmpolyeeList"
      @query="getPlanList" />
  </div>
</template>

<script setup>
// 指定当前组件的名字
defineOptions({
  name: 'm_promotion_plan'
})

import { parseTime } from '@/utils'
import userStore from '@/store/modules/user'
import { getPromotionActiveStatus } from '@/dicts'
import { getChargeListAPI, getPlanListAPI, deletePlanAPI } from '@/api'
import PlanSearch from './plan-search.vue'

const { proxy } = getCurrentInstance();
const router = useRouter()
const promotionIdentity = computed(() => userStore().promotionIdentity)
const employeeName = computed(() => userStore().employeeName)

// 搜索弹窗
const showSearch = ref(false)

// 计划列表
const query = reactive({
  pageNum: 1,
  pageSize: 10
})
const planList = ref([])
const loading = ref(false)
const finished = ref(false)

// 活动状态
const planColumns = [
  {
    text: '未执行',
    value: 'NOT_EXECUTION'
  },
  {
    text: '执行',
    value: 'EXECUTION'
  }
]

// 归属人
const allEmpolyeeList = ref([])
const getEmployeeList = async () => {

  const res = await getChargeListAPI()
  allEmpolyeeList.value = res.data.map(item => {
    return {
      text: item.name,
      value: item.id,
      employeeNo: item.employeeNo,
      deptQcName: item.deptQcName,
      deptQcId: item.deptQcId
    }
  })
}
getEmployeeList()
const getPlanList = async ({activityStartDate, activityEndDate, planStatus, employeeId, storeNameLike} = {}) => {
  const res = await getPlanListAPI({
    ...query,
    queryParams: {
      activityStartDate: parseTime(activityStartDate, "{y}-{m}-{d}"),
      activityEndDate: parseTime(activityEndDate, "{y}-{m}-{d}"),
      planStatus: planColumns.find(item => item.text === planStatus)?.value,
      employeeId,
      storeNameLike
    },
  })
  planList.value = res.data.records
  // planList.value = [...planList.value, ...res.data.records]
  finished.value = res.data.records.length === 0
  loading.value = false
}
getPlanList()

// const init = async () => {
//   await 
//   // getPlanList()
// }
// init()

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

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

// 编辑计划
const editPlan = (row) => {
  router.push(`/m/promotion_plan_editing/${row.id}`)
}

// 删除计划
const deletePlan = (row) => {
  proxy.$modal.confirm(`确认删除计划吗？`).then(async () => {
    await deletePlanAPI({
      planIds: [row.id],
      employeeNo: useuserStore().employeeNo
    })
    proxy.$modal.msgSuccess('删除成功')
    // 找到 row 在数组里第几条删除
    const index = planList.value.findIndex(item => item.id === row.id)
    planList.value.splice(index, 1)
  })
}

</script>

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

    .van-list {
      min-height: 100vh;

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

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

          ::v-deep(.van-swipe-cell__right) {
            display: flex;

            button {
              height: 100%;
            }
          }

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

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

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

          p {
            margin: 0;
          }
        }
      }
    }
  }


</style>