<template>
  <div class="mobile-container">
    <van-nav-bar right-text="搜索"
      left-arrow
      @click-left="clickBack"
      @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"
              :class="{ 'plan-deleted': query.isDeleted }"
              @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 && !query.isDeleted">
              <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 ref="planSearch"
      v-model:show="showSearch"
      v-model:query="query"
      :planColumns="planColumns"
      :allEmpolyeeList="allEmpolyeeList"
      @query="querySearch" />
    <!-- 新增组件（浮动气泡） -->
    <van-floating-bubble icon="plus"
      @click="addNewPlan" />
    <!-- 底部-长按操作栏 -->
    <van-action-bar v-show="showSelect">
      <van-action-bar-button type="default"
        text="取消"
        @click="cancelActionBar" />
      <van-action-bar-button type="warning"
        text="修改归属人"
        @click="clickChangeBelong" />
      <van-action-bar-button type="danger"
        text="删除"
        @click="clickDelSome" />
    </van-action-bar>
    <!-- 选择归属人 -->
    <PickerBelong v-model:show="showPickerBelong"
      @confirm="confirmPickerBelong" />
  </div>
</template>

<script setup>
// 指定当前组件的名字
defineOptions({
  name: 'Promotion_plan'
})
import userStore from '@/store/modules/user'
import { parseTime } from '@/utils'
import { checkPlanExpire, checkPlanChangeExpire } from '@/hooks'
import { PROMOTION_STATUS, getPromotionActiveStatus } from '@/dicts'
import { getPlanListAPI, deletePlanAPI, batchUpdatePlanAPI, getChargeListAPI } from '@/api'
import PlanSearch from './planSearch.vue'
import PickerBelong from '../components/PickerBelong'

const { proxy } = getCurrentInstance();
const router = useRouter()
const route = useRoute()
const isCityManager = userStore().promotionIdentity
const empInfo = userStore().empInfo

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

// 从新增页面跳转回来需要刷新列表
watch(() => route.path, (newPath, oldPath) => {
  console.log(oldPath, newPath)
  if (oldPath.includes('/cp_activity/promotion_plan_editing') && newPath === '/cp_activity/promotion_plan') {
    planSearch.value.resetFn()
  }
});

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

// 活动状态
const planColumns = Object.values(PROMOTION_STATUS).map(item => {
  return {
    text: item.label,
    value: item.value
  }
})

// 归属人
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: isCityManager ? allEmpolyeeList.value.find(o => o.employeeNo === empInfo.empNo)?.value : query.employeeId,
      storeNameLike: query.storeNameLike,
      statusType: query.isDeleted
    },
  })

  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 || query.isDeleted) return
  // router.push(`/cp_activity/promotion_plan_detail/${row.id}?isDeleted=${query.isDeleted}`)
  router.push(`/cp_activity/promotion_plan_detail/${row.id}`)
}

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

// 变更计划
const editPlan = (row) => {
  if (!checkPlanExpire(row)) {
    return showNotify({ type: 'warning', message: '无法变更，已执行或之前计划' })
  }
  // 日期小于等于今日，无法变更
  if (!checkPlanChangeExpire(row)) {
    return showNotify({ type: 'warning', message: '无法变更，日期小于等于今日' })
  }
  router.push(`/cp_activity/promotion_plan_editing/${row.id}`)
}

// 删除计划
const deletePlan = (row) => {
  if (!checkPlanExpire(row)) {
    return showNotify({ type: 'warning', message: '无法删除，已执行或之前计划' });
  }
  showConfirmDialog({
    title: '系统提示',
    message:
      '确认删除计划吗？'
  }).then(async () => {
    await deletePlanAPI({
      planIds: [row.id],
      employeeNo: empInfo.empNo
    })
    showNotify({ type: 'success', message: '删除成功' })
    // 重新获取列表
    onRefresh()
  })
}

onMounted(async () => {
  await getEmployeeList()
  getPlanList()
})


// 长按出现全选功能
const showSelect = ref(false)
const onLongPress = () => {
  if (query.isDeleted) return // 已删除
  showSelect.value = true
}

// 删除全选的计划
const clickDelSome = () => {
  const ids = planList.value.filter(item => item.checked).map(item => item.id)
  if (ids.length === 0) {
    return showNotify({ type: 'warning', message: '请选择要删除的计划' })
  }
  showConfirmDialog({
    title: '系统提示',
    message: `确认删除${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 showNotify({ type: 'warning', message: '无法删除，已执行或之前计划' })
      }
    }
    await deletePlanAPI({
      planIds: ids,
      employeeNo: empInfo.empNo
    })
    showNotify({ type: 'success', message: '删除成功' })
    showSelect.value = false
    onRefresh()
  })
}

// 选择归属人
const showPickerBelong = ref(false)
const clickChangeBelong = () => {
  const ids = planList.value.filter(item => item.checked).map(item => item.id)
  if (ids.length === 0) {
    return showNotify({ type: 'warning', message: '请选择要修改归属人的计划' })
  }
  for (let i = 0; i < ids.length; i++) {
    const item = planList.value.find(o => o.id === ids[i])
    if (!checkPlanExpire(item)) {
      return showNotify({ type: 'warning', message: '无法修改，已执行或之前计划' })
    }
  }
  showPickerBelong.value = true
}
const confirmPickerBelong = async (val) => {
  showPickerBelong.value = false
  showSelect.value = false
  // 调用后台接口批量修改归属人
  // 循环判断计划是否含有以前和执行中的
  await batchUpdatePlanAPI({
    employeeId: val.selectedOptions[0]?.value, // 选择的归属人 id
    operName: empInfo.empName,
    planIds: planList.value.filter(item => item.checked).map(item => item.id)
  })
  showNotify({ type: 'success', message: '修改成功' })
  onRefresh()
}

const planSearch = ref({})
const clickBack = () => {
  planSearch.value.resetFn()
  showSelect.value = false
  router.back()
}

const cancelActionBar = () => {
  showSelect.value = false
  // 把复选框的值都取消
  planList.value.forEach(item => {
    item.checked = false
  })
}

// 订阅删除促销任务事件
onMounted(() => {
  // 订阅事件
  proxy.eventBus.on('delPromotionTaskEvent', () => {
    planList.value = []
    getPlanList()
  });
});
onUnmounted(() => {
  // 取消订阅事件
  proxy.eventBus.off('delPromotionTaskEvent');
})

// 新增计划判断
const addNewPlan = () => {
  // 后台设置按钮权限分配就能新增
  if (proxy.checkPermi(['promotion:plan:create'])) {
    router.push('/cp_activity/promotion_plan_editing')
  } else {
    showNotify({ type: 'warning', message: '规定日期内_无法新增计划' })
  }
}
</script>

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

    /* 头部返回按钮 */
    ::v-deep(.van-nav-bar) {

      .van-icon,
      .van-nav-bar__text {
        color: var(--main-color);
      }
    }

    .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 {
              &.plan-deleted {
                background-color: rgb(235, 235, 235);
              }

              .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 {
      padding: 0 0 0 20px;

      .van-button--default {
        background-color: #f5f5f5;
      }

      span {
        font-size: 14px;
        padding: 0 10px;
      }
    }
  }


</style>