<template>
  <div class="app-container">
    <div class="container">
      <!-- 查询表单 -->
      <el-form :model="queryParams"
        inline
        label-width="68px">
        <el-row>
          <el-form-item label="活动状态"
            prop="planStatus">
            <el-select v-model="queryParams.planStatus"
              placeholder="请选择活动状态"
              filterable
              clearable
              @change="getPlanList">
              <el-option v-for="item in taskStatusList"
                :key="item.value"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-row>
      </el-form>
      <!-- 表格列表 -->
      <el-table :data="tableList"
        border
        show-overflow-tooltip
        @selection-change="handleSelectionChange"
        :row-class-name="tableRowTimeOutClassName">
        <el-table-column v-for="item in columns"
          :key="item.label"
          :prop="item.prop"
          :label="item.label"
          :width="item.width"
          :formatter="formatter"
          :fixed="item.fixed"
          :show-overflow-tooltip="true" />
        <el-table-column label="操作"
          width="150"
          fixed="right">
          <template #default="scope">
            <el-button type="success"
              link
              @click="editFn(scope.row)">
              查看名单
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination :total="total"
        v-model:page="pageNum"
        v-model:limit="pageSize"
        @pagination="getPlanList" />

      <!-- 参与人员名单 -->
      <el-dialog v-model="participantDialogVisible"
        title="参与人员名单"
        width="80%"
        :close-on-click-modal="false"
        :close-on-press-escape="false">
        <div class="participant-dialog-content">
          <el-table :data="participantList"
            border
            stripe
            height="400"
            v-loading="participantLoading">
            <el-table-column prop="name"
              label="昵称"
              width="120"
              align="center" />
            <el-table-column prop="position"
              label="是否中奖"
              width="120"
              align="center" />
            <el-table-column prop="department"
              label="奖项等级"
              width="150"
              align="center" />
            <el-table-column prop="phone"
              label="奖品名称"
              width="150"
              align="center" />
            <el-table-column prop="email"
              label="收货地址"
              min-width="200"
              align="center" />
            <el-table-column prop="joinTime"
              label="收货人姓名"
              width="180"
              align="center" />
            <el-table-column prop="status"
              label="联系电话"
              width="100"
              align="center">
              <template #default="scope">
                <el-tag :type="scope.row.status === '已确认' ? 'success' : 'warning'">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button type="primary"
                  link
                  @click="fillOrderNumberFn(scope.row)">
                  填写单号
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 弹窗内分页 -->
          <div class="participant-pagination">
            <el-pagination v-model:current-page="participantPageNum"
              v-model:page-size="participantPageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="participantTotal"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleParticipantSizeChange"
              @current-change="handleParticipantCurrentChange" />
          </div>
        </div>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="participantDialogVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 填写单号弹窗 -->
      <el-dialog v-model="orderNumberDialogVisible"
        title="填写发货单号"
        width="500px"
        :close-on-click-modal="false"
        :close-on-press-escape="false">
        <el-form :model="orderNumberForm"
          :rules="orderNumberRules"
          ref="orderNumberFormRef"
          label-width="100px">
          <el-form-item label="发货单号"
            prop="shipmentNumber">
            <el-input v-model="orderNumberForm.shipmentNumber"
              placeholder="请输入发货单号"
              maxlength="50"
              show-word-limit />
          </el-form-item>
          <el-form-item label="备注信息"
            prop="notes">
            <el-input v-model="orderNumberForm.notes"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息（可选）"
              maxlength="200"
              show-word-limit />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="orderNumberDialogVisible = false">取消</el-button>
            <el-button type="primary"
              @click="handleSaveOrderNumber">保存</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { v4 as uuidv4 } from 'uuid';
import { getPlanListAPI, uploadFileToOSSAPI, addPlanAPI, savePlanAPI, deletePlanAPI, addPlanByRoleAPI, getChargeListAPI, addPlanByWebAPI, updatePlanByWebAPI, getPlanStoreListAPI, updatePlanAPI, batchUpdatePlanAPI } from '@/api'
import { checkPlanExpire, checkPlanChangeExpire } from '@/hooks'
import userStore from '@/store/modules/user'
import { PROMOTION_ACTIVITY_MODE_LIST, getPromotionActiveStatus } from '@/dicts'
import { parseTime } from '@/utils'

const props = defineProps({
  queryParams: {
    type: Object
  }
})

