<template>
  <div class="app-container">
    <el-card class="main-card">
      <div class="search-area">
        <span style="margin-left: 10px">产品型号：</span>
        <el-input v-model="searchProductType" clearable placeholder="输入产品型号" size="small" style="width:180px;"/>
        <el-button
          icon="el-icon-search"
          plain
          size="small"
          style="margin-left: 10px"
          type="primary"
          @click="searchData()">查询
        </el-button>
        <el-button icon="el-icon-circle-plus" size="small" type="primary" @click="createMachineType()">
          新增机型
        </el-button>
      </div>
      <el-table
        v-loading="loading"
        ref="machineTable"
        :data="tableData"
        :header-cell-style="{background:'#f5f7fa', color:'#333', fontSize: '14px', fontWeight: 'bold'}"
        border
        class="main-table"
        element-loading-background="rgba(0, 0, 0, 0.2)"
        element-loading-spinner="el-icon-loading"
        element-loading-text="数据加载中"
        height="770px"
        highlight-current-row
        size="medium"
        style="width: 100%;"
        tooltip-effect="dark">
        <el-table-column align="center" label="序号" type="index" width="60"/>
        <el-table-column align="center" label="产品型号" prop="产品型号" min-width="120"/>
        <!-- 动态工位列 -->
        <el-table-column
          v-for="station in stationList"
          :key="station.工位号"
          :label="station.工位号"
          :prop="station.工位号"
          align="center"
          min-width="80">
          <template slot="header">
            <el-tooltip :content="station.工位名称" placement="top">
              <span>{{ station.工位号 }}</span>
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <span>{{ scope.row[station.工位号] !== null ? scope.row[station.工位号] : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button
              icon="el-icon-edit"
              size="mini"
              type="primary"
              @click="handleEdit(scope.row)">编辑
            </el-button>
            <el-button
              icon="el-icon-delete"
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑机型对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      :visible.sync="dialogVisible" 
      center 
      width="900px"
      @close="resetForm()">
      <el-form ref="machineForm" :model="machineForm" :rules="formRules" label-position="right" label-width="100px">
        <el-form-item label="产品型号" prop="productType">
          <el-input v-model="machineForm.productType" clearable placeholder="请输入产品型号" style="width: 300px;"/>
        </el-form-item>
        <el-divider content-position="left">工位程序号配置</el-divider>
        <div class="station-config-grid">
          <div v-for="station in stationList" :key="station.工位号" class="station-config-item">
            <el-form-item :label="station.工位号" label-width="80px">
              <el-input-number 
                v-model="machineForm.stationConfig[station.工位号]" 
                :min="0"
                :step="1"
                :precision="0"
                size="small"
                style="width: 100px;"/>
              <el-tooltip :content="station.工位名称" placement="top">
                <i class="el-icon-info" style="margin-left: 5px; color: #909399;"></i>
              </el-tooltip>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="submitForm()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchProductType: '', // 查询条件 - 产品型号
      tableData: [], // 表格数据
      stationList: [], // 工位列表
      loading: false, // 加载状态
      dialogVisible: false, // 对话框显示状态
      dialogTitle: '新增机型', // 对话框标题
      isEdit: false, // 是否编辑模式
      originalProductType: '', // 原产品型号（编辑时使用）
      machineForm: {
        productType: '', // 产品型号
        stationConfig: {} // 工位配置 {工位号: 程序号}
      },
      formRules: {
        productType: [
          { required: true, message: '请输入产品型号', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.loadStationList()
  },
  methods: {
    // 加载工位列表
    loadStationList() {
      const data = this.CreateData('11', 'MES_计划BOM_工位与名称_装配线工位查询', [])
      this.ExecDatabase(data).then(response => {
        this.stationList = response.data
        // 初始化工位配置
        this.initStationConfig()
        // 加载机型数据
        this.searchData()
      }).catch(() => {
        this.$message.error('加载工位列表失败')
      })
    },

    // 初始化工位配置
    initStationConfig() {
      const config = {}
      this.stationList.forEach(station => {
        config[station.工位号] = 0
      })
      this.machineForm.stationConfig = config
    },

    // 查询机型数据
    searchData() {
      this.loading = true
      const param = []
      if (this.searchProductType) {
        param.push(['产品型号_check', 1])
        param.push(['产品型号', this.searchProductType])
      } else {
        param.push(['产品型号_check', 0])
      }

      const data = this.CreateData('11', 'MES_基本变量_机型代码_查询数据', param)
      this.ExecDatabase(data).then(response => {
        this.tableData = response.data
        this.loading = false
      }).catch(() => {
        this.loading = false
        this.$message.error('加载数据失败')
      })
    },

    // 创建新机型
    createMachineType() {
      this.isEdit = false
      this.dialogTitle = '新增机型'
      this.resetForm()
      this.dialogVisible = true
    },

    // 编辑机型
    handleEdit(row) {
      this.isEdit = true
      this.dialogTitle = '编辑机型'
      this.originalProductType = row.产品型号
      this.machineForm.productType = row.产品型号
      
      // 填充工位配置
      const config = {}
      this.stationList.forEach(station => {
        config[station.工位号] = row[station.工位号] !== null ? row[station.工位号] : 0
      })
      this.machineForm.stationConfig = config
      this.dialogVisible = true
    },

    // 删除机型
    handleDelete(row) {
      const productType = row.产品型号
      this.$confirm(`确定要删除产品型号 "${productType}" 的所有工位配置吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const param = [['产品型号', productType]]
        const data = this.CreateData('12', 'MES_基本变量_机型代码_删除', param)
        
        this.ExecDatabase(data).then(response => {
          if (response.data && response.data[0] && response.data[0].result === '1') {
            this.$message.success('删除成功')
            this.searchData()
          } else {
            const msg = response.data && response.data[0] && response.data[0].msg ? response.data[0].msg : '删除失败'
            this.$message.error(msg)
          }
        }).catch(() => {
          this.$message.error('删除失败')
        })
      }).catch(() => {
        // 取消删除操作
      })
    },

    // 提交表单
    submitForm() {
      this.$refs.machineForm.validate((valid) => {
        if (valid) {
          if (this.isEdit) {
            this.updateMachine()
          } else {
            this.addMachine()
          }
        }
      })
    },

    // 构建工位配置JSON
    buildStationConfigJson() {
      const configArray = []
      this.stationList.forEach(station => {
        configArray.push({
          工位号: station.工位号,
          程序号: this.machineForm.stationConfig[station.工位号] || 0
        })
      })
      return JSON.stringify(configArray)
    },

    // 新增机型
    addMachine() {
      const configJson = this.buildStationConfigJson()
      const param = [
        ['产品型号', this.machineForm.productType],
        ['工位配置', configJson]
      ]
      const data = this.CreateData('12', 'MES_基本变量_机型代码_增加', param)
      
      this.ExecDatabase(data).then(response => {
        if (response.data && response.data[0] && response.data[0].result === '1') {
          this.$message.success('添加成功')
          this.dialogVisible = false
          this.searchData()
        } else {
          const msg = response.data && response.data[0] && response.data[0].msg ? response.data[0].msg : '添加失败'
          this.$message.error(msg)
        }
      }).catch(() => {
        this.$message.error('添加失败')
      })
    },

    // 更新机型
    updateMachine() {
      const configJson = this.buildStationConfigJson()
      const param = [
        ['原产品型号', this.originalProductType],
        ['新产品型号', this.machineForm.productType],
        ['工位配置', configJson]
      ]
      const data = this.CreateData('12', 'MES_基本变量_机型代码_修改', param)
      
      this.ExecDatabase(data).then(response => {
        if (response.data && response.data[0] && response.data[0].result === '1') {
          this.$message.success('更新成功')
          this.dialogVisible = false
          this.searchData()
        } else {
          const msg = response.data && response.data[0] && response.data[0].msg ? response.data[0].msg : '更新失败'
          this.$message.error(msg)
        }
      }).catch(() => {
        this.$message.error('更新失败')
      })
    },

    // 重置表单
    resetForm() {
      if (this.$refs.machineForm) {
        this.$refs.machineForm.resetFields()
      }
      this.machineForm.productType = ''
      this.originalProductType = ''
      this.initStationConfig()
    }
  }
}
</script>

<style scoped>
.main-card {
  margin: 10px;
  padding: 5px;
}

.search-area {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.main-table {
  margin-top: 10px;
}

.station-config-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  padding: 10px;
}

.station-config-item {
  display: flex;
  align-items: center;
}

.el-divider {
  margin: 15px 0;
}

::v-deep .el-input.is-disabled .el-input__inner {
  color: #606266 !important;
  background-color: white !important;
}

::v-deep .el-form-item {
  margin-bottom: 15px;
}

::v-deep .el-form-item__label {
  font-weight: normal;
}
</style>
