<template>
  <div class="app-container">
    <el-card>
      <!-- <span class="show-text">工位名称:</span>
      <el-input
        v-model="searchWorkstationName"
        clearable
        placeholder="请输入工位名称"
        style="width: 280px;margin-right: 26px"/>
      <el-button icon="el-icon-search" plain type="primary" @click="searchData()">查询</el-button> -->
      
      <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">
              {{ scope.row.指南工位号 }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="工位号" width="100">
            <template slot-scope="scope">
              {{ scope.row.工位号 }}
            </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="120">
            <template slot-scope="scope">
              <el-button
                icon="el-icon-user"
                style="font-family: MiSans Regular,serif;color: #67c23a"
                type="text"
                @click="handleBindPerson(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>当前工位: {{ currentWorkstation.指南工位号 }} ({{ currentWorkstation.工位号 }})</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 {
      searchWorkstationName: '',
      loading: false,
      tableData: [],
      dialogBindPersonVisible: false,
      currentWorkstation: {},
      personnelList: [],
      selectedPersonnel: [],
    }
  },
  created() {
    this.searchData()
    this.loadPersonnelList()
  },
  methods: {
    // 查询工位数据
    searchData() {
      this.loading = true
      this.tableData = []
      var param = []
      var Data = this.CreateData('11', 'MES_登录_工位与名称_查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.length !== 0) {
          this.tableData = response.data
          this.loadBoundPersonnelForWorkstations()
        } else {
          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
          }))
        }
      })
    },

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

      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
        }
        // 使用 Vue.set 确保响应式更新
        this.$set(workstation, '绑定人员列表', boundPersonnel)
        
        resolve()
      }).catch((error) => {
        console.error(`加载工位 ${workstation.工位号} 绑定人员失败:`, error)
        this.$set(workstation, '绑定人员列表', [])
        resolve()
      })
    })
  })

  Promise.all(promises).then(() => {
    console.log('所有工位绑定人员加载完成，最终数据:', this.tableData)
    this.loading = false
  })
},

    // 绑定人员
    handleBindPerson(row) {
      this.currentWorkstation = { ...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.currentWorkstation.工位号) {
        this.$message.error('工位信息错误')
        return
      }

      var param = []
      param[0] = ['工位号', this.currentWorkstation.工位号]
      param[1] = ['人员编号列表', this.selectedPersonnel.join(',')]
      
      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;
}
</style>