<template>
  <div class="app-container">
    <el-card>
      <!-- 添加新班次按钮 -->
      <div >
        <el-button type="primary" icon="el-icon-plus" @click="handleAddShift"  style="width: auto;">添加新班次</el-button>
      </div>
      <div style="margin-top: 10px">
        <el-table
          v-loading="loading"
          :data="tableData"
          border
          element-loading-background="rgba(0, 0, 0, 0.2)"
          element-loading-spinner="el-icon-loading"
          element-loading-text="数据加载中"
          height="694"
          highlight-current-row
          size="mini"
          stripe
          style="width: 100%"
          tooltip-effect="dark">
          <el-table-column align="center" label="序号" type="index" width="60"/>
          <el-table-column align="center" label="班次" width="120">
            <template slot-scope="scope">
              <el-input
                v-if="scope.row.isEditing"
                v-model="scope.row.班次名称"
                size="mini"
                placeholder="请输入班次名称"
                
              />
              <span v-else>{{ scope.row.班次名称 }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="时间" width="300">
            <template slot-scope="scope">
              <div v-if="scope.row.isEditing" style="display: flex; align-items: center; gap: 5px">
                <el-time-picker
                  v-model="scope.row.开始时间"
                  placeholder="开始时间"
                  format="HH:mm"
                  value-format="HH:mm"
                  size="mini"
                  style="width: 120px"
                />
                <span>-</span>
                <el-time-picker
                  v-model="scope.row.结束时间"
                  placeholder="结束时间"
                  format="HH:mm"
                  value-format="HH:mm"
                  size="mini"
                  style="width: 120px"
                />
              </div>
              <span v-else>{{ scope.row.开始时间 }} - {{ scope.row.结束时间 }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="绑定人员" width="300">
            <template slot-scope="scope">
              <el-tag
                v-for="person in scope.row.绑定人员列表"
                :key="person.人员编号"
                style="margin: 2px"
                type="info">
                {{ person.人员姓名 }}
              </el-tag>
              <span v-if="!scope.row.绑定人员列表 || scope.row.绑定人员列表.length === 0">未绑定人员</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="320">
            <template slot-scope="scope">
              <el-button
                v-if="!scope.row.isEditing"
                icon="el-icon-edit"
                style="font-family: MiSans Regular,serif;color: #409EFF"
                type="text"
                @click="handleEditShift(scope.row)">编辑
              </el-button>
              <el-button
                v-else
                icon="el-icon-check"
                style="font-family: MiSans Regular,serif;color: #67C23A"
                type="text"
                @click="handleSaveShift(scope.row)">保存
              </el-button>
              <el-button
                v-if="scope.row.isEditing"
                icon="el-icon-close"
                style="font-family: MiSans Regular,serif;color: #F56C6C"
                type="text"
                @click="handleCancelEdit(scope.row)">取消
              </el-button>
              <el-button
                icon="el-icon-user"
                style="font-family: MiSans Regular,serif;color: #67c23a"
                type="text"
                @click="handleBindPerson(scope.row)">绑定
              </el-button>
              <el-button
                icon="el-icon-delete"
                style="font-family: MiSans Regular,serif;color: #F56C6C"
                type="text"
                @click="handleDeleteShift(scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      
    </el-card>

    <!-- 绑定人员对话框 -->
    <el-dialog :visible.sync="dialogBindPersonVisible" center title="绑定人员" width="600px">
      <el-divider style="margin: 0"/>
      <div style="margin: 20px 0">
        <span>当前班次: {{ currentShift.班次名称 }} ({{ currentShift.开始时间 }} - {{ currentShift.结束时间 }})</span>
      </div>
      <el-transfer
        v-model="selectedPersonnel"
        :data="personnelList"
        :titles="['可选人员', '已选人员']"
        filterable
        style="text-align: left"
        @change="handleTransferChange">
      </el-transfer>
      <div slot="footer" style="text-align: center; margin-top: 20px">
        <el-button type="primary" @click="submitBindPerson">确 定</el-button>
        <el-button @click="dialogBindPersonVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loading: false,
      tableData: [],
      dialogBindPersonVisible: false,
      currentShift: {},
      personnelList: [],
      selectedPersonnel: [],
      originalData: {} // 用于保存编辑前的数据
    }
  },
  created() {
    this.searchData()
    this.loadPersonnelList()
  },
  methods: {
    // 查询班次数据
    searchData() {
      this.loading = true
      this.tableData = []
      var param = []
      var Data = this.CreateData('11', '生产管理_班次管理_班次列表查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data && response.data.length !== 0) {
          // 添加编辑状态字段
          this.tableData = response.data.map(item => ({
            ...item,
            isEditing: false
          }))
          this.loadBoundPersonnelForShifts()
        } else {
          this.loading = false
        }
      }).catch(() => {
        this.loading = false
      })
    },

    // 加载所有人员列表
    loadPersonnelList() {
      var param = []
      var Data = this.CreateData('11', '系统管理_人员管理_所有有效人员查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data && response.data.length > 0) {
          this.personnelList = response.data.map(person => ({
            key: person.人员编号,
            label: `${person.人员姓名} (${person.账号})`,
            disabled: false
          }))
        }
      })
    },

    // 为所有班次加载绑定的人员信息
    loadBoundPersonnelForShifts() {
      console.log('开始加载班次绑定人员信息...')
      
      const promises = this.tableData.map((shift, index) => {
        return new Promise((resolve) => {
          var param = []
          param[0] = ['班次编号', shift.班次编号]

          var Data = this.CreateData('11', '生产管理_班次管理_班次绑定人员查询', param)
          this.ExecDatabase(Data).then(response => {
            let boundPersonnel = []
            
            if (response.data && Array.isArray(response.data)) {
              boundPersonnel = response.data
            } else if (response.result && Array.isArray(response.result)) {
              boundPersonnel = response.result
            } else if (response.data && response.data.result && Array.isArray(response.data.result)) {
              boundPersonnel = response.data.result
            }
            
            this.$set(shift, '绑定人员列表', boundPersonnel)
            resolve()
          }).catch((error) => {
            console.error(`加载班次 ${shift.班次名称} 绑定人员失败:`, error)
            this.$set(shift, '绑定人员列表', [])
            resolve()
          })
        })
      })

      Promise.all(promises).then(() => {
        console.log('所有班次绑定人员加载完成')
        this.loading = false
      })
    },

    // 编辑班次
    handleEditShift(row) {
      this.originalData[row.班次编号] = { ...row }
      row.isEditing = true
    },

    // 保存班次
    handleSaveShift(row) {
      if (!row.班次名称) {
        this.$message.error('请输入班次名称')
        return
      }
      
      if (!row.开始时间 || !row.结束时间) {
        this.$message.error('请设置班次时间')
        return
      }

      var param = []
      param[0] = ['班次编号', row.班次编号]
      param[1] = ['班次名称', row.班次名称]
      param[2] = ['开始时间', row.开始时间]
      param[3] = ['结束时间', row.结束时间]
      param[4] = ['操作人', this.$store.state.user.name]
      var Data = this.CreateData('11', '生产管理_班次管理_班次保存', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data[0].执行结果 === 1) {
          this.$message.success('班次保存成功')
          row.isEditing = false
          delete this.originalData[row.班次编号]
          // 如果是新增的班次，重新加载数据获取正确的班次编号
          if (row.班次编号.startsWith('NEW_')) {
            this.searchData()
          }
        } else {
          this.$message.error('班次保存失败: ' + response.data[0].提示信息)
        }
      }).catch(() => {
        this.$message.error('班次保存失败')
      })
    },

    // 取消编辑
    handleCancelEdit(row) {
      if (this.originalData[row.班次编号]) {
        Object.assign(row, this.originalData[row.班次编号])
        delete this.originalData[row.班次编号]
      }
      row.isEditing = false
      
      // 如果是新增的班次且取消编辑，则从列表中移除
      if (row.班次编号.startsWith('NEW_')) {
        const index = this.tableData.findIndex(item => item.班次编号 === row.班次编号)
        if (index !== -1) {
          this.tableData.splice(index, 1)
        }
      }
    },

    // 添加新班次
    handleAddShift() {
      const newShift = {
        班次编号: 'NEW_' + Date.now(),
        班次名称: '',
        开始时间: '08:00',
        结束时间: '17:00',
        绑定人员列表: [],
        isEditing: true
      }
      this.tableData.unshift(newShift)
      this.originalData[newShift.班次编号] = { ...newShift }
    },

    // 删除班次
    handleDeleteShift(row) {
      this.$confirm(`确定要删除班次"${row.班次名称}"吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var param = []
        param[0] = ['班次编号', row.班次编号]
        
        var Data = this.CreateData('11', '生产管理_班次管理_班次删除', param)
        this.ExecDatabase(Data).then(response => {
          if (response.data[0].执行结果 === 1) {
            this.$message.success('班次删除成功')
            this.searchData() // 刷新数据
          } else {
            this.$message.error('班次删除失败: ' + response.data[0].提示信息)
          }
        }).catch(() => {
          this.$message.error('班次删除失败')
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    // 绑定人员
    handleBindPerson(row) {
      this.currentShift = { ...row }
      this.dialogBindPersonVisible = true
      
      var param = []
      param[0] = ['班次编号', row.班次编号]
      var Data = this.CreateData('11', '生产管理_班次管理_班次绑定人员查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data && response.data.length > 0) {
          this.selectedPersonnel = response.data.map(person => person.人员编号)
        } else {
          this.selectedPersonnel = []
        }
      })
    },

    // 提交人员绑定
    submitBindPerson() {
      if (!this.currentShift.班次编号) {
        this.$message.error('班次信息错误')
        return
      }

      var param = []
      param[0] = ['班次编号', this.currentShift.班次编号]
      param[1] = ['人员编号列表', this.selectedPersonnel.join(',')]
      param[2] = ['操作人', this.$store.state.user.name]
      var Data = this.CreateData('11', '生产管理_班次管理_班次绑定人员保存', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data[0].执行结果 === 1) {
          this.$message.success('人员绑定成功')
          this.dialogBindPersonVisible = false
          this.searchData() // 刷新数据
        } else {
          this.$message.error('人员绑定失败: ' + response.data[0].提示信息)
        }
      }).catch(() => {
        this.$message.error('人员绑定失败')
      })
    },

    // 传输框变化处理
    handleTransferChange(value, direction, movedKeys) {
      console.log('传输框变化:', value, direction, movedKeys)
    }
  }
}
</script>

<style scoped>
.el-card {
  margin: 0px;
}

.el-transfer {
  display: flex;
  justify-content: center;
}

.el-input {
  width: 100%;
}
</style>