<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" width="1000px" append-to-body :close-on-click-modal="false" @close="handleClose">
    <el-row :gutter="10" class="mb8" v-if="!readonly">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增明细</el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="itemList" border>
      <el-table-column label="分类" align="center" prop="category" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.procurement_item_category" :value="scope.row.category" />
        </template>
      </el-table-column>
      <el-table-column label="规格描述" align="center" prop="spec" :show-overflow-tooltip="true" min-width="200" />
      <el-table-column label="数量" align="center" prop="qty" width="120" />
      <el-table-column label="单位" align="center" prop="unit" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.material_unit || []" :value="scope.row.unit" />
        </template>
      </el-table-column>
      <el-table-column label="是否可重复使用" align="center" prop="isReusable" width="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.material_reusable" :value="String(scope.row.isReusable || '0')" />
        </template>
      </el-table-column>
      <el-table-column label="目标物资" align="center" prop="targetMaterialName" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" min-width="150" />
      <el-table-column label="操作" align="center" width="200" fixed="right" v-if="!readonly">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">关 闭</el-button>
    </div>

    <!-- 明细编辑对话框 -->
    <el-dialog :title="itemTitle" :visible.sync="itemOpen" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="itemForm" :model="itemForm" :rules="itemRules" label-width="120px">
        <el-form-item label="分类" prop="category">
          <el-select v-model="itemForm.category" placeholder="请选择分类" style="width: 100%" @change="handleCategoryChange">
            <el-option
              v-for="dict in (dict.type.procurement_item_category || [])"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="规格描述" prop="spec">
          <el-input 
            v-model="itemForm.spec" 
            type="textarea" 
            placeholder="请输入规格描述" 
            maxlength="500" 
            :rows="3"
            :disabled="!!itemForm.targetMaterialId"
          />
          <div style="color: #909399; font-size: 12px; margin-top: 5px;" v-if="itemForm.targetMaterialId">
            提示：已选择目标物资，规格描述已从物资信息中获取
          </div>
        </el-form-item>
        <el-form-item label="数量" prop="qty">
          <el-input-number v-model="itemForm.qty" :min="0" :precision="2" placeholder="请输入数量" style="width: 100%" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-select
            v-model="itemForm.unit"
            placeholder="请选择单位"
            filterable
            allow-create
            default-first-option
            style="width: 100%"
            :disabled="!!itemForm.targetMaterialId"
          >
            <el-option
              v-for="dict in (dict.type.material_unit || [])"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
          <div style="color: #909399; font-size: 12px; margin-top: 5px;" v-if="itemForm.targetMaterialId">
            提示：已选择目标物资，单位已从物资信息中获取
          </div>
        </el-form-item>
        <el-form-item label="是否可重复使用" prop="isReusable">
          <el-radio-group v-model="itemForm.isReusable" :disabled="!!itemForm.targetMaterialId">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
          <div style="color: #909399; font-size: 12px; margin-top: 5px;" v-if="itemForm.targetMaterialId">
            提示：已选择目标物资，此属性已从物资信息中获取
          </div>
        </el-form-item>
        <el-form-item label="目标物资" prop="targetMaterialId" v-if="itemForm.category === 'material' || !itemForm.category">
          <el-select
            v-model="itemForm.targetMaterialId"
            :placeholder="getTargetMaterialPlaceholder()"
            :disabled="itemForm.category !== 'material'"
            filterable
            clearable
            style="width: 100%"
            @focus="loadMaterialList"
            @change="handleTargetMaterialChange"
          >
            <el-option
              v-for="material in materialList"
              :key="material.id"
              :label="`${material.materialName} (${material.materialCode})`"
              :value="material.id"
            />
          </el-select>
          <div style="color: #909399; font-size: 12px; margin-top: 5px;" v-if="itemForm.category === 'material'">
            提示：选择已有物资则入库时只增加库存；不选择则入库时自动创建新物资
          </div>
          <div style="color: #909399; font-size: 12px; margin-top: 5px;" v-else>
            提示：此字段仅在分类为物资时可用
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="itemForm.remark" type="textarea" placeholder="请输入备注" maxlength="500" :rows="2" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitItemForm">确 定</el-button>
        <el-button @click="itemOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import {
  listProcurementItem,
  addProcurementItem,
  updateProcurementItem,
  delProcurementItem
} from '@/api/resource/procurement'
import { listMaterial, getMaterial } from '@/api/resource/material'

