<template>
  <div>
    <el-row>
      <!-- 查询表单（保持不变） -->
      <el-form :inline="true" :model="queryForm" ref="queryForm" label-width="100px">
        <el-form-item label="钢卷号" prop="coilid">
          <el-input size="mini" v-model="queryForm.coilid" placeholder="请输入钢卷号"></el-input>
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker size="mini" v-model="queryForm.startDate" type="date" placeholder="选择开始日期"
            value-format="yyyy-MM-dd" clearable></el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker size="mini" v-model="queryForm.endDate" type="date" placeholder="选择结束日期"
            value-format="yyyy-MM-dd" clearable></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" :loading="btnLoading" icon="el-icon-search"
            size="mini">查询</el-button>
          <el-button @click="handleReset" icon="el-icon-refresh" size="mini">重置</el-button>
          <el-button type="success" @click="handleAdd" icon="el-icon-plus" size="mini">补录</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格（保持不变） -->
      <el-table v-loading="tableLoading" :data="tableData" border style="width: 100%; margin-top: 20px;"
        @row-click="handleRowClick" highlight-current-row>
        <el-table-column prop="exitMatId" label="成品卷" width="150" align="center" />
        <el-table-column prop="entryMatId" label="来料卷" width="150" align="center" />
        <el-table-column prop="subId" label="分切数" width="100" align="center" />
        <el-table-column prop="status" label="状态" width="100" align="center" />
        <el-table-column prop="startPosition" label="开始位置" width="100" align="center" />
        <el-table-column prop="endPosition" label="结束位置" width="100" align="center" />
        <el-table-column prop="planId" label="计划ID" width="120" align="center" />
        <el-table-column prop="planNo" label="计划号" width="150" align="center" />
        <el-table-column prop="prodCode" label="产品类型" width="120" align="center" />
        <el-table-column prop="groupNo" label="班号" width="100" align="center" />
        <el-table-column prop="shiftNo" label="组号" width="100" align="center" />
        <el-table-column prop="steelGrade" label="钢种" width="100" align="center" />
        <el-table-column prop="entryThick" label="来料厚度" width="100" align="center" />
        <el-table-column prop="entryWidth" label="来料宽带" width="100" align="center" />
        <el-table-column prop="entryLength" label="来料长度" width="100" align="center" />
        <el-table-column prop="entryWeight" label="来料重量" width="100" align="center" />
        <el-table-column prop="weightTop" label="上表面镀锌" width="100" align="center" />
        <el-table-column prop="weightBottom" label="下表面镀锌" width="100" align="center" />
        <el-table-column prop="exitLength" label="成品长度" width="100" align="center" />
        <el-table-column prop="exitNetWeight" label="成品带涂料重量" width="120" align="center" />
        <el-table-column prop="theoryWeight" label="理论重量" width="100" align="center" />
        <el-table-column prop="actualWeight" label="实际重量" width="100" align="center" />
        <el-table-column prop="exitOuterDiameter" label="成品外径" width="100" align="center" />
        <el-table-column prop="exitThickness" label="成品厚度" width="100" align="center" />
        <el-table-column prop="exitWidth" label="成品宽度" width="100" align="center" />
        <el-table-column prop="customer" label="客户" width="120" align="center" />
        <el-table-column label="上线时间" prop="onlineTime" width="180" align="center">
          <template slot-scope="scope">{{ parseTime(scope.row.onlineTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</template>
        </el-table-column>
        <el-table-column label="开始时间" prop="startTime" width="180" align="center">
          <template slot-scope="scope">{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</template>
        </el-table-column>
        <el-table-column label="结束时间" prop="endTime" width="180" align="center">
          <template slot-scope="scope">{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</template>
        </el-table-column>
        <el-table-column prop="unitCode" label="机组号" width="100" align="center" />
        <el-table-column prop="processCode" label="工序号" width="100" align="center" />
        <el-table-column label="是否尾卷" width="100" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.lastFlag ? '是' : '否' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="是否分卷" width="100" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.separateFlag ? '是' : '否' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="计划来源" align="center" prop="planOrigin" width="120">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.pdo_plan_origin" :value="scope.row.planOrigin" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right" prop="action">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleEdit(scope.row)" icon="el-icon-edit">操作</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)" :loading="scope.row.deleteLoading"
              icon="el-icon-delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>

    <el-row>
      <el-col :span="3">
        <pdo-summary :table-data="tableData" />
      </el-col>
      
      <el-col :span="21">
        <line-chart :enCoilID="currentRow.exitMatId" :baseURL="baseURL" />
      </el-col>
    </el-row>

    <!-- 编辑/新增弹窗：根据isAdd条件渲染内容 -->
    <el-dialog 
      :title="dialogTitle"
      :visible.sync="dialogVisible" 
      width="60%" 
      :close-on-click-modal="false"
    >
      <!-- 补录（新增）：仅显示数据修正组件，无tab -->
      <div v-if="isAdd">
        <pdo-data-correction
          :detail="formData"
          :save-callback="handleSave"
          :save-loading="saveLoading"
        ></pdo-data-correction>
      </div>

      <!-- 编辑：保留原有tab，显示数据修正+标签打印 -->
      <el-tabs v-else v-model="activeTab">
        <el-tab-pane label="数据修正" name="basicInfo">
          <pdo-data-correction
            :detail="formData"  
            :save-callback="handleSave"
            :save-loading="saveLoading"
          ></pdo-data-correction>
        </el-tab-pane>
        <el-tab-pane label="标签打印" name="labelPrint">
          <pdo-label-print
            :detail="formData"
          ></pdo-label-print>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script>
// import { getPdoList, addPdo, updatePdo, deletePdo } from '@/api/l2/pdo'
import createFetch from '@/api/l2/pdo'
import LineChart from './components/line.vue'
// 引入封装的两个组件
import PdoDataCorrection from './components/DataCorrection.vue'
import PdoLabelPrint from './components/LabelPrint.vue'
import PdoSummary from './components/PdoSummary.vue'

export default {
  name: 'PdoManagement',
  dicts: ['pdo_plan_origin'],
  components: {
    LineChart,
    PdoDataCorrection, // 注册数据修正组件
    PdoLabelPrint,      // 注册标签打印组件
    PdoSummary
  },
  props: {
    baseURL: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      fetchApi: {},
      activeTab: 'basicInfo',
      queryForm: { coilid: '', startDate: '', endDate: '' },
      tableData: [],
      tableLoading: false,
      btnLoading: false,
      dialogVisible: false,
      dialogTitle: '新增实绩',
      // 新增：区分「补录（新增）」和「编辑」的状态标识
      isAdd: false,
      // 传递给子组件的详情数据（父组件仅做数据中转，不直接修改）
      formData: {},
      saveLoading: false,
      currentRow: {},
      socketType: [
        { value: 'alarm', label: '报警' },
        { value: 'track_position', label: '跟踪位置' },
        { value: 'track_measure', label: '跟踪测量' },
        { value: 'track_signal', label: '跟踪信号' },
        { value: 'track_matmap', label: '跟踪料号' },
        { value: 'calc_setup_result', label: '计算结果' }
      ]
    }
  },
  created() {
    this.fetchApi = createFetch(this.baseURL)
    this.getPdoList()
  },
  methods: {
    // 获取列表数据（保持不变）
    getPdoList() {
      this.tableLoading = true
      this.fetchApi.getPdoList(this.queryForm).then(res => {
        this.tableData = res.data.map(item => ({ ...item, deleteLoading: false }))
      }).catch(err => {
        console.error(err)
        this.$message.error('获取数据失败')
      }).finally(() => {
        this.tableLoading = false
        this.btnLoading = false
      })
    },
    // 查询（保持不变） 
    handleQuery() {
      this.btnLoading = true;
      this.getPdoList()
    },
    // 重置（保持不变）
    handleReset() {
      this.$refs.queryForm.resetFields();
      this.getPdoList()
    },
    // 行点击（保持不变）
    handleRowClick(row) {
      this.currentRow = row;
    },
    // 补录（新增）：设置isAdd=true，初始化空表单
    handleAdd() {
      this.isAdd = true; // 标记为「补录」
      this.dialogTitle = '新增实绩';
      // 初始化空表单数据（传递给子组件）
      this.formData = {
        subId: 0,
        startPosition: 0,
        endPosition: 0,
        planId: 0,
        entryThick: 0,
        entryWidth: 0,
        entryLength: 0,
        entryWeight: 0,
        weightTop: 0,
        weightBottom: 0,
        exitLength: 0,
        exitNetWeight: 0,
        theoryWeight: 0,
        actualWeight: 0,
        exitOuterDiameter: 0,
        exitThickness: 0,
        exitWidth: 0,
        lastFlag: false,
        separateFlag: false
      };
      this.dialogVisible = true
    },
    // 编辑：设置isAdd=false，赋值行数据
    handleEdit(row) {
      this.isAdd = false; // 标记为「编辑」
      this.dialogTitle = '编辑实绩';
      // 深拷贝行数据（避免直接修改表格数据）
      this.formData = JSON.parse(JSON.stringify(row));
      this.dialogVisible = true
    },
    // 删除（保持不变）
    handleDelete(row) {
      this.$confirm(`确定删除成品卷 ${row.exitMatId}?`, '确认删除', { type: 'danger' }).then(() => {
        row.deleteLoading = true
        this.fetchApi.deletePdo(row.exitMatId, row.planId).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功');
            this.getPdoList()
          } else this.$message.error(res.msg || '删除失败')
        }).finally(() => row.deleteLoading = false)
      })
    },
    // 保存回调（子组件触发，处理实际API调用）
    handleSave(formData) {
      this.saveLoading = true
      // 根据是否有id判断是新增还是编辑
      const request = formData.id ? this.fetchApi.updatePdo(formData) : this.fetchApi.addPdo(formData)
      request.then(res => {
        if (res.code === 200) {
          this.$message.success('保存成功');
          this.dialogVisible = false;
          this.getPdoList() // 刷新列表
        } else this.$message.error(res.msg || '保存失败')
      }).finally(() => {
        this.saveLoading = false
      })
    },
  }
}
</script>