<template>
  <div class="app-container">
    <div class="container">
      <!-- 查询表单 -->
      <el-form :model="queryParams"
        inline
        label-width="68px">
        <el-form-item label="选择日期"
          prop="date">
          <el-date-picker v-model="queryParams.activityDate"
            type="daterange"
            :clearable="false"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="pickerOptions"
            @change="getPlanList" />
        </el-form-item>
        <el-form-item label="上传计划">
          <el-upload class="upload-demo"
            action="#"
            accept=".xls,.xlsx"
            :http-request="uploadFile"
            :show-file-list="false">
            <template #trigger>
              <el-button type="primary">选择 Excel</el-button>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <el-row :gutter="10"
        class="mb8">
        <el-col :span="1.5">
          <el-button type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:user:remove']">删除</el-button>
        </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="操作">
          <template #default="scope">
            <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>
    </div>
  </div>
</template>

<script setup>
import { getPlanListAPI, uploadFileToOSSAPI, addPlanAPI, savePlanAPI, deletePlanAPI, addPlanByRoleAPI } from '@/api'
import { useDatePickerOptions } from '@/hooks'
import { v4 as uuidv4 } from 'uuid';
import store from '@/store'
import { parseTime } from '@/utils'
import { ElMessage } from 'element-plus';

const { recentPickerOptions: pickerOptions, thisYearDate } = useDatePickerOptions(0)
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  activityDate: thisYearDate
})
// 等待被删除的数据
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,
    fixed: true
  },
  {
    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: 'modifyTime',
    width: 250
  },
  {
    label: '上传文件名称',
    prop: '',
    width: 150
  }
])
const getPlanList = async () => {
  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' || 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) {
    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 = [
  ...columns.value,
  {
    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 confirmPlanBtn = async () => {
  await savePlanAPI(confirmExcelUUID.value)
  ElMessage.success('保存成功')
  dialogVisible.value = false
  getPlanList()
}

// 删除计划
const deletePlane = (row) => {
  deleteList.value = [row]
  handleDelete()
}
const handleDelete = async () => {
  await deletePlanAPI({
    ids: deleteList.value.map(o => o.id),
    employeeNo: store.state.value.user.userInfo.userName
  })
  ElMessage.success('删除成功')
  getPlanList()
}
</script>

<style scoped
  lang="scss">
  .el-table {
    opacity: 1;
    
    ::v-deep(.error-row) {
      --el-table-tr-bg-color: var(--el-color-error-light-9);
    }
    /* 灰色过期行颜色 */
    ::v-deep(.timeout-row) {
      --el-table-tr-bg-color: #e2e2e29e;
    }
  }

</style>