export default {
  name: 'ProcurementItemDialog',
  dicts: ['procurement_item_category', 'material_unit', 'material_reusable'],
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    procurementId: {
      type: Number,
      default: null
    },
    procurementTitle: {
      type: String,
      default: ''
    },
    readonly: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialogVisible: this.visible,
      loading: false,
      itemList: [],
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      itemOpen: false,
      itemTitle: '',
      itemForm: {},
      materialList: [],
      itemRules: {
        category: [{ required: true, message: '分类不能为空', trigger: 'change' }],
        qty: [{ required: true, message: '数量不能为空', trigger: 'blur' }]
      }
    }
  },
  computed: {
    title() {
      return `采购明细管理 - ${this.procurementTitle}`
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val
      if (val && this.procurementId) {
        this.getList()
      }
    },
    dialogVisible(val) {
      this.$emit('update:visible', val)
    }
  },
  methods: {
    /** 查询明细列表 */
    getList() {
      this.loading = true
      listProcurementItem(this.procurementId, this.queryParams).then(response => {
        this.itemList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 新增明细 */
    handleAdd() {
      this.resetItemForm()
      this.itemOpen = true
      this.itemTitle = '新增采购明细'
    },
    /** 分类变化处理 */
    handleCategoryChange(value) {
      // 如果选择的是物资分类，自动加载物资列表
      if (value === 'material') {
        this.loadMaterialList()
      } else {
        // 如果不是物资分类，清空目标物资ID
        this.itemForm.targetMaterialId = undefined
      }
    },
    /** 获取目标物资占位符文本 */
    getTargetMaterialPlaceholder() {
      if (this.itemForm.category === 'material') {
        return '请选择已有物资（不选择则入库时自动创建新物资）'
      } else {
        return '请先选择分类为物资后，再选择已有物资'
      }
    },
    /** 目标物资变化处理 */
    handleTargetMaterialChange(materialId) {
      if (materialId) {
        // 选择了目标物资，加载物资详情并填充规格描述和单位
        getMaterial(materialId).then(response => {
          const material = response.data
          if (material) {
            // 填充规格描述（优先使用spec，如果没有则使用materialName）
            this.itemForm.spec = material.spec || material.materialName || ''
            // 填充单位
            this.itemForm.unit = material.unit || ''
            // 如果物资有可重复使用属性，也同步
            if (material.reusable !== undefined) {
              this.itemForm.isReusable = material.reusable
            }
          }
        }).catch(() => {
          this.$modal.msgError('获取物资信息失败')
        })
      } else {
        // 清空目标物资，恢复规格描述和单位的可编辑状态（不清空值，让用户决定是否保留）
        // 这里不清空值，因为用户可能想保留之前输入的内容
      }
    },
    /** 加载物资列表 */
    loadMaterialList() {
      if (this.materialList.length > 0) {
        return // 已加载过，不重复加载
      }
      listMaterial({ pageNum: 1, pageSize: 1000 }).then(response => {
        this.materialList = response.rows || []
      }).catch(() => {
        this.materialList = []
      })
    },
    /** 编辑明细 */
    handleEdit(row) {
      this.resetItemForm()
      this.itemForm = {
        id: row.id,
        category: row.category,
        spec: row.spec,
        qty: row.qty,
        unit: row.unit,
        isReusable: row.isReusable || 0,
        targetMaterialId: row.targetMaterialId,
        remark: row.remark
      }
      this.itemOpen = true
      this.itemTitle = '编辑采购明细'
      // 如果是物资分类，加载物资列表
      if (row.category === 'material') {
        this.loadMaterialList()
      }
    },
    /** 删除明细 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除该采购明细？').then(() => {
        return delProcurementItem(this.procurementId, row.id)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 提交明细表单 */
    submitItemForm() {
      this.$refs['itemForm'].validate(valid => {
        if (valid) {
          if (this.itemForm.id != undefined) {
            // 编辑时确保包含 procurementId
            const formData = {
              ...this.itemForm,
              procurementId: this.procurementId
            }
            updateProcurementItem(this.procurementId, this.itemForm.id, formData).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.itemOpen = false
              this.getList()
              this.$emit('success')
            })
          } else {
            // 新增时确保包含 procurementId，满足后端验证要求
            const formData = {
              ...this.itemForm,
              procurementId: this.procurementId
            }
            addProcurementItem(this.procurementId, formData).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.itemOpen = false
              this.getList()
              this.$emit('success')
            })
          }
        }
      })
    },
    /** 重置明细表单 */
    resetItemForm() {
      this.itemForm = {
        id: undefined,
        category: undefined,
        spec: undefined,
        qty: undefined,
        unit: undefined,
        isReusable: 0,
        targetMaterialId: undefined,
        remark: undefined
      }
      this.resetForm('itemForm')
    },
    /** 关闭对话框 */
    handleClose() {
      this.itemList = []
      this.total = 0
      this.queryParams = {
        pageNum: 1,
        pageSize: 10
      }
    }
  }
}
</script>