const taskStatusList = ref([
  {
    label: '进行中',
    value: '进行中'
  },
  {
    label: '过期',
    value: '过期'
  }
])

const queryParams = reactive({
  activityDate: [],
  planStatus: '',
  region: '全国',
  provinceId: '',
  cityId: '',
  dealerId: '', // 经销商
  warZoneId: '', // 战区
  employeeId: '', // 归属人
  storeName: '', // 门店名称
})

const { proxy } = getCurrentInstance();
const isCityManager = userStore().promotionIdentity
const empInfo = userStore().empInfo

const planTemplateExcelUrl = import.meta.env.VITE_APP_PLAN_TEMPLATE_EXCEL
const uploadPlanExcelPath = `planExcel/${new Date().getFullYear()}-${new Date().getMonth() + 1}/${empInfo.empNo}/${uuidv4()}.xlsx` // 上传计划表格路径

/*************** 删除计划 ***************/
// 批量
const delMultipleBtnDis = ref(true)
const handleDelete = async () => {
  await proxy.$modal.confirm('确认删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  await deletePlanAPI({
    planIds: checkedRowList.value.map(o => o.id),
    employeeNo: empInfo.empNo
  })
  proxy.$modal.msgSuccess('删除成功')
  proxy.eventBus.emit('refreshPlanList') // 刷新计划列表
  getPlanList()
}
// 单条
const deletePlane = (row) => {
  checkedRowList.value = [row]
  handleDelete()
}

/*************** 新增计划 ***************/
const isHaveErrPlan = ref(false) // 上传表格计划中有无错误
// 批量
const uploadPlanFile = async (file) => { // 上传计划表格
  proxy.$modal.loading("正在上传数据，请稍后...");
  const excelUrl = await uploadFileToOSSAPI(uploadPlanExcelPath, file.file)
  const targetAPI = isCityManager ? addPlanAPI : addPlanByRoleAPI // 城市经理和职能角色上传接口不同
  try {
    const res = await targetAPI({
      "excelUrl": excelUrl,
      "employeeNo": empInfo.empNo
    })
    console.log(res)
    planTableList.value = res.data.table
    isHaveErrPlan.value = !!res.data.table[0].errorMsg
    confirmExcelUUID.value = res.data.uuid
    uploadPlanDialogVisible.value = true
  } finally {
    proxy.$modal.closeLoading();
  }
  // 保证下次还能上传
  return true
}
// 单条
const handleAdd = () => {
  resetAddOrEditPlanForm()
  // 城市经理，默认填充归属人
  isCityManager && (addOrEditPlanForm.value.employeeNo = empInfo.empNo)
  addOrEditPlanVisible.value = true
}

/*************** 修改计划 ***************/
// 批量
const uploadChangeFile = async (file) => {
  proxy.$modal.loading("正在上传数据，请稍后...");
  const excelUrl = await uploadFileToOSSAPI(uploadPlanExcelPath, file.file)
  try {
    const res = await updatePlanAPI({
      "excelUrl": excelUrl,
      "employeeNo": empInfo.empNo
    })
    planTableList.value = res.data.table
    isHaveErrPlan.value = !!res.data.table[0].errorMsg
    confirmExcelUUID.value = res.data.uuid
    uploadPlanDialogVisible.value = true
  } finally {
    proxy.$modal.closeLoading();
  }
  return true
}
// 单条
const participantDialogVisible = ref(false)
const editFn = (row) => {
  participantDialogVisible.value = true
  proxy.resetForm("addOrEditPlanRef");
  addOrEditPlanForm.value = {
    ...row,
    inTime: parseTime(row.clockInTime, "{h}:{i}:{s}"),
    outTime: parseTime(row.clockOutTime, "{h}:{i}:{s}"),
    noonInTime: parseTime(row.noonClockInTime, "{h}:{i}:{s}"),
    noonOutTime: parseTime(row.noonClockOutTime, "{h}:{i}:{s}"),
  }
  editDealerId.value = row.dealerId
  getStoreList()
  addOrEditPlanVisible.value = true
}

