<template>
  <div class="app-container">
    <div class="container">
      <!-- 查询表单 -->
      <el-form :model="queryParams"
        inline
        label-width="68px">
        <el-row>
          <el-form-item label="选择日期"
            prop="activityDate">
            <el-date-picker v-model="queryParams.activityDate"
              type="daterange"
              clearable
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :shortcuts="pickerOptions"
              @change="getPlanList" />
          </el-form-item>
          <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-row>
          <el-form-item label="区域查询"
            prop="region">
            <el-radio-group v-model="queryParams.region"
              @change="regionChange">
              <el-radio-button label="全国"
                value="全国" />
              <el-radio-button label="省"
                value="省" />
              <el-radio-button label="省-市"
                value="省-市" />
            </el-radio-group>
          </el-form-item>
          <el-form-item label="省份"
            prop="province"
            v-show="queryParams.region !== '全国'">
            <el-select v-model="queryParams.provinceId"
              placeholder="请选择省"
              @change="getProCity"
              filterable
              clearable>
              <el-option v-for="item in provinceList"
                :key="item.value"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="城市"
            prop="city"
            v-show="queryParams.region === '省-市'">
            <el-select v-model="queryParams.cityId"
              placeholder="请选择市"
              @change="getPlanList"
              filterable
              clearable>
              <el-option v-for="item in cityList"
                :key="item.value"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="经销商"
            prop="zone">
            <el-select v-model="queryParams.zoneId"
              placeholder="搜索经销商"
              @change="getPlanList"
              filterable
              remote
              :remote-method="remoteMethod"
              clearable>
              <el-option v-for="item in zoneList"
                :key="item.value"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="战区"
            prop="warzone">
            <el-select v-model="queryParams.warzoneId"
              placeholder="请选择战区"
              filterable
              clearable
              :disabled="cityManagerPrivilege"
              @change="getPlanList">
              <el-option v-for="item in warZoneList"
                :key="item.value"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="归属人"
            prop="manager">
            <el-select v-model="queryParams.employeeId"
              placeholder="请选择归属人(搜索)"
              filterable
              clearable
              :disabled="cityManagerPrivilege"
              @change="getPlanList">
              <el-option v-for="item in managerList"
                :key="item.value"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="终端名"
            prop="store">
            <el-input v-model="queryParams.storeName"
              clearable
              placeholder="请输入门店名称"
              @input="getPlanList" />
          </el-form-item>
        </el-row>
      </el-form>
      <el-row :gutter="10"
        class="mb8"
        justify="space-between">
        <el-col :span="1.5">
          <el-button type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete">删除</el-button>
          <el-button type="success"
            plain
            icon="Plus"
            @click="handleAdd">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-upload class="upload-demo"
            action="#"
            accept=".xls,.xlsx"
            :http-request="uploadFile"
            :show-file-list="false">
            <template #trigger>
              <el-button type="primary">{{ cityManagerPrivilege ? '城市经理' : '职能角色' }}-新增计划上传</el-button>
            </template>
          </el-upload>
          <el-upload class="upload-demo"
            action="#"
            accept=".xls,.xlsx"
            :http-request="uploadChangeFile"
            :show-file-list="false">
            <template #trigger>
              <el-button type="primary">修改计划上传</el-button>
            </template>
          </el-upload>
        </el-col>
      </el-row>
      <!-- 表格列表 -->
      <el-table :data="tableList"
        :cell-style="{ 'word-wrap': 'break-word', 'white-space': 'normal' }"
        border
        style="width: 100%"
        show-overflow-tooltip
        @selection-change="handleSelectionChange"
        :row-class-name="tableRowTimeOutClassName">
        <el-table-column type="selection"
          width="55"
          :selectable="selectableFn">
        </el-table-column>
        <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" />
        <el-table-column label="操作"
          width="150"
          fixed="right">
          <template #default="scope">
            <el-button type="success"
              link
              :disabled="!selectableFn(scope.row)"
              @click="editFn(scope.row)">
              编辑
            </el-button>
            <el-button type="danger"
              link
              :disabled="!selectableFn(scope.row)"
              @click="deletePlane(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getPlanList" />
      <!-- 弹窗确认上传计划 -->
      <el-dialog title="上传计划"
        v-model="dialogVisible"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        width="80%">
        <div>
          <!-- 计划表格 -->
          <el-table :data="planTableList"
            :cell-style="{ 'word-wrap': 'break-word', 'white-space': 'normal' }"
            border
            style="width: 100%"
            show-overflow-tooltip
            :row-class-name="tableRowClassName">
            <el-table-column v-for="item in confirmTableColumns"
              :key="item.label"
              :prop="item.prop"
              :label="item.label"
              :width="item.width"
              :formatter="formatterConfirm" />
          </el-table>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <p style="color: red; float: left;">如果表格有红色行，请根据错误提示修改本地表格重新上传</p>
            <el-button @click="dialogVisible = false">取消上传</el-button>
            <el-button type="primary"
              :disabled="!confirmExcelUUID"
              @click="confirmPlanBtn">
              确定保存
            </el-button>
          </div>
        </template>
      </el-dialog>
      <!-- 新增/修改计划 -->
      <el-dialog :title="(addOrEditPlanForm.id ? '修改' : '新增') + '计划'"
        v-model="addOrEditPlanVisible"
        width="60%">
        <!-- 表单 -->
        <el-form :model="addOrEditPlanForm"
          label-width="150px"
          :rules="addOrEditPlanFormRules"
          ref="addOrEditPlanRef"
          inline>
          <el-row>
            <el-col :span="12">
              <!-- 门店列表 -->
              <el-form-item label="门店列表"
                prop="storeCode">
                <el-select v-model="addOrEditPlanForm.storeCode"
                  placeholder="请选择门店"
                  filterable
                  clearable
                  style="width: 95%"
                  @change="selStoreInfo"
                  remote
                  :remote-method="remoteStoreMethod"
                  :disabled="!!addOrEditPlanForm.id">
                  <el-option v-for="item in storeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value" />
                </el-select>
                <p class="info_p"
                  :class="{ info_error: isInfoError }">{{ selecteStoreInfo }}
                </p>
                <div>
                  <a class="link"
                    v-show="isInfoError"
                    target="_blank"
                    href="https://cloud.region2.qince.com/sysapp/react/web/main.html#/home">跳转勤策系统</a>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <!-- 活动日期 -->
              <el-form-item label="活动日期"
                prop="date">
                <el-date-picker v-model="addOrEditPlanForm.date"
                  :clearable="false"
                  start-placeholder="活动日期"
                  value-format="YYYY-MM-DDTHH:mm:ss"
                  :disabled-date="disabledDateFn"
                  :disabled="!!addOrEditPlanForm.id" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <!-- 活动模式 -->
            <el-col :span="12">
              <el-form-item label="活动模式"
                prop="pattern">
                <el-select v-model="addOrEditPlanForm.pattern"
                  placeholder="请选择活动模式"
                  filterable
                  clearable
                  style="width: 95%"
                  @change="selPattern">
                  <el-option v-for="item in activityModeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <!-- 归属人 -->
              <el-form-item label="归属人"
                prop="employeeNo">
                <el-select v-model="addOrEditPlanForm.employeeNo"
                  placeholder="请选择归属人"
                  filterable
                  clearable
                  style="width: 95%"
                  :disabled="cityManagerPrivilege || !!addOrEditPlanForm.id"
                  @change="selEmployee">
                  <el-option v-for="item in managerList"
                    :key="item.employeeNo"
                    :label="item.label"
                    :value="item.employeeNo" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <!-- 上班打卡时间 -->
              <el-form-item label="上班打卡时间"
                prop="clockInTime">
                <el-time-picker v-model="addOrEditPlanForm.clockInTime"
                  placeholder="选择时间"
                  format="HH:mm"
                  value-format="YYYY-MM-DDTHH:mm:ss"
                  style="width: 95%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <!-- 下班打卡时间 -->
              <el-form-item label="下班打卡时间"
                prop="clockOutTime">
                <el-time-picker v-model="addOrEditPlanForm.clockOutTime"
                  placeholder="选择时间"
                  format="HH:mm"
                  value-format="YYYY-MM-DDTHH:mm:ss"
                  style="width: 95%"
                  :disabled="!addOrEditPlanForm.clockInTime"
                  :disabled-hours="disabledHours"
                  :disabled-minutes="disabledMinutes"
                  :disabled-seconds="disabledSeconds" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <!-- 工资 -->
              <el-form-item label="工资"
                prop="salary">
                <el-input-number v-model="addOrEditPlanForm.salary"
                  style="width: 80%"
                  placeholder="请输入工资" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <!-- 杂费 -->
              <el-form-item label="杂费"
                prop="incidentals">
                <el-input-number v-model="addOrEditPlanForm.incidentals"
                  style="width: 80%"
                  placeholder="请输入杂费" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="default"
              @click="addOrEditPlanVisible = false">
              取消
            </el-button>
            <el-button type="primary"
              @click="handleAddOrEditPlan"
              :disabled="isInfoError">
              确定保存
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { getPlanListAPI, uploadFileToOSSAPI, addPlanAPI, savePlanAPI, deletePlanAPI, addPlanByRoleAPI, getProCityAPI, getDealerListAPI, getWarZoneListAPI, getChargeListAPI, addPlanByWebAPI, updatePlanByWebAPI, getPlanStoreListAPI, updatePlanAPI } from '@/api'
import { useDatePickerOptions } from '@/hooks'
import { v4 as uuidv4 } from 'uuid';
import store from '@/store'
import { parseTime } from '@/utils'
import { ElMessage, ElMessageBox } from 'element-plus';

