<template>
  <div class="app-container">
    <!-- 日期范围选择 -->
    <div class="date-range-section">
      <TimeRangePicker v-model="dateRangeParams" startKey="scheduleDateStart" endKey="scheduleDateEnd"
        :defaultStartTime="defaultStartTime" :defaultEndTime="defaultEndTime" @change="handleDateRangeChange"
        @quick-select="getScheduleList" />
    </div>

    <!-- 操作栏 -->
    <div class="operation-bar">
      <el-button plain type="primary" icon="el-icon-plus" @click="handleCreate">创建排班</el-button>
      <el-button plain type="info" icon="el-icon-refresh" @click="handleRefresh">刷新</el-button>
    </div>

    <el-alert type="info" title="提示：双击排班单元格可编辑排班"></el-alert>

    <!-- 排班表格 -->
    <div class="schedule-table-wrapper">
      <el-table v-loading="loading" :data="scheduleData" border stripe>
        <!-- 员工列 -->
        <el-table-column prop="employeeName" label="员工" width="120" fixed="left" />
        <!-- 操作列 -->
        <el-table-column label="操作" width="120" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="danger" @click="handleDeleteRow(scope.row)">删除整行</el-button>
          </template>
        </el-table-column>
        <!-- 动态日期列 -->
        <el-table-column v-for="date in dateList" :key="date" :label="formatDateLabel(date)" width="150" align="center">
          <template slot-scope="scope">
            <div class="schedule-cell" :class="{ 'has-data': scope.row[date], 'empty-cell': !scope.row[date] }"
              @dblclick="handleCellDoubleClick(scope.row, date)">
              <template v-if="scope.row[date]">
                <div class="shift-name" :class="getShiftTypeClass(scope.row[date].shiftType)">
                  {{ scope.row[date].shiftName }}
                </div>
                <div class="shift-time-info">
                  <span v-if="scope.row[date].shiftStartTime">{{ scope.row[date].shiftStartTime }}-{{
                    scope.row[date].shiftEndTime }}</span>
                  <span v-if="scope.row[date].shiftStartTime2" class="second-shift">
                    {{ scope.row[date].shiftStartTime2 }}-{{ scope.row[date].shiftEndTime2 }}
                  </span>
                </div>
              </template>
              <template v-else>
                <span class="empty-hint">双击排班</span>
              </template>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 创建排班弹窗 -->
    <el-dialog title="创建排班" :visible.sync="dialogVisible" width="800px">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="时间段" prop="dateRange">
          <el-date-picker v-model="form.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" value-format="yyyy-MM-dd" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="选择员工" prop="selectedEmployees">
          <EmployeeSelector v-model="form.selectedEmployees" :multiple="true" placeholder="请点击选择员工" title="选择排班员工"
            @change="handleEmployeeSelect" />
        </el-form-item>
        <el-form-item label="排班配置" v-if="form.shiftConfig.length > 0">
          <div class="shift-config">
            <div v-for="(item, index) in form.shiftConfig" :key="index" class="shift-config-item">
              <div class="employee-info">
                <el-button icon="el-icon-delete" type="default" size="mini" @click="handleDeleteEmployee(index)"></el-button>
                <el-tag type="info">{{ item.employeeName || '员工' + (index + 1) }}</el-tag>
              </div>
              <template>
                <el-select clearable v-model="item.shiftId" placeholder="选择班次" style="width: 150px;">
                  <el-option v-for="shift in shiftList" :key="shift.shiftId" :label="shift.shiftName"
                    :value="shift.shiftId" />
                </el-select>
                <div class="shift-time" v-if="item.shiftId">
                  <span class="time-label">工作时间：</span>
                  <span class="time-value">{{ getShiftTime(item.shiftId) }}</span>
                </div>

                <el-select clearable v-model="item.shiftRuleId" placeholder="选择倒班规则（不倒班则不填）" style="width: 200px;">
                  <el-option v-for="rule in shiftRuleList" :key="rule.ruleId" :label="rule.ruleName"
                    :value="rule.ruleId" />
                </el-select>
              </template>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="buttonLoading" :disabled="!canSubmit">确定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑班次弹窗 -->
    <el-dialog title="编辑班次" :visible.sync="editDialogVisible" width="400px">
      <el-form ref="editForm" :model="editForm" label-width="80px">
        <el-form-item label="班次">
          <el-select v-model="editForm.shiftId" placeholder="选择班次" style="width: 100%;">
            <el-option v-for="shift in shiftList" :key="shift.shiftId" :label="shift.shiftName"
              :value="shift.shiftId" />
          </el-select>
        </el-form-item>
        <el-form-item label="工作时间">
          <div v-if="currentShift" class="shift-detail">
            <div>
              <span class="time-label">时段一：</span>
              <span class="time-value">{{ currentShift.startTime }} - {{ currentShift.endTime }}</span>
            </div>
            <div v-if="currentShift.startTime2">
              <span class="time-label">时段二：</span>
              <span class="time-value">{{ currentShift.startTime2 }} - {{ currentShift.endTime2 }}</span>
            </div>
          </div>
          <span v-else>请选择班次</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelEdit">取消</el-button>
        <el-button type="danger"
          v-if="currentEditRow && currentEditRow[currentEditDate] && currentEditRow[currentEditDate].scheduleId"
          @click="handleDelete">删除排班</el-button>
        <el-button type="primary" @click="submitEdit" :disabled="!editForm.shiftId">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import TimeRangePicker from '@/views/wms/report/components/timeRangePicker.vue'