/*************** 新增/修改计划弹框 ***************/
// 新增/变更计划表单弹框
const addOrEditPlanVisible = ref(false)
const addOrEditPlanForm = ref({})
const activityModeList = ref(PROMOTION_ACTIVITY_MODE_LIST) // 活动模式
const editDealerId = ref(null) // 经销商 ID
// 重置表单
const resetAddOrEditPlanForm = () => {
  addOrEditPlanForm.value = {}
  selecteStoreInfo.value = ''
  editDealerId.value = null
  isInfoError.value = false
}
// 表单验证（所有都是必填项）
const addOrEditPlanFormRules = reactive({
  storeCode: [
    {
      required: true,
      message: '请输入门店编码',
      trigger: 'blur'
    }
  ],
  date: [
    {
      required: true,
      message: '请选择活动日期',
      trigger: 'blur'
    }
  ],
  pattern: [
    {
      required: true,
      message: '请选择活动模式',
      trigger: 'blur'
    }
  ],
  employeeNo: [
    {
      required: true,
      message: '请选择归属人',
      trigger: 'blur'
    }
  ],
  inTime: [
    {
      required: true,
      message: '请选择上班打卡时间',
      trigger: 'blur'
    }
  ],
  noonOutTime: [
    {
      message: '请选择中午打卡时间',
      trigger: 'blur'
    }
  ],
  noonInTime: [
    {
      validator: (rule, value, callback) => {
        // 如果填写了午休开始时间，则午休结束时间必填
        if (addOrEditPlanForm.value.noonOutTime && !value) {
          callback(new Error('请填写午休结束时间'));
        } else {
          callback();
        }
      },
      message: '请选择中午打卡时间',
      trigger: 'blur'
    }
  ],
  outTime: [
    {
      required: true,
      message: '请选择下班打卡时间',
      trigger: 'blur'
    }
  ],
  temWlSct: [
    {
      required: true,
      message: '请选择是否有试吃台',
      trigger: 'blur'
    }
  ],
  prdClass: [
    {
      required: true,
      message: '请选择活动品项',
      trigger: 'blur'
    }
  ],
  // salary: [
  //   {
  //     required: true,
  //     message: '请输入工资',
  //     trigger: 'blur'
  //   }
  // ],
  // incidentals: [
  //   {
  //     required: true,
  //     message: '请输入杂费',
  //     trigger: 'blur'
  //   }
  // ]
})
// 获取门店列表
const storeList = ref([])
const allStoreList = ref([])
const selecteStoreInfo = ref('')
const isInfoError = ref(false)
const prdList = ref([
  {
    label: '老品',
    value: '老品'
  },
  {
    label: '黑鸭',
    value: '黑鸭'
  },
  {
    label: '散称',
    value: '散称'
  }
])
const getStoreList = async () => {
  const { data } = await getPlanStoreListAPI({
    storeNameVague: addOrEditPlanForm.value.storeName,
    dealerId: editDealerId.value
  })
  allStoreList.value = data
  storeList.value = data.map(item => {
    return {
      label: item.storeName,
      value: item.storeCode
    }
  })
}
getStoreList()
// 选择门店
const selStoreInfo = (storeCode) => {
  // 从门店列表找到选中的对象
  const storeInfo = allStoreList.value.find(item => item.storeCode === storeCode)
  // 判断门店是否包含必要的三个信息（因为勤测那边的数据一致性不好，所以需要判断）
  if (storeInfo) {
    if (!storeInfo.dealersName || !storeInfo.dealerId || !storeInfo.lineName) {
      isInfoError.value = true
      // 门店系统名称、经销商不可为空，请到勤策中修改；
      selecteStoreInfo.value = "门店系统名称、经销商不可为空，请到勤策中修改:"
    } else {
      isInfoError.value = false
      // 门店系统名称、经销商不可为空，请到勤策中修改；
      selecteStoreInfo.value = storeInfo.storeAddr + "-" + storeInfo.storeCode
    }
  } else {
    isInfoError.value = false
    // 门店系统名称、经销商不可为空，请到勤策中修改；
    selecteStoreInfo.value = ''
  }
  // 清除表单验证提示
  proxy.$refs.addOrEditPlanRef.clearValidate('storeCode');
}
// 门店搜索
const remoteStoreMethod = (query) => {
  addOrEditPlanForm.value.storeName = query
  getStoreList()
}