// 城市经理状态为 true
const cityManagerPrivilege = computed(() => {
  return store.state?.value?.user?.userInfo?.privilegeId == 1
})

const { recentPickerOptions: pickerOptions, thisYearDate } = useDatePickerOptions(0)
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  activityDate: [],
  region: '全国',
})
const taskStatusList = ref([
  {
    label: '执行',
    value: 'EXECUTION'
  },
  {
    label: '未执行',
    value: 'NOT_EXECUTION'
  }
])
// 查询参数-区域查询
const provinceList = ref([])
const cityList = ref([])
const getProCity = async () => {
  const { data } = await getProCityAPI(queryParams)
  if (queryParams.provinceId) {
    queryParams.cityId = undefined
    cityList.value = data.map(item => ({
      label: item.name,
      value: item.num
    }))
  } else {
    queryParams.cityId = undefined
    cityList.value = []
    provinceList.value = data.map(item => ({
      label: item.name,
      value: item.num
    }))
  }
  getPlanList()
}
getProCity()

// 查询经销商列表
const zoneList = ref([])
const getDealerList = async () => {
  const { data } = await getDealerListAPI(queryParams)
  zoneList.value = data.map(item => {
    return {
      label: item.dealerName,
      value: item.dealerId
    }
  })
}
// 经销商远程搜索
const remoteMethod = (query) => {
  queryParams.dealerName = query
  getDealerList()
}
getDealerList()
// 查询战区列表
const warZoneList = ref([])
const getWarZoneList = async () => {
  const { data } = await getWarZoneListAPI()
  warZoneList.value = data.map(item => {
    return {
      label: item.orgName,
      value: item.qcId
    }
  })
}
getWarZoneList()
// 查询归属人列表
const managerList = ref([])
const getChargeList = async () => {
  const { data } = await getChargeListAPI()
  managerList.value = data.map(item => {
    return {
      label: item.name,
      value: item.id,
      employeeNo: item.employeeNo,
      deptQcName: item.deptQcName,
      deptQcId: item.deptQcId
    }
  })
}
getChargeList()

