<template>
  <a-modal
    title="测量项点"
    :width="900"
    :visible="visible"
    :confirm-loading="confirmLoading"
    :body-style="measureBody"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form-model
        ref="measureItemForm"
        :model="measureItem"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-model-item label="测量项" prop="dataPot">
          <a-input v-model="measureItem.dataPot" placeholder="请输入测量项" />
        </a-form-model-item>

        <a-form-model-item class="measure-model-item" label="测量项点" prop="points">
          <a-button type="primary" size="small" @click="handleAdd">添加</a-button>
          <a-table
            size="small"
            row-key="key"
            :columns="columns"
            :data-source="measureItem.points"
            bordered
            :pagination="false"
            :scroll="{ y: 350 }"
            :locale="{ emptyText: '暂无测量项点' }"
          >
            <!-- 序号列 -->
            <span slot="dataIndex" slot-scope="text, record, index">
              {{ record.dispIndex || index + 1 }}
            </span>

            <!-- 可编辑列 -->
            <template
              v-for="col in ['dataPot', 'maxValue', 'minValue', 'unit', 'avgCount', 'toolId']"
              :slot="col"
              slot-scope="text, record"
            >
              <div :key="col" class="editable-cell">
                <a-select
                  v-if="record.editable && col === 'toolId'"
                  style="width: 100%"
                  placeholder="请选择工具"
                  :value="record[col]"
                  :options="toolOptions"
                  @change="(value) => handleChange(value, record, col)"
                />
                <a-input
                  v-else-if="record.editable"
                  style="width: 100%"
                  :value="record[col]"
                  @change="(e) => handleChange(e.target.value, record, col)"
                />
                <span v-else>{{ text }}</span>
              </div>
            </template>

            <!-- 操作列 -->
            <span slot="operation" slot-scope="text, record">
              <span v-if="record.editable">
                <!-- 新增行：用 popconfirm（轻量、无请求） -->
                <a-popconfirm
                  v-if="record.isNew"
                  title="是否取消？"
                  @confirm="() => handleCancelEdit(record)"
                >
                  <a>取消</a>
                </a-popconfirm>
                <!-- 已有行：用 $confirm（需异步删除） -->
                <a v-else @click="() => handleDeleteConfirm(record)">删除</a>
              </span>
              <span v-else>
                <a :disabled="!!editingKey" @click="() => edit(record)">编辑</a>
              </span>
            </span>
          </a-table>
        </a-form-model-item>
      </a-form-model>
    </a-spin>

    <template slot="footer">
      <a-button @click="handleCancel">关闭</a-button>
      <a-button type="primary" @click="handleSubmit">确定</a-button>
      <a-button class="orange-btn" type="primary" @click="copyMeasure">参照</a-button>
    </template>

    <measure-copy ref="measureCopy" @copyItems="handleCopyItems" />
  </a-modal>
</template>

<script>
import { deleteAction, getAction, httpAction } from '@api/manage'
import MeasureCopy from '@views/regular/components/MeasureCopy/index.vue'