// 定义禁用日期的函数
const disabledDateFn = (time) => {
  // 城市经理
  if (isCityManager) {
    // 如果是变更状态，则只能修改次日到本月底最后一日
    if (addOrEditPlanForm.value.id) {
      const now = new Date();
      const nextDay = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1)
      const end = new Date(now.getFullYear(), now.getMonth() + 1, 0);

      return time.getTime() < nextDay.getTime() || time.getTime() > end.getTime()
    }
    // 如果是新增状态，只能新增下个月一整个月的
    const now = new Date();
    const start = new Date(now.getFullYear(), now.getMonth() + 1, 1);
    const end = new Date(now.getFullYear(), now.getMonth() + 2, 0);
    return time.getTime() < start.getTime() || time.getTime() > end.getTime()
  } else {
    // 职能角色能添加当月今天往后和下个月一整个月
    const now = new Date();
    // 变更计划时，只能选择明天以后的
    const thisMonthStart = new Date(now.getFullYear(), now.getMonth(), addOrEditPlanForm.value.id ? now.getDate() + 1 : now.getDate());
    const nextMonthEnd = new Date(now.getFullYear(), addOrEditPlanForm.value.id ? now.getMonth() + 1 : now.getMonth() + 2, 0);
    return time.getTime() < thisMonthStart.getTime() || time.getTime() > nextMonthEnd.getTime();
  }
}
// 根据选择的开始时间，禁用小时分钟秒只能选择之后的时间
const makeRange = (start, end) => {
  const result = []
  for (let i = start; i <= end; i++) {
    result.push(i)
  }
  return result
}
// 根据上班时间选择的结果，禁用小时
const disabledHours = (key) => {
  if (key === 'noonOutTime') {
    return () => {
      const time = addOrEditPlanForm.value.inTime
      if (!time) return
      const [hours, minutes, seconds] = time.split(':').map(Number)
      return makeRange(0, hours - 1)
    }
  } else if (key === 'noonInTime') {
    return () => {
      const time = addOrEditPlanForm.value.noonOutTime
      if (!time) return
      const [hours, minutes, seconds] = time.split(':').map(Number)
      return makeRange(0, hours - 1)
    }
  } else if (key === 'outTime') {
    return () => {
      // 如果有午休结束时间则判断，否则用上班时间
      const time = addOrEditPlanForm.value.noonInTime || addOrEditPlanForm.value.inTime
      if (!time) return
      const [hours, minutes, seconds] = time.split(':').map(Number)
      return makeRange(0, hours - 1)
    }
  }
}
// 如果小时大于上班打卡时间小时，则不限制分钟
const disabledMinutes = (key) => {
  if (key === 'noonOutTime') {
    return (h) => {
      const time = addOrEditPlanForm.value.inTime
      if (!time) return
      const [hours, minutes, seconds] = time.split(':').map(Number)
      if (h > hours) {
        return makeRange(0, -1);
      } else {
        return makeRange(0, minutes);
      }
    }
  } else if (key === 'noonInTime') {
    return (h) => {
      const time = addOrEditPlanForm.value.noonOutTime
      if (!time) return
      const [hours, minutes, seconds] = time.split(':').map(Number)
      if (h > hours) {
        return makeRange(0, -1);
      } else {
        return makeRange(0, minutes);
      }
    }
  } else if (key === 'outTime') {
    return (h) => {
      const time = addOrEditPlanForm.value.noonInTime || addOrEditPlanForm.value.inTime
      if (!time) return
      const [hours, minutes, seconds] = time.split(':').map(Number)
      if (h > hours) {
        return makeRange(0, -1);
      } else {
        return makeRange(0, minutes);
      }
    }
  }
}

// 新增计划表单-选完以后去掉错误提示
const selPattern = () => {
  proxy.$refs.addOrEditPlanRef.clearValidate('pattern');
}
const selEmployee = () => {
  proxy.$refs.addOrEditPlanRef.clearValidate('employeeNo');
}