// 区域查询切换
const regionChange = (val) => {
  if (val === '全国') {
    queryParams.provinceId = undefined
    queryParams.cityId = undefined
  } else if (val === '省') {
    queryParams.cityId = undefined
  } else if (val === '省-市') {
    cityList.value = []
    getProCity()
  }
  getPlanList()
}

// 等待被删除的数据
const deleteList = ref([])

// 全选
const handleSelectionChange = (val) => {
  deleteList.value = val
  multiple.value = !(deleteList.value.length > 0)
}

// 任务列表
const tableList = ref([])
const total = ref(0)
const multiple = ref(true)
const columns = ref([
  {
    label: '活动 ID',
    prop: 'id',
    width: 90,
    // fixed: true
  },
  {
    label: '归属人',
    prop: 'employeeName',
    width: 90,
    fixed: true
  },
  {
    label: '归属人工号',
    prop: 'employeeNo',
    width: 140
  },
  {
    label: '经销商 ID',
    prop: 'dealerId',
    width: 120
  },
  {
    label: '经销商',
    prop: 'dealerName',
    width: 220
  },
  {
    label: '系统名称',
    prop: 'lineName',
    width: 100
  },
  {
    label: '店铺编码',
    prop: 'storeCode',
    width: 160
  },
  {
    label: '店铺名称',
    prop: 'storeName',
    width: 200
  },
  {
    label: '活动日期',
    prop: 'date',
    width: 180
  },
  {
    label: '活动状态',
    prop: 'planStatus',
    width: 100
  },
  {
    label: '活动模式',
    prop: 'pattern',
    width: 100
  },
  {
    label: '省份',
    prop: 'province',
    width: 100
  },
  {
    label: '地址',
    prop: 'addr',
    width: 200
  },
  {
    label: '上班时间',
    prop: 'clockInTime',
    width: 180
  },
  {
    label: '下班时间',
    prop: 'clockOutTime',
    width: 180
  },
  {
    label: '促销员薪资',
    prop: 'salary',
    width: 100
  },
  {
    label: '杂费',
    prop: 'incidentals',
    width: 100
  },
  {
    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 getPlanList = async () => {
  // 后台省市不要 id，自己查个名字给后台
  queryParams.province = provinceList.value.find(item => item.value === queryParams.provinceId)?.label
  queryParams.city = cityList.value.find(item => item.value === queryParams.cityId)?.label
  // 城市经理查自己，职能角色查所有（需要的是促销系统 id）
  if (cityManagerPrivilege.value) {
    // 城市经理 
    await getChargeList()
    queryParams.employeeId = managerList.value.find(item => item.employeeNo === store.state.value.user.userInfo.userName)?.value
    // 先从归属人查询当前登录用户的战区 ID
    queryParams.warzoneId = managerList.value.find(item => item.employeeNo === store.state.value.user.userInfo.userName)?.deptQcId
  }
  const res = await getPlanListAPI(queryParams)
  tableList.value = res.data.records
  total.value = res.data.totalRecord
}
getPlanList()
const formatter = (row, col, value) => {
  if (col.property === 'planStatus') {
    return value == 0 ? '未执行' : '执行'
  } else if (col.property === 'modifyTime' || col.property === 'date') {
    return parseTime(value, '{y}-{m}-{d}')
  } else if (col.property === 'clockInTime' || col.property === 'clockOutTime') {
    return parseTime(value)
  } else {
    return value
  }
}
// 判断计划是否过期
const checkPlanExpire = (row) => {
  const date = new Date()
  const targetDate = new Date(`${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} 10:00:00`)
  const rowDate = new Date(row.date)
  if (rowDate < targetDate || row.planStatus === 1) {
    // 过期/已经开始不可以操作
    return false
  } else {
    return true
  }
}
// 计划是否可选
const selectableFn = (row) => {
  return checkPlanExpire(row)
}
// 计划是否已经过期，不可以操作
const tableRowTimeOutClassName = ({ row }) => {
  const isExpire = checkPlanExpire(row)
  if (!isExpire) {
    return 'timeout-row'
  } else {
    return ''
  }
}

// 上传计划表格
const uploadFile = async (file) => {

  // 拼接当前月数为文件夹名
  const date = new Date()
  const month = date.getMonth() + 1
  const excelUrl = await uploadFileToOSSAPI(`planExcel/${date.getFullYear()}-${month}/${store.state.value.user.userInfo.userName}/${uuidv4()}.xlsx`, file.file)
  const targetAPI = store.state.value.user.userInfo.privilegeId === 1 ? addPlanAPI : addPlanByRoleAPI
  const res = await targetAPI({
    "excelUrl": excelUrl,
    "employeeNo": store.state.value.user.userInfo.userName
  })
  planTableList.value = res.data.table
  confirmExcelUUID.value = res.data.uuid
  dialogVisible.value = true

  return true
}

// 确认计划
const planTableList = ref([])
const dialogVisible = ref(false)
const confirmExcelUUID = ref('')
const confirmTableColumns = [
  {
    label: '活动 ID',
    prop: 'id',
    width: 90,
    // fixed: true
  },
  {
    label: '归属人',
    prop: 'employeeName',
    width: 90,
    fixed: true
  },
  {
    label: '归属人工号',
    prop: 'employeeNo',
    width: 140
  },
  {
    label: '经销商 ID',
    prop: 'dealerId',
    width: 120
  },
  {
    label: '经销商',
    prop: 'dealerName',
    width: 220
  },
  {
    label: '系统名称',
    prop: 'lineName',
    width: 100
  },
  {
    label: '店铺编码',
    prop: 'storeCode',
    width: 160
  },
  {
    label: '店铺名称',
    prop: 'storeName',
    width: 200
  },
  {
    label: '活动日期',
    prop: 'date',
    width: 180
  },
  {
    label: '活动状态',
    prop: 'planStatus',
    width: 100
  },
  {
    label: '活动模式',
    prop: 'pattern',
    width: 100
  },
  {
    label: '省份',
    prop: 'province',
    width: 100
  },
  {
    label: '地址',
    prop: 'addr',
    width: 200
  },
  {
    label: '上班时间',
    prop: 'clockInTime',
    width: 180
  },
  {
    label: '下班时间',
    prop: 'clockOutTime',
    width: 180
  },
  {
    label: '促销员薪资',
    prop: 'salary',
    width: 100
  },
  {
    label: '杂费',
    prop: 'incidentals',
    width: 100
  },
  {
    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
  },
  {
    label: '错误消息',
    prop: 'errorMsg',
    width: 450
  }
]
const tableRowClassName = ({ row, rowIndex }) => {
  if (row.errorMsg) {
    return 'error-row'
  } else {
    return ''
  }
}
const formatterConfirm = (row, col, value) => {
  if (col.property === 'clockInTime' || col.property === 'clockOutTime' || col.property === 'date') {
    return parseTime(value)
  } else {
    return value
  }
}
const addOrEditPlanRef = ref(null)
// 表格上传计划确认保存
const confirmPlanBtn = async () => {
  await savePlanAPI(confirmExcelUUID.value)
  ElMessage.success('保存成功')
  dialogVisible.value = false
  getPlanList()
}

// 新增/编辑计划
const addOrEditPlanVisible = ref(false)
const addOrEditPlanForm = ref({
})
// 重置表单
const resetAddOrEditPlanForm = () => {
  addOrEditPlanForm.value = {}
  selecteStoreInfo.value = ''
  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'
    }
  ],
  clockInTime: [
    {
      required: true,
      message: '请选择上班打卡时间',
      trigger: 'blur'
    }
  ],
  clockOutTime: [
    {
      required: true,
      message: '请选择下班打卡时间',
      trigger: 'blur'
    }
  ],
  salary: [
    {
      required: true,
      message: '请输入工资',
      trigger: 'blur'
    }
  ],
  incidentals: [
    {
      required: true,
      message: '请输入杂费',
      trigger: 'blur'
    }
  ]
})
// 定义禁用日期的函数
const disabledDateFn = (time) => {
  // 判断日期不在某个区间的就禁用
  // 职能角色今日到次月最后一天
  if (store.state.value.user.userInfo.privilegeId === 2) {
    const now = new Date();
    const start = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    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 nextMonth = now.getMonth() + 1;
    const start = new Date(now.getFullYear(), nextMonth, 1);
    const end = new Date(now.getFullYear(), nextMonth + 1, 0);
    return time.getTime() < start.getTime() || time.getTime() > end.getTime();
  }
}
const handleAdd = () => {
  resetAddOrEditPlanForm()
  addOrEditPlanVisible.value = true
}
const activityModeList = ref([
  {
    label: '单点CP',
    value: '单点CP'
  },
  {
    label: '常规MINI秀',
    value: '常规MINI秀'
  },
  {
    label: '校园活动',
    value: '校园活动'
  }
])
// 根据选择的开始时间，禁用小时分钟秒只能选择之后的时间
const makeRange = (start, end) => {
  const result = []
  for (let i = start; i <= end; i++) {
    result.push(i)
  }
  return result
}
const disabledHours = (h) => {
  // 根据上班时间选择的结果，禁用小时
  const date = new Date(addOrEditPlanForm.value.clockInTime)
  return makeRange(0, date.getHours() - 1);
}
const disabledMinutes = (h, m) => {
  // 如果小时大于上班打卡时间小时，则不限制分钟
  const inDate = new Date(addOrEditPlanForm.value.clockInTime)
  if (h > inDate.getHours()) {
    return makeRange(0, -1);
  } else {
    const date = new Date(addOrEditPlanForm.value.clockInTime)
    return makeRange(0, date.getMinutes() - 1);
  }
}
const disabledSeconds = (h, m, s) => {
  const date = new Date(addOrEditPlanForm.value.clockInTime)
  return makeRange(0, date.getSeconds() - 1);
}