import EmployeeSelector from '@/components/EmployeeSelector/index.vue'
import { listAttendanceSchedule, generateenerateSchedule, updateAttendanceSchedule, addAttendanceSchedule, delAttendanceSchedule } from '@/api/wms/attendanceSchedule'
import { listShift } from '@/api/wms/attendanceShift'
import { listAttendanceShiftRule } from '@/api/wms/attendanceShiftRule'

export default {
  name: 'AttendanceSchedule',
  components: { TimeRangePicker, EmployeeSelector },
  data() {
    return {
      loading: false,
      buttonLoading: false,
      dateRangeParams: {},
      defaultStartTime: '',
      defaultEndTime: '',
      dateList: [],
      scheduleData: [],
      shiftList: [],
      shiftRuleList: [],
      dialogVisible: false,
      editDialogVisible: false,
      scheduleMode: 'single', // single: 普通排班, rotate: 倒班排班
      form: {
        dateRange: [],
        selectedEmployees: '',
        shiftConfig: []
      },
      editForm: {
        shiftId: ''
      },
      currentEditRow: null,
      currentEditDate: '',
      rules: {
        dateRange: [
          { required: true, message: '请选择时间段', trigger: 'change' }
        ],
        selectedEmployees: [
          { required: true, message: '请选择员工', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    canSubmit() {
      if (!this.form.dateRange || this.form.dateRange.length === 0) {
        return false
      }
      if (!this.form.selectedEmployees) {
        return false
      }
      if (this.form.shiftConfig.length === 0) {
        return false
      }
      if (this.scheduleMode === 'single') {
        return this.form.shiftConfig.every(item => item.shiftId)
      } else {
        return this.form.shiftConfig.every(item => item.shiftRuleId)
      }
    },
    currentShift() {
      if (!this.editForm.shiftId) {
        return null
      }
      return this.shiftList.find(s => s.shiftId === this.editForm.shiftId)
    }
  },
  created() {
    this.initDateRange()
    this.getShiftList()
    this.getShiftRuleList()
  },
  methods: {
    // 刷新排班
    handleRefresh() {
      this.getScheduleList()
    },
    // 初始化日期范围为当前月份
    initDateRange() {
      const now = new Date()
      const firstDay = new Date(now.getFullYear(), now.getMonth(), 1)
      const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0)

      this.defaultStartTime = this.formatDate(firstDay) + ' 00:00:00'
      this.defaultEndTime = this.formatDate(lastDay) + ' 23:59:59'

      this.dateRangeParams = {
        scheduleDateStart: this.defaultStartTime,
        scheduleDateEnd: this.defaultEndTime
      }

      this.generateDateList(firstDay, lastDay)
      this.getScheduleList()
    },

    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      return `${year}-${month}-${day}`
    },

    // 生成日期列表
    generateDateList(startDate, endDate) {
      this.dateList = []
      let currentDate = new Date(startDate)
      while (currentDate <= endDate) {
        this.dateList.push(this.formatDate(currentDate))
        currentDate.setDate(currentDate.getDate() + 1)
      }
    },

    handleDeleteEmployee(index) {
      this.form.shiftConfig.splice(index, 1)
    },

    // 格式化日期标签
    formatDateLabel(date) {
      const dateObj = new Date(date)
      const weekDays = ['日', '一', '二', '三', '四', '五', '六']
      const month = dateObj.getMonth() + 1
      const day = dateObj.getDate()
      const weekDay = weekDays[dateObj.getDay()]
      return `${month}月${day}日 周${weekDay}`
    },

    // 日期范围变化
    handleDateRangeChange() {
      if (this.dateRangeParams.scheduleDateStart && this.dateRangeParams.scheduleDateEnd) {
        const startDate = new Date(this.dateRangeParams.scheduleDateStart.split(' ')[0])
        const endDate = new Date(this.dateRangeParams.scheduleDateEnd.split(' ')[0])
        this.generateDateList(startDate, endDate)
        this.getScheduleList()
      }
    },

    // 获取排班列表
    getScheduleList() {
      this.loading = true
      listAttendanceSchedule(this.dateRangeParams).then(response => {
        this.scheduleData = this.transformScheduleData(response.rows || [])
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },



    // 转换排班数据
    transformScheduleData(rows) {
      const dataMap = {}

      rows.forEach(record => {
        if (!dataMap[record.userId]) {
          dataMap[record.userId] = {
            employeeName: record.employeeName,
            employeeId: record.userId
          }
        }
        if (record.workDate) {
          const dateKey = record.workDate.split(' ')[0]
          dataMap[record.userId][dateKey] = {
            scheduleId: record.scheduleId,
            shiftId: record.shiftId,
            shiftName: record.shiftName,
            shiftType: record.shiftType,
            shiftStartTime: record.shiftStartTime,
            shiftEndTime: record.shiftEndTime,
            shiftStartTime2: record.shiftStartTime2,
            shiftEndTime2: record.shiftEndTime2
          }
        }
      })

      return Object.values(dataMap)
    },

    // 获取班次列表
    getShiftList() {
      listShift().then(response => {
        this.shiftList = response.rows || []
      })
    },

    // 获取倒班规则列表
    getShiftRuleList() {
      listAttendanceShiftRule().then(response => {
        this.shiftRuleList = response.rows || []
      })
    },

    // 获取班次时间显示
    getShiftTime(shiftId) {
      const shift = this.shiftList.find(s => s.shiftId === shiftId)
      if (!shift) return ''

      const startTime = shift.startTime ? shift.startTime.substring(0, 5) : ''
      const endTime = shift.endTime ? shift.endTime.substring(0, 5) : ''

      if (shift.isCrossDay) {
        return `${startTime} - 次日${endTime}`
      }
      return `${startTime} - ${endTime}`
    },

    // 获取班次类型样式
    getShiftTypeClass(shiftType) {
      return shiftType === '夜班' ? 'night-shift' : 'day-shift'
    },

    // 双击单元格处理
    handleCellDoubleClick(row, date) {
      this.currentEditRow = row
      this.currentEditDate = date
      if (row[date]) {
        this.editForm.shiftId = row[date].shiftId
      } else {
        this.editForm.shiftId = ''
      }
      this.editDialogVisible = true
    },

    // 取消编辑
    cancelEdit() {
      this.editDialogVisible = false
      this.editForm.shiftId = ''
      this.currentEditRow = null
      this.currentEditDate = ''
    },

    // 提交编辑
    submitEdit() {
      if (!this.editForm.shiftId || !this.currentEditRow) {
        return
      }

      const shift = this.shiftList.find(s => s.shiftId === this.editForm.shiftId)
      if (!shift) {
        return
      }

      const date = this.currentEditDate
      const employeeId = this.currentEditRow.employeeId

      if (this.currentEditRow[date]) {
        updateAttendanceSchedule({
          scheduleId: this.currentEditRow[date].scheduleId,
          userId: employeeId,
          workDate: date,
          shiftId: shift.shiftId,
          shiftName: shift.shiftName,
        }).then(_ => {
          this.$message.success('修改成功')
          this.getScheduleList()
        }).catch(() => {
          this.$message.error('修改失败')
          this.getScheduleList()
        })
      } else {
        addAttendanceSchedule({
          shiftId: shift.shiftId,
          userId: employeeId,
          workDate: date,
          shiftName: shift.shiftName,
        }).then(_ => {
          this.$message.success('添加成功')
          this.getScheduleList()
        }).catch(() => {
          this.$message.error('添加失败')
          this.getScheduleList()
        })
      }

      // this.currentEditRow[date] = {
      //   scheduleId: this.currentEditRow[date]?.scheduleId,
      //   shiftId: shift.shiftId,
      //   shiftName: shift.shiftName,
      //   shiftType: shift.shiftType,
      //   shiftStartTime: shift.startTime,
      //   shiftEndTime: shift.endTime,
      //   shiftStartTime2: shift.startTime2,
      //   shiftEndTime2: shift.endTime2
      // }

      this.cancelEdit()
    },

    // 删除排班
    handleDelete() {
      const scheduleId = this.currentEditRow[this.currentEditDate]?.scheduleId
      if (!scheduleId) {
        return
      }

      this.$confirm('确定要删除该排班吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delAttendanceSchedule(scheduleId).then(() => {
          this.$message.success('删除成功')
          delete this.currentEditRow[this.currentEditDate]
          this.cancelEdit()
        }).catch(() => {
          this.$message.error('删除失败，正在重新获取数据')
          this.getScheduleList()
          this.cancelEdit()
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    // 删除整行排班
    handleDeleteRow(row) {
      const scheduleIds = []
      this.dateList.forEach(date => {
        if (row[date] && row[date].scheduleId) {
          scheduleIds.push(row[date].scheduleId)
        }
      })

      if (scheduleIds.length === 0) {
        this.$message.info('该行没有排班记录')
        return
      }

      this.$confirm(`确定要删除该员工的 ${scheduleIds.length} 条排班记录吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delAttendanceSchedule(scheduleIds.join(',')).then(() => {
          this.$message.success('删除成功')
          this.getScheduleList()
        }).catch(() => {
          this.$message.error('删除失败，正在重新获取数据')
          this.getScheduleList()
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    // 处理班次变更
    handleShiftChange(employeeId, date, shiftId) {
      if (!shiftId) {
        return
      }
      const shift = this.shiftList.find(s => s.shiftId === shiftId)
      if (!shift) {
        return
      }



      const scheduleItem = this.scheduleData.find(item => item.employeeId === employeeId)


      if (scheduleItem && scheduleItem[date]) {
        updateAttendanceSchedule({
          ...scheduleItem[date],
          shiftId: scheduleItem.shiftId
        }).then(_ => {
          this.$message.success('修改成功')
        }).catch(() => {
          this.$message.success('修改成功')
          this.getScheduleList()
        })
        scheduleItem[date].shiftId = shift.shiftId
        scheduleItem[date].shiftName = shift.shiftName
        scheduleItem[date].shiftType = shift.shiftType
        scheduleItem[date].shiftStartTime = shift.startTime
        scheduleItem[date].shiftEndTime = shift.endTime
        scheduleItem[date].shiftStartTime2 = shift.startTime2
        scheduleItem[date].shiftEndTime2 = shift.endTime2
      } else if (scheduleItem) {
        scheduleItem[date] = {
          shiftId: shift.shiftId,
          shiftName: shift.shiftName,
          shiftType: shift.shiftType,
          shiftStartTime: shift.startTime,
          shiftEndTime: shift.endTime,
          shiftStartTime2: shift.startTime2,
          shiftEndTime2: shift.endTime2
        }
      }
    },

    // 创建排班
    handleCreate() {
      this.reset()
      this.dialogVisible = true
    },

    // 重置表单
    reset() {
      this.scheduleMode = 'single'
      this.form = {
        dateRange: [],
        selectedEmployees: '',
        shiftConfig: []
      }
      this.resetForm('form')
    },

    // 员工选择变化时自动生成配置项
    handleEmployeeSelect(employees) {
      if (!employees || employees.length === 0) {
        this.form.shiftConfig = []
        return
      }

      // 为每个选中的员工生成配置项
      if (this.scheduleMode === 'single') {
        this.form.shiftConfig = employees.map(employee => ({
          employeeId: employee.infoId,
          employeeName: employee.name,
          shiftId: null
        }))
      } else {
        this.form.shiftConfig = employees.map(employee => ({
          employeeId: employee.infoId,
          employeeName: employee.name,
          shiftRuleId: null
        }))
      }
    },

    // 排班模式切换
    handleScheduleModeChange() {
      // 模式切换时重新生成配置项
      if (this.form.selectedEmployees && this.form.selectedEmployees.length > 0) {
        this.handleEmployeeSelect(this.form.selectedEmployees)
      }
    },

    // 提交表单
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.loading = true;
          this.buttonLoading = true;
          // 构建提交数据
          const list = []
          for (const item of this.form.shiftConfig) {
            const payload = {
              userId: item.employeeId,
              shiftId: item.shiftId,
              ruleId: item.shiftRuleId,
              startDate: this.dateRangeParams.scheduleDateStart.split(' ')[0],
              endDate: this.dateRangeParams.scheduleDateEnd.split(' ')[0]
            }
            list.push(payload)
          }

          // 调用API
          generateenerateSchedule(list).then(response => {
            this.$modal.msgSuccess('生成成功')
            this.dialogVisible = false
            this.loading = false;
            this.buttonLoading = false;
            this.getScheduleList()
          })
        }
      })
    },

    // 取消
    cancel() {
      this.dialogVisible = false
      this.reset()
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.date-range-section {
  margin-bottom: 20px;
}

.operation-bar {
  margin-bottom: 20px;
}

.schedule-table-wrapper {
  overflow-x: auto;
}

.schedule-cell {
  padding: 4px;
  min-height: 60px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.schedule-cell:hover {
  background-color: #f5f7fa;
}

.has-data {
  padding: 8px 4px;
}

.empty-cell {
  display: flex;
  align-items: center;
  justify-content: center;
}

.empty-hint {
  font-size: 12px;
  color: #c0c4cc;
}

.shift-info {
  text-align: center;
}

.shift-name {
  display: inline-block;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 11px;
  color: #fff;
  margin-bottom: 2px;
}

.day-shift {
  background-color: #67c23a;
}

.night-shift {
  background-color: #409eff;
}

.shift-time-info {
  font-size: 10px;
  color: #606266;
  line-height: 1.4;
}

.second-shift {
  display: block;
  margin-top: 2px;
}

.shift-config {
  width: 100%;
}

.shift-config-item {
  margin-bottom: 12px;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.employee-info {
  min-width: 100px;
}

.shift-time {
  flex: 1;
  margin-left: 12px;
}

.time-label {
  font-size: 12px;
  color: #909399;
}

.time-value {
  font-size: 12px;
  color: #606266;
}
</style>