// 保存新增/变更计划
const handleAddOrEditPlan = async () => {
  // 表单校验
  await proxy.$refs.addOrEditPlanRef.validate()
  // 设置操作人参数给后台
  addOrEditPlanForm.value.operNo = empInfo.empNo
  addOrEditPlanForm.value.operName = empInfo.empName
  addOrEditPlanForm.value.operId = empInfo.empId

  const dataObj = {
    ...addOrEditPlanForm.value,
    // 格式是 xx:xx:xx，替换最后一对 xx 为 00
    inTime: addOrEditPlanForm.value.inTime.replace(/:\d{2}$/, ':00'),
    noonOutTime: addOrEditPlanForm.value.noonOutTime?.replace(/:\d{2}$/, ':00'),
    noonInTime: addOrEditPlanForm.value.noonInTime?.replace(/:\d{2}$/, ':00'),
    outTime: addOrEditPlanForm.value.outTime.replace(/:\d{2}$/, ':00')
  }

  if (dataObj.id) {
    // 根据归属人 employeeId 查询它的 id 和名字
    const employeeInfo = belongPerList.value.find(item => item.employeeNo === dataObj.employeeNo)
    dataObj.employeeId = employeeInfo.value
    dataObj.employeeName = employeeInfo.label
    await updatePlanByWebAPI(dataObj)
  } else {
    await addPlanByWebAPI(dataObj)
  }

  proxy.$modal.msgSuccess('保存成功')
  addOrEditPlanVisible.value = false
  getPlanList()
}

/*************** 修改归属人 ***************/
// 批量
const editMultipleBtnDis = ref(true)
const handleEditBelong = () => {
  editPlanEmpVisible.value = true
  nextTick(() => {
    editPlanEmpForm.value.employeeId = null
    proxy.resetForm("editPlanEmpRef");
  })
}
const editPlanEmpVisible = ref(false)
const editPlanEmpForm = ref({
  employeeId: null
})
const editPlanEmpRules = ref({
  employeeId: [{
    required: true,
    message: '请选择归属人',
    trigger: 'change'
  }]
})

// 确定批量修改计划人
const handleEditPlanEmp = async () => {
  const res = await batchUpdatePlanAPI({
    employeeId: editPlanEmpForm.value.employeeId,
    operName: empInfo.empName,
    planIds: checkedRowList.value.map(item => item.id)
  })
  proxy.$modal.msgSuccess(res.msg)
  editPlanEmpVisible.value = false
  getPlanList()
}

/*************** 计划表格 ***************/
const tableList = ref([
  {
    id: 1,
    employeeName: '抓财手活动',
    nickName: '2026.12.01',
    province: '2026.12.31',
    planStatus: '进行中',
    date: '2024-01-15',
    week: '周一',
    modifyTime: '2024-01-15 10:30:00',
    clockInTime: '09:00:00',
    clockOutTime: '18:00:00',
    noonClockOutTime: '12:00:00',
    noonClockInTime: '13:30:00',
    employeeNo: '202611期',
    salary: 500,
    incidentals: 100
  },
  {
    id: 2,
    employeeName: '李四',
    nickName: '夏季大促活动',
    province: '上海市',
    planStatus: '过期',
    date: '2024-01-14',
    week: '周日',
    modifyTime: '2024-01-14 14:20:00',
    clockInTime: '08:30:00',
    clockOutTime: '17:30:00',
    noonClockOutTime: '12:00:00',
    noonClockInTime: '13:00:00',
    employeeNo: 'EMP002',
    salary: 600,
    incidentals: 150
  },
  {
    id: 3,
    employeeName: '王五',
    nickName: '国庆节促销',
    province: '广东省',
    planStatus: '进行中',
    date: '2024-01-16',
    week: '周二',
    modifyTime: '2024-01-16 09:15:00',
    clockInTime: '09:30:00',
    clockOutTime: '18:30:00',
    noonClockOutTime: '12:30:00',
    noonClockInTime: '14:00:00',
    employeeNo: 'EMP003',
    salary: 550,
    incidentals: 120
  },
  {
    id: 4,
    employeeName: '赵六',
    nickName: '双十一活动',
    province: '浙江省',
    planStatus: '进行中',
    date: '2024-01-17',
    week: '周三',
    modifyTime: '2024-01-17 11:45:00',
    clockInTime: '10:00:00',
    clockOutTime: '19:00:00',
    noonClockOutTime: '13:00:00',
    noonClockInTime: '14:30:00',
    employeeNo: 'EMP004',
    salary: 700,
    incidentals: 200
  },
  {
    id: 5,
    employeeName: '钱七',
    nickName: '年终大促',
    province: '江苏省',
    planStatus: '过期',
    date: '2024-01-13',
    week: '周六',
    modifyTime: '2024-01-13 16:10:00',
    clockInTime: '08:00:00',
    clockOutTime: '17:00:00',
    noonClockOutTime: '11:30:00',
    noonClockInTime: '12:30:00',
    employeeNo: 'EMP005',
    salary: 480,
    incidentals: 80
  }
])
const columns = ref([
  {
    label: '活动标题',
    prop: 'employeeName'
  },
  {
    label: '活动开始时间',
    prop: 'nickName'
  },
  {
    label: '活动开始结束时间',
    prop: 'province'
  }
])
// 格式化计划列表单元格内容
const formatter = (row, col, value) => {
  if (col.property === 'planStatus') {
    return getPromotionActiveStatus(value)?.label
  } else if (col.property === 'date') { // 活动日期
    return parseTime(value, '{y}-{m}-{d}')
  } else if (col.property === 'week') {
    return parseTime(row['date'], '周{a}')
  } else if (col.property === 'modifyTime') {
    return parseTime(value, '{y}-{m}-{d} {h}:{i}:{s}')
  } else if (col.property === 'clockInTime' || col.property === 'clockOutTime' || col.property === 'noonClockOutTime' || col.property === 'noonClockInTime') {
    return parseTime(value)
  } else if (col.property === 'employeeName') {
    // 判断归属人名字小于 4 个字，少于几个就加几个空格
    if (value.length === 2) {
      return value + '　　' + '(' + row.employeeNo + ')'
    } else if (value.length === 3) {
      return value + '　' + '(' + row.employeeNo + ')'
    } else {
      return value + '(' + row.employeeNo + ')'
    }
  }
  // else if (col.property === 'salary' || col.property === 'incidentals') {
  //   return '¥ ' + value + ' 元'
  // }
  else {
    return value
  }
}
// 表格复选框的数据
const checkedRowList = ref([])
const handleSelectionChange = (val) => {
  checkedRowList.value = val
  delMultipleBtnDis.value = !(checkedRowList.value.length > 0)
  editMultipleBtnDis.value = !(checkedRowList.value.length > 0)
}
// 控制表格复选框是否可选
const selectableFn = (row) => {
  return checkPlanExpire(row)
}
// 计算当前行类名
const tableRowTimeOutClassName = ({ row }) => {
  // 检查计划是否能操作
  const isExpire = checkPlanExpire(row)
  if (!isExpire) {
    return 'timeout-row'
  } else {
    return ''
  }
}

