<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"
      success-text="刷新成功"
      @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"
      v-model:query="query"
      :planColumns="planColumns"
      :allEmpolyeeList="allEmpolyeeList"
      @query="querySearch" />
  </div>
</template>

<script setup>
// 指定当前组件的名字
defineOptions({
  name: 'm_promotion_plan'
})
import userStore from '@/store/modules/user'
import { parseTime } from '@/utils'
import { checkPlanExpire } from '@/hooks'
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 employeeNo = computed(() => userStore().employeeNo)

// 搜索弹窗
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
    }
  })
}

const getPlanList = async () => {
  // 搜索条件改变/刷新时，页码重置为 1
  !loading.value && (query.pageNum = 1)
  const res = await getPlanListAPI({
    pageNum: query.pageNum,
    pageSize: query.pageSize,
    queryParams: {
      activityStartDate: parseTime(query.activityStartDate, "{y}-{m}-{d}"),
      activityEndDate: parseTime(query.activityEndDate, "{y}-{m}-{d}"),
      planStatus: planColumns.find(item => item.text === query.planStatus)?.value,
      employeeId: promotionIdentity.value ? allEmpolyeeList.value.find(o => o.employeeNo === employeeNo.value)?.value : query.employeeId,
      storeNameLike: query.storeNameLike
    },
  })

  planList.value = [...planList.value, ...res.data.records]
  loading.value = false
  refreshLoading.value = false
  finished.value = res.data.records.length < query.pageSize
}

// 加载更多
const onLoad = () => {
  loading.value = true
  query.pageNum++
  getPlanList()
}

// 刷新 
const refreshLoading = ref(false)
const onRefresh = () => {
  setTimeout(async () => {
    query.pageNum = 1
    planList.value = []
    getPlanList()
  }, 300)
}

// 搜索表单
const querySearch = () => {
  query.pageNum = 1
  planList.value = []
  getPlanList()
}

// 编辑计划
const editPlan = (row) => {
  if (!checkPlanExpire(row)) {
    return proxy.$modal.msgWarning('无法编辑，已执行或之前计划')
  }
  router.push(`/m/promotion_plan_editing/${row.id}`)
}

// 删除计划
const deletePlan = (row) => {
  if (!checkPlanExpire(row)) {
    return proxy.$modal.msgWarning('无法删除，已执行或之前计划')
  }
  proxy.$modal.confirm(`确认删除计划吗？`).then(async () => {
    await deletePlanAPI({
      planIds: [row.id],
      employeeNo: employeeNo.value
    })
    proxy.$modal.msgSuccess('删除成功')
    // 找到 row 在数组里第几条删除
    const index = planList.value.findIndex(item => item.id === row.id)
    planList.value.splice(index, 1)
  })
}

const init = async () => {
  await getEmployeeList()
  getPlanList()
}
init()
</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;

          .van-cell__label {
            font-size: 14px !important;
          }

          .employee {
            margin-bottom: 5px !important;
          }

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

          p {
            margin: 0;
          }
        }

        .van-swipe-cell__right {
          display: flex;

          button {
            height: 100%;
          }
        }
      }
    }
  }


</style>