<template>
  <div class="mobile-container">
    <van-nav-bar right-text="搜索"
      left-arrow
      @click-left="$router.back()"
      @click-right="showSearch = true"
      placeholder
      fixed />
    <!-- 计划列表 -->
    <van-pull-refresh v-model="refreshLoading"
      :pull-distance="100"
      success-text="刷新成功"
      @refresh="onRefresh"
      :class="{safe_bottom: showSelect}">
      <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"
            v-long-press="onLongPress">
            <van-checkbox v-show="showSelect"
              v-model="item.checked"
              shape="square" />
            <van-cell :title="item.storeName"
              @click="clickDetail(item)">
              <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
              v-if="!showSelect">
              <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" />
    <!-- 新增组件（浮动气泡） -->
    <van-floating-bubble icon="plus"
      @click="$router.push('/m/promotion_plan_editing')" />
    <!-- 底部-长按操作栏 -->
    <van-action-bar v-show="showSelect">
      <span @click="showSelect = false">取消</span>
      <van-action-bar-button type="warning"
        text="修改归属人" />
      <van-action-bar-button type="danger"
        text="删除"
        @click="clickDelSome" />
    </van-action-bar>
  </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 clickDetail = (row) => {
  if (showSelect.value) return // 当前处于长按状态，点击详情不做任何操作
  router.push(`/m/promotion_plan_detail/${row.id}`)
}

// 搜索表单
const querySearch = () => {
  onRefresh()
}

// 编辑计划
const editPlan = (row) => {
  console.log(123)
  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('删除成功')
    // 重新获取列表
    onRefresh()
  })
}

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

onActivated(() => {
  querySearch()
})

// 长按出现全选功能
const showSelect = ref(false)
const onLongPress = () => {
  showSelect.value = true
}

// 删除全选的计划
const clickDelSome = () => {
  const ids = planList.value.filter(item => item.checked).map(item => item.id)
  if (ids.length === 0) {
    return proxy.$modal.msgWarning('请选择要删除的计划')
  } 
  proxy.$modal.confirm(`确认删除${ids.length}条计划吗？`).then(async () => {
    // 循环判断计划是否含有以前和执行中的
    for (let i = 0; i < ids.length; i++) {
      const item = planList.value.find(o => o.id === ids[i])
      if (!checkPlanExpire(item)) {
        return proxy.$modal.msgWarning('无法删除，已执行或之前计划')
      } 
    }
    await deletePlanAPI({
      planIds: ids,
      employeeNo: employeeNo.value
    }) 
    proxy.$modal.msgSuccess('删除成功')
    showSelect.value = false
    onRefresh()
  })
}
</script>

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

    .van-pull-refresh{
      /* 并列选择身上的类名 */
      &.safe_bottom{
        padding-bottom: 50px; 
      }
    }

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

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

        .van-swipe-cell {
          /* 阻止长按选文字效果 */
          -webkit-user-select: none;
          -moz-user-select: none;
          -ms-user-select: none;
          user-select: none;

          /* Standard syntax */
          ::v-deep(.van-swipe-cell__wrapper) {
            display: flex;
            margin-top: 10px;

            .van-checkbox {
              padding-right: 10px;
            }

            .van-cell {

              .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%;
              }
            }
          }

        }

      }
    }

    /* 底部菜单 */
    .van-action-bar {
      span {
        font-size: 14px;
        padding: 0 10px;
      }
    }
  }


</style>