/*************** 数据和分页 ***************/
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
// 任务列表
const getPlanList = async (arg) => {
  if (arg === 'resetPage') pageNum.value = 1
  const res = await getPlanListAPI({
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    queryParams: {
      activityStartDate: props.queryParams.activityDate && props.queryParams.activityDate[0],
      activityEndDate: props.queryParams.activityDate && props.queryParams.activityDate[1],
      planStatus: props.queryParams.planStatus,
      region: props.queryParams.region,
      province: props.queryParams.provinceName,
      city: props.queryParams.cityName,
      dealerId: props.queryParams.dealerId,
      orgQcId: props.queryParams.warZoneId,
      employeeId: props.queryParams.employeeId,
      storeNameLike: props.queryParams.storeName
    }
  })
  tableList.value = res.data.records
  total.value = res.data.totalRecord
}

// 归属人列表
const belongPerList = ref([])
const getBelongPerList = async () => {
  const { data } = await getChargeListAPI()
  belongPerList.value = data.map(item => {
    return {
      label: item.name,
      value: item.id,
      employeeNo: item.employeeNo,
      deptQcName: item.deptQcName,
      deptQcId: item.deptQcId
    }
  })
}
getBelongPerList()

/*************** 弹窗上传计划表格（展示） ***************/
const uploadPlanDialogVisible = ref(false)
const planTableList = ref([])
const confirmExcelUUID = ref('')
const confirmTableColumns = ref([
  {
    label: '归属人',
    prop: 'employeeName',
    width: 90,
    fixed: true
  },
  {
    label: '归属人工号',
    prop: 'employeeNo',
    width: 140
  },
  {
    label: '店铺名称',
    prop: 'storeName',
    width: 200
  },
  {
    label: '店铺编码',
    prop: 'storeCode',
    width: 160
  },
  {
    label: '活动模式',
    prop: 'pattern',
    width: 100
  },
  {
    label: '活动日期',
    prop: 'date',
    width: 180
  },
  {
    label: '上班时间',
    prop: 'clockInTime',
    width: 180
  },
  {
    label: '午休开始时间',
    prop: 'noonClockOutTime',
    width: 180
  },
  {
    label: '午休结束时间',
    prop: 'noonClockInTime',
    width: 180
  },
  {
    label: '下班时间',
    prop: 'clockOutTime',
    width: 180
  },
  // {
  //   label: '促销员薪资',
  //   prop: 'salary',
  //   width: 100
  // },
  // {
  //   label: '杂费',
  //   prop: 'incidentals',
  //   width: 100
  // },
  {
    label: "是否有促销台",
    prop: "temWlSct",
    width: 120
  },
  {
    label: "活动品项",
    prop: "prdClass",
    width: 100
  },
  // {
  //   label: '活动 ID',
  //   prop: 'id',
  //   width: 90,
  //   // fixed: true
  // },
  {
    label: '经销商 ID',
    prop: 'dealerId',
    width: 120
  },
  {
    label: '经销商',
    prop: 'dealerName',
    width: 220
  },
  {
    label: '系统名称',
    prop: 'lineName',
    width: 100
  },
  // {
  //   label: '活动状态',
  //   prop: 'planStatus',
  //   width: 100
  // },
  {
    label: '省份',
    prop: 'province',
    width: 100
  },
  {
    label: '地址',
    prop: 'addr',
    width: 200
  },
  {
    label: '战区',
    prop: 'orgName',
    width: 150
  },
  // {
  //   label: '城市',
  //   prop: 'city',
  //   width: 100
  // },
  {
    label: '创建人',
    prop: 'createBy',
    width: 100
  },
  {
    label: '最近修改人',
    prop: 'modifyBy',
    width: 100
  },
  {
    label: '最后修改时间',
    prop: 'modifyTime',
    width: 250
  }
])
const tableRowClassName = ({ row }) => {
  if (row.errorMsg) {
    return 'error-row'
  } else {
    return ''
  }
}
const formatterConfirm = (row, col, value) => {
  if (col.property === 'clockInTime' || col.property === 'clockOutTime' || col.property === 'date' || col.property === 'noonClockOutTime' || col.property === 'noonClockInTime') {
    return parseTime(value)
  } else if (col.property === 'errorMsg') {
    // 把分号替换成 \n
    return value && value.replace(/；/g, '\n')
  } else {
    return value
  }
}
// 表格上传计划确认保存
const confirmPlanBtn = async () => {
  await savePlanAPI(confirmExcelUUID.value)
  proxy.$modal.msgSuccess('保存成功')
  uploadPlanDialogVisible.value = false
  getPlanList()
}