// 编辑计划
const editFn = (row) => {
  addOrEditPlanForm.value = { ...row }
  addOrEditPlanVisible.value = true
}

// 保存新增/编辑计划
const handleAddOrEditPlan = async () => {
  // 表单校验
  await addOrEditPlanRef.value.validate()
  addOrEditPlanForm.value.operNo = store.state.value.user.userInfo.userName
  addOrEditPlanForm.value.operName = store.state.value.user.userInfo.nickName
  addOrEditPlanForm.value.operId = store.state.value.user.userInfo.userId
  if (addOrEditPlanForm.value.id) {
    await updatePlanByWebAPI(addOrEditPlanForm.value)
  } else {
    await addPlanByWebAPI(addOrEditPlanForm.value)
  }

  ElMessage.success('保存成功')
  addOrEditPlanVisible.value = false
  getPlanList()
}

// 删除计划
const deletePlane = (row) => {
  deleteList.value = [row]
  handleDelete()
}
const handleDelete = async () => {
  // 弹出确认框
  await ElMessageBox.confirm('确认删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  await deletePlanAPI({
    planIds: deleteList.value.map(o => o.id),
    employeeNo: store.state.value.user.userInfo.userName
  })
  ElMessage.success('删除成功')
  getPlanList()
}

// 获取门店列表
const storeList = ref([])
const allStoreList = ref([])
const selecteStoreInfo = ref('')
const isInfoError = ref(false)
const getStoreList = async () => {
  const { data } = await getPlanStoreListAPI({
    storeName: addOrEditPlanForm.value.storeName
  })
  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 = ''
  }
  // 清除表单验证提示
  addOrEditPlanRef.value.clearValidate('storeCode');
}
// 门店搜索
const remoteStoreMethod = (query) => {
  addOrEditPlanForm.value.storeName = query
  getStoreList()
}

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

// 批量表格修改计划
const uploadChangeFile = async (file) => {
  // 拼接当前月数为文件夹名
  const date = new Date()
  const month = date.getMonth() + 1
  const excelUrl = await uploadFileToOSSAPI(`planExcel/${date.getFullYear()}-${month}/${store.state.value.user.userInfo.userName}/${uuidv4()}.xlsx`, file.file)
  const res = await updatePlanAPI({
    "excelUrl": excelUrl,
    "employeeNo": store.state.value.user.userInfo.userName
  })
  planTableList.value = res.data.table
  confirmExcelUUID.value = res.data.uuid
  dialogVisible.value = true

  return true
}
</script>

<style scoped
  lang="scss">
  .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);
    }
  }

  .upload-demo {
    display: inline-block;
    margin: 0 5px;
  }


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

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

  .link {
    color: #409eff;
  }
</style>