<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="部门" prop="departmentName">
        <el-input v-model="queryParams.departmentName" placeholder="请输入部门名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="值班日期" prop="dutyDate">
        <el-date-picker clearable v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 240px">
          <el-option label="停用" :value="0" />
          <el-option label="正常" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['attendance:shiftScheduling:add']">生成排班</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['attendance:shiftScheduling:remove']">删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['attendance:shiftScheduling:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Upload" @click="handleImport"
          v-hasPermi="['attendance:shiftScheduling:import']">导入</el-button>
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="shiftSchedulingList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="部门" align="center" prop="departmentName" />
      <el-table-column label="值班日期" align="center" prop="dutyDate" />
      <el-table-column label="开始时间" align="center" prop="startTime">
        <template #default="scope">
          {{ scope.row.startTime ? scope.row.startTime.split(' ')[0] : '' }}
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime">
        <template #default="scope">
          {{ scope.row.endTime ? scope.row.endTime.split(' ')[0] : '' }}
        </template>
      </el-table-column>
      <el-table-column label="是否跨天" align="center" prop="crossDay">
        <template #default="scope">
          {{ scope.row.crossDay == '1' ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          {{ scope.row.status == '1' ? '正常' : '停用' }}
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['attendance:shiftScheduling:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['attendance:shiftScheduling:remove']">删除</el-button>
        </template>
      </el-table-column> -->
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改排班对话框 -->
    <el-dialog :title="title" v-model="open" :width="1000" append-to-body>
      <el-form ref="shiftSchedulingRef" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="9">
            <el-form-item label="开始时间" prop="startDate">
              <el-date-picker clearable style="width:100%" v-model="form.startDate" type="date" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" placeholder="请选择开始时间" @change="calculateDuration">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker clearable style="width:100%" v-model="form.endTime" type="date" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" placeholder="请选择结束时间" @change="calculateDuration">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="display: flex;align-items: center;height: 33px;">

            共<el-input v-model="form.daysToGenerate" placeholder="自动计算" disabled readonly
              style="width:100%;padding-left:10px;padding-right:10px;" />天

          </el-col>
        </el-row>



        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始大队" prop="startDeptId">
              <el-select v-model="form.startDeptId" placeholder="请选择开始大队" style="width:100%">
                <el-option v-for="dept in departmentList" :key="dept.deptId" :label="dept.deptName"
                  :value="dept.deptId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="大队顺序" prop="deptIds">
              <el-select v-model="form.deptIds" multiple placeholder="请选择大队顺序" style="width:100%">
                <el-option v-for="dept in departmentList" :key="dept.deptId" :label="dept.deptName"
                  :value="dept.deptId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="班次安排" prop="shifts">
          <div style="display: flex; align-items: center; width:100%">
            <el-input-number v-model="form.shiftStart" :min="0" :max="24" controls-position="right" style="width:120px"
              :default-value="9" />
            <span style="margin: 0 10px; color: #666;">-</span>
            <el-input-number v-model="form.shiftEnd" :min="0" :max="24" controls-position="right" style="width:120px"
              :default-value="9" />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="ShiftScheduling">
import { listShiftScheduling, generateUnifiedSchedule, delSimpleDutySchedule } from "@/api/attendance/shiftScheduling"
import { listDept } from "@/api/system/dept"
import useUserStore from '@/store/modules/user'

const { proxy } = getCurrentInstance()
const userStore = useUserStore()



const shiftSchedulingList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const dateRange = ref([])
const departmentList = ref([])

import { getToken } from "@/utils/auth"


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    departmentName: null,
    dutyDate: null,
    status: null
  },
  rules: {
    startDate: [
      { required: true, message: "开始时间不能为空", trigger: "blur" }
    ],
    endTime: [
      { required: true, message: "结束时间不能为空", trigger: "blur" }
    ],
    startDeptId: [
      { required: true, message: "开始大队不能为空", trigger: "change" }
    ],
    deptIds: [
      { required: true, message: "大队顺序不能为空", trigger: "change" }
    ],
    shifts: [
      {
        required: true,
        validator: (rule, value, callback) => {
          if (!form.value.shiftStart && !form.value.shiftEnd) {
            callback(new Error("班次安排不能为空"))
          } else {
            callback()
          }
        },
        trigger: "change"
      }
    ],

  }
})

const upload = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/attendance/shiftScheduling/importData"
})

const { queryParams, form, rules } = toRefs(data)

/** 查询排班列表 */
function getList() {
  loading.value = true
  let params = {
    ...queryParams.value,
    startTime: dateRange.value && dateRange.value[0],
    endTime: dateRange.value && dateRange.value[1]
  }

  listShiftScheduling(params).then(response => {
    shiftSchedulingList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 计算持续时间
const calculateDuration = () => {
  if (form.value.startDate && form.value.endTime) {
    const start = new Date(form.value.startDate)
    const end = new Date(form.value.endTime)
    const diffTime = Math.abs(end - start)
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
    form.value.daysToGenerate = diffDays

    // 判断是否跨天
    form.value.crossDay = start.getDate() !== end.getDate() ? '1' : '0'
  }
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    startDate: null,
    endTime: null,
    daysToGenerate: null,
    crossDay: '0',
    startDeptId: null,
    deptIds: [],
    shifts: null,
    shiftStart: 9,
    shiftEnd: 9
  }
  proxy.resetForm("shiftSchedulingRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = []
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "生成排班"
}


/** 提交按钮 */
function submitForm() {
  proxy.$refs["shiftSchedulingRef"].validate(async valid => {
    if (valid) {
      const submitData = await prepareFormData()



      if (form.value.id != null) {
        updateShiftScheduling(submitData).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        // 使用生成统一排班接口
        generateUnifiedSchedule(submitData).then(response => {
          proxy.$modal.msgSuccess("排班生成成功")
          open.value = false
          getList()
        }).catch(error => {
          console.error('生成排班失败:', error)
          proxy.$modal.msgError("排班生成失败")
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除排班数据项？').then(function () {

    return delSimpleDutySchedule(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}



// 获取大队列表
const fetchDepartmentList = async () => {
  try {
    const response = await listDept()
    departmentList.value = (response.data || []).filter(item => item.deptType === 'BRIGADE')
  } catch (error) {
    console.error('获取大队列表失败:', error)
    departmentList.value = []
  }
}

// 提交表单前的数据处理
const prepareFormData = async () => {
  const formData = { ...form.value }

  // 获取当前登录用户的stationId - 尝试多种可能的字段名
  const info = await userStore.getInfo()

  // 如果找到了stationId，将其添加到表单数据中
  if (info) {
    formData.stationId = info.userInfo && info.userInfo.stationId
  }

  // 为createBy和createTime字段赋值
  // createBy: 当前登录用户的昵称
  formData.createBy = userStore.nickName || userStore.name || ''

  // createTime: 当前时间，格式为YYYY-MM-DD
  const now = new Date()
  formData.createTime = now.toISOString().substring(0, 10)


  formData.shifts = `${formData.shiftStart || 0}-${formData.shiftEnd || 0}`

  // 处理开始日期，从开始时间中提取日期部分
  if (formData.startDate) {
    formData.startDate = formData.startDate.split(' ')[0]
  }
  if (formData.deptIds) {
    formData.deptIds = formData.deptIds.join(',')
  }
  delete formData.endTime
  delete formData.shiftStart
  delete formData.shiftEnd

  return formData
}

onMounted(() => {
  getList()
  fetchDepartmentList()
})




</script>