defineExpose({
  getPlanList
})

const participantList = ref([
  {
    id: 1,
    name: '张三',
    position: '市场经理',
    department: '市场部',
    activityRole: '活动负责人',
    phone: '13800138001',
    email: 'zhangsan@company.com',
    joinTime: '2024-01-15 09:00:00',
    status: '已确认',
    notes: '张三负责活动的现场协调工作'
  },
  {
    id: 2,
    name: '李四',
    position: '销售代表',
    department: '销售部',
    activityRole: '客户接待',
    phone: '13800138002',
    email: 'lisi@company.com',
    joinTime: '2024-01-15 09:30:00',
    status: '已确认',
    notes: '李四需要提前30分钟到达现场'
  },
  {
    id: 3,
    name: '王五',
    position: '前端工程师',
    department: '技术部',
    activityRole: '技术支持',
    phone: '13800138003',
    email: 'wangwu@company.com',
    joinTime: '2024-01-15 10:00:00',
    status: '待确认',
    notes: '王五负责活动物资的准备工作'
  },
  {
    id: 4,
    name: '赵六',
    position: '产品经理',
    department: '产品部',
    activityRole: '产品展示',
    phone: '13800138004',
    email: 'zhaoliu@company.com',
    joinTime: '2024-01-15 10:30:00',
    status: '已确认',
    notes: '赵六需要携带笔记本电脑'
  },
  {
    id: 5,
    name: '钱七',
    position: '运营专员',
    department: '运营部',
    activityRole: '现场运营',
    phone: '13800138005',
    email: 'qianqi@company.com',
    joinTime: '2024-01-15 11:00:00',
    status: '已确认',
    notes: '钱七负责客户接待工作'
  },
  {
    id: 6,
    name: '孙八',
    position: 'UI设计师',
    department: '设计部',
    activityRole: '视觉设计',
    phone: '13800138006',
    email: 'sunba@company.com',
    joinTime: '2024-01-15 11:30:00',
    status: '待确认',
    notes: '孙八需要准备活动资料'
  },
  {
    id: 7,
    name: '周九',
    position: '客服专员',
    department: '客服部',
    activityRole: '客户服务',
    phone: '13800138007',
    email: 'zhoujiu@company.com',
    joinTime: '2024-01-15 12:00:00',
    status: '已确认',
    notes: '周九负责现场摄影工作'
  },
  {
    id: 8,
    name: '吴十',
    position: '会计',
    department: '财务部',
    activityRole: '费用管理',
    phone: '13800138008',
    email: 'wushi@company.com',
    joinTime: '2024-01-15 13:00:00',
    status: '已确认',
    notes: '吴十需要穿着正装出席'
  },
  {
    id: 9,
    name: '郑一',
    position: '市场专员',
    department: '市场部',
    activityRole: '现场协调',
    phone: '13800138009',
    email: 'zhengyi@company.com',
    joinTime: '2024-01-15 13:30:00',
    status: '待确认',
    notes: '郑一负责活动签到工作'
  },
  {
    id: 10,
    name: '王二',
    position: '销售经理',
    department: '销售部',
    activityRole: '销售支持',
    phone: '13800138010',
    email: 'wanger@company.com',
    joinTime: '2024-01-15 14:00:00',
    status: '已确认',
    notes: '王二需要准备演示材料'
  }
])