export default {
  name: 'MeasureItemModal',
  components: { MeasureCopy },
  data() {
    return {
      detailId: '',
      deviceTypeId: '',
      editingKey: '', // 当前正在编辑的 key
      dataVersion: 0,// 当打开弹窗时有初始测量项，置为1；为1时，如果参照了其他数据，置为2(用于删除旧数据)
      confirmLoading: false,
      visible: false,
      measureItem: {
        dataPot: '',
        detailId: '',
        points: [],
      },
      labelCol: { span: 2 },
      wrapperCol: { span: 22 },
      rules: {
        dataPot: [{ required: true, message: '请输入测量项名称', trigger: 'blur' }],
        // points 不直接校验，由子项控制
      },
      columns: [
        { title: '序号', width: 50,dataIndex: 'dispIndex', key: 'dispIndex', align: 'center', scopedSlots: { customRender: 'dataIndex' } },
        { title: '项点', dataIndex: 'dataPot', key: 'dataPot',align: 'center', scopedSlots: { customRender: 'dataPot' } },
        { title: '最大值', width: 90,dataIndex: 'maxValue', key: 'maxValue', align: 'center', scopedSlots: { customRender: 'maxValue' } },
        { title: '最小值', width: 90,dataIndex: 'minValue', key: 'minValue', align: 'center', scopedSlots: { customRender: 'minValue' } },
        { title: '单位', width: 80,dataIndex: 'unit', key: 'unit', align: 'center', scopedSlots: { customRender: 'unit' } },
        { title: '期望值基数', width: 90,dataIndex: 'avgCount', key: 'avgCount', align: 'center', scopedSlots: { customRender: 'avgCount' } },
        { title: '工具', width: 120,dataIndex: 'toolId_dictText', key: 'toolId', align: 'center', scopedSlots: { customRender: 'toolId' } },
        { title: '操作', width: 80,dataIndex: 'operation', key: 'operation', align: 'center', scopedSlots: { customRender: 'operation' } },
      ],
      url: {
        add: '/regular/regularInput/add',
        edit: '/regular/regularInput/edit',
        list: '/regular/regularInput/list',
      },
      tools: [],
      measureBody: {
        padding: '24px 24px 0 24px',
        fontSize: '14px',
        lineHeight: '1.5',
        maxHeight: '70vh',
        overflowY: 'auto'
      },
    }
  },
  computed: {
    toolOptions() {
      return this.tools.map(d => ({
        value: d.toolId,
        label: d.toolId_dictText,
      }))
    },
  },
  methods: {
    show(detailId, deviceTypeId) {
      this.detailId = detailId
      this.deviceTypeId = deviceTypeId
      this.measureItem.detailId = detailId
      this.editingKey = ''
      this.visible = true

      if (!detailId) {
        this.resetMeasureItem()
        this.loadAllTool(detailId)
        return
      }

      // 加载已有数据
      getAction(this.url.list, { detailId }).then(res => {
        if (res.success) {
          if (res.result.length > 0) {
            const item = res.result[0]
            // 清理只读字段
            this.measureItem = {
              id: item.id,
              dataPot: item.dataPot,
              detailId: detailId,
              points: (item.points || []).map(p => ({
                ...p,
                key: p.id || Date.now() + Math.random(),
                dispIndex: p.dispIndex || 1,
              })),
            }
            this.dataVersion = 1;// 有测量项数据
          } else {
            this.resetMeasureItem()
            this.dataVersion = 0
          }
        } else {
          this.$message.error(res.message)
          this.resetMeasureItem()
        }
        this.loadAllTool(detailId)
      })
    },

    resetMeasureItem() {
      this.measureItem = {
        dataPot: '',
        detailId: this.detailId,
        points: [],
      }
    },

    loadAllTool(detailId) {
      getAction('/regular/regularTools/list/all', { detailId }).then(res => {
        if (res.success) {
          this.tools = res.result || []
        } else {
          this.$message.error(res.message)
        }
      })
    },

    edit(record) {
      if (this.editingKey) return // 防止多行同时编辑
      this.editingKey = record.key
      const newData = [...this.measureItem.points]
      const target = newData.find(item => item.key === record.key)
      if (target) {
        target.editable = true
        this.measureItem.points = newData
      }
    },

    // 取消（无请求）
    handleCancelEdit(record) {
      const newData = [...this.measureItem.points]
      const index = newData.findIndex(item => item.key === record.key)
      if (index > -1 && record.isNew) {
        newData.splice(index, 1)
        this.recalculateDispIndex(newData)
        this.measureItem.points = newData
        this.editingKey = ''
      }
    },

    // 删除已有项点（异步，需确认 + 请求）
    handleDeleteConfirm(record) {
      this.$confirm({
        title: '确认删除',
        content: '确定要删除该测量项点吗？此操作不可恢复。',
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk: () => {
          return deleteAction('/regular/regularInput/delete', { id: record.id }).then(res => {
            if (res.success) {
              this.$message.success('删除成功')
              const newData = [...this.measureItem.points]
              const index = newData.findIndex(item => item.key === record.key)
              if (index > -1) {
                newData.splice(index, 1)
                this.recalculateDispIndex(newData)
                this.measureItem.points = newData
              }
            } else {
              this.$message.error(res.message || '删除失败')
            }
            this.editingKey = ''
          }).catch(err => {
            console.error('删除失败:', err)
            this.$message.error('网络错误，请重试')
            this.editingKey = ''
          })
        },
        onCancel: () => {
          this.editingKey = ''
        }
      })
    },
    recalculateDispIndex(list) {
      list.forEach((item, index) => {
        item.dispIndex = index + 1
      })
    },

    handleChange(value, record, column) {
      const newData = [...this.measureItem.points]
      const target = newData.find(item => item.key === record.key)
      if (!target) return

      // 数值校验
      if (column === 'maxValue' || column === 'minValue') {
        const num = parseFloat(value)
        if (value !== '' && isNaN(num)) {
          this.$message.error('请输入有效数字')
          return
        }
        if (column === 'maxValue' && target.minValue !== '' && num < parseFloat(target.minValue)) {
          this.$message.error('最大值不能小于最小值')
          return
        }
        if (column === 'minValue' && target.maxValue !== '' && num > parseFloat(target.maxValue)) {
          this.$message.error('最小值不能大于最大值')
          return
        }
      }

      if (column === 'avgCount') {
        let num = Number(value)
        // 非正整数 → 强制回退为 1
        if (!Number.isInteger(num) || num < 1) {
          this.$message.error('平均次数必须为大于等于 1 的整数')
          num = 1
        }
        value = String(num)
      }

      target[column] = value
      this.measureItem.points = newData
    },

    handleAdd() {
      const newItem = {
        key: Date.now() + Math.random(),
        dispIndex: this.measureItem.points.length + 1,
        dataPot: '',
        maxValue: '',
        minValue: '',
        unit: '',
        avgCount: '1',
        toolId: undefined,
        editable: true,
        isNew: true,
      }
      this.measureItem.points.push(newItem)
    },

    handleSubmit() {
      this.$refs.measureItemForm.validate(valid => {
        if (!valid) return
        if (this.measureItem.points.length === 0) {
          this.$message.warning('请至少添加一个测量项点')
          return
        }
        const hasEmpty = this.measureItem.points.some(p => !p.dataPot.trim())
        if (hasEmpty) {
          this.$message.warning('项点名称不能为空')
          return
        }
        this.confirmLoading = true

        // ✅ 覆盖模式：先删除旧数据
        if (this.dataVersion === 2) {
          deleteAction('/regular/regularInput/deleteBatchByDetail', { detailId: this.detailId })
            .then(res => {
              if (!res.success) {
                this.$message.error('删除旧数据失败')
                this.confirmLoading = false
                return
              }

              // 删除成功后，执行新增
              this.saveMeasureItem()
            })
            .catch(err => {
              console.error('删除失败:', err)
              this.$message.error('删除旧数据异常')
              this.confirmLoading = false
            })
        } else {
          // 普通新增或编辑
          this.saveMeasureItem()
        }
      })
    },
    // 抽离保存逻辑
    saveMeasureItem() {
      const url = this.measureItem.id ? this.url.edit : this.url.add
      const method = this.measureItem.id ? 'put' : 'post'

      httpAction(url, this.measureItem, method)
        .then(res => {
          if (res.success) {
            this.$message.success('保存成功')
            this.visible = false
            this.$emit('ok')
          } else {
            this.$message.error(res.message)
          }
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },

    handleCancel() {
      this.visible = false
    },

    copyMeasure() {
      this.$refs.measureCopy.show(this.deviceTypeId)
    },

    handleCopyItems(selectedId) {
      if (!selectedId) return
      getAction(this.url.list, { detailId: selectedId }).then(res => {
        if (res.success && res.result.length > 0) {
          const source = res.result[0]
          // 清理 ID，标记为新数据
          const newPoints = (source.points || []).map(p => ({
            dataPot: p.dataPot,
            maxValue: p.maxValue,
            minValue: p.minValue,
            unit: p.unit,
            key: Date.now() + Math.random(),
            detailId: this.detailId,
            editable: true,
            isNew: true,
          }))

          this.measureItem = {
            dataPot: source.dataPot,
            detailId: this.detailId,
            points: newPoints,
          }

          // 👇 关键：标记为“参照覆盖”模式
          if (this.dataVersion === 1) {
            this.dataVersion = 2
          }
        } else {
          this.$message.warning('所选检修项未配置测量项点')
        }
      })
    },
  },
}
</script>

<style scoped>
.editable-cell {
  margin: -5px 0;
}
.orange-btn {
  background-color: orange;
  border-color: orange;
  margin-left: 8px;
}
.orange-btn:hover {
  background-color: #f6cc7d;
  border-color: #f6cc7d;
}
</style>