const orderNumberDialogVisible = ref(false)
const orderNumberForm = ref({
  shipmentNumber: '',
  notes: ''
})
const orderNumberFormRef = ref()
const currentParticipant = ref({})

// 表单验证规则
const orderNumberRules = ref({
  shipmentNumber: [
    { required: true, message: '请输入发货单号', trigger: 'blur' },
    { min: 1, max: 50, message: '发货单号长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  notes: [
    { max: 200, message: '备注信息不能超过 200 个字符', trigger: 'blur' }
  ]
})

// 填写单号函数
const fillOrderNumberFn = (row) => {
  currentParticipant.value = { ...row }
  orderNumberForm.value = {
    shipmentNumber: row.shipmentNumber || '',
    notes: row.notes || ''
  }
  orderNumberDialogVisible.value = true

  // 重置表单验证
  nextTick(() => {
    if (orderNumberFormRef.value) {
      orderNumberFormRef.value.clearValidate()
    }
  })
}

// 保存发货单号
const handleSaveOrderNumber = async () => {
  if (!orderNumberFormRef.value) return

  try {
    await orderNumberFormRef.value.validate()

    // 这里调用保存发货单号的API
    // await saveShipmentNumberAPI({
    //   participantId: currentParticipant.value.id,
    //   shipmentNumber: orderNumberForm.value.shipmentNumber,
    //   notes: orderNumberForm.value.notes
    // })

    // 更新participantList中的数据
    const index = participantList.value.findIndex(item => item.id === currentParticipant.value.id)
    if (index !== -1) {
      participantList.value[index] = {
        ...participantList.value[index],
        shipmentNumber: orderNumberForm.value.shipmentNumber,
        notes: orderNumberForm.value.notes
      }
    }

    proxy.$modal.msgSuccess('发货单号保存成功')
    orderNumberDialogVisible.value = false
  } catch (error) {
    // 验证失败，不执行保存操作
    console.log('表单验证失败:', error)
  }
}
</script>

<style scoped
  lang="scss">
  .el-row {

    /* 下载计划模版 */
    .download-a {
      margin-left: 12px;
    }

    /* 上传计划 */
    .upload-demo {
      display: inline-block;
      margin: 0 5px;
    }
  }

  .el-table {

    ::v-deep(.error-row) {
      --el-table-tr-bg-color: var(--el-color-error-light-9);
    }

    /* 灰色过期行颜色 */
    ::v-deep(.timeout-row) {
      --el-table-tr-bg-color: var(--el-timeout-row);
    }
  }

  /* 新增修改计划表单 */
  .add-edit-plan {

    /* 门店列表选择后-下面的介绍信息 */
    .info_p {
      margin: 0;
      font-size: 12px;
      color: gray;
      white-space: nowrap;
    }

    .info_error {
      color: rgb(167, 0, 0);
    }

    /* 工资和杂费输入框 */
    .el-input-number {
      width: 170px;
    }
  }
</style>