<template>
  <!-- 基于 Element UI 新增和修改弹窗 -->
  <el-dialog
      :title="!dataForm.id ? '添加' : '修改'"
      :close-on-click-modal="false"
      :visible.sync="visible">
    <!-- 新增和修改表单 -->
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataSubmit()" label-width="120px">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="项目名称" prop="projectId">
          <el-select v-model="dataForm.projectId" placeholder="请选择项目名称" style="width: 100%" @change="handleProjectChange(dataForm.projectId)">
            <el-option
              v-for="project in projectList"
              :key="project.id"
              :label="project.projectName"
              :value="project.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="楼栋名称" prop="buildingId">
          <el-select v-model="dataForm.buildingId" placeholder="请选择楼栋名称" style="width: 100%" @change="handleBuildingChange(dataForm.buildingId)">
            <el-option
              v-for="building in buildingList"
              :key="building.id"
              :label="building.buildingNo"
              :value="building.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="设施名称" prop="facilityId">
          <el-select v-model="dataForm.facilityId" placeholder="请选择设施名称" style="width: 100%">
            <el-option
              v-for="facility in facilityList"
              :key="facility.id"
              :label="facility.facilityName"
              :value="facility.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="维保类型" prop="maintenanceType">
          <el-select v-model="dataForm.maintenanceType" placeholder="请选择维保类型" style="width: 100%">
            <el-option
              v-for="dict in dict.type.maintenance_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="维保周期" prop="cycleDays">
          <el-input-number v-model="dataForm.cycleDays" :min="1" :precision="0" placeholder="维保周期(天)" style="width: 100%"></el-input-number>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="下次执行时间" prop="nextExecTime">
          <el-date-picker v-model="dataForm.nextExecTime" type="datetime" placeholder="选择下次执行时间" style="width: 100%"></el-date-picker>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="执行部门" prop="executorDept">
          <el-input v-model="dataForm.executorDept" placeholder="执行部门"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-form-item label="维保内容" prop="maintenanceContent">
      <el-input v-model="dataForm.maintenanceContent" placeholder="维保内容" type="textarea" rows="4"></el-input>
    </el-form-item>
    <el-form-item label="备注" prop="remark">
      <el-input v-model="dataForm.remark" placeholder="备注" type="textarea" rows="4"></el-input>
    </el-form-item>
    <!-- 显示添加维保记录按钮 -->
    <el-form-item>
      <el-button type="success" @click="addMaintenanceRecord">添加维保记录</el-button>
    </el-form-item>
    </el-form>

    <!-- 维保记录列表 -->
    <div class="maintenance-records-container">
      <el-table :data="maintenanceRecords" style="width: 100%">
        <el-table-column prop="execTime" label="维保日期" width="180"></el-table-column>
        <el-table-column prop="executorId" label="执行人" width="120"></el-table-column>
        <el-table-column prop="executorDept" label="执行部门" width="150"></el-table-column>
        <el-table-column prop="content" label="维保内容" width="200"></el-table-column>
        <el-table-column prop="consumables" label="耗材使用" width="150"></el-table-column>
        <el-table-column prop="costAmount" label="维保费用" width="120">
          <template slot-scope="scope">
            {{ scope.row.costAmount || 0 }} 元
          </template>
        </el-table-column>
        <el-table-column prop="status" label="维保状态" width="120"></el-table-column>
        <el-table-column prop="result" label="维保结果" width="150"></el-table-column>
        <el-table-column prop="remark" label="备注" width="150"></el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="editMaintenanceRecord(scope.row.id)">{{ '修改' }}</el-button>
            <el-button type="text" size="small" @click="deleteMaintenanceRecord(scope.row.id, scope.$index)">{{ '删除' }}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataSubmit()">确定</el-button>
    </span>

    <!-- 维保记录弹窗 -->
    <add-or-update-record ref="addOrUpdateRecord" :planId="dataForm.id" @refreshDataList="getMaintenanceRecords" @saveMaintenanceRecord="saveMaintenanceRecord"></add-or-update-record>
  </el-dialog>
</template>

<script>
  import * as api from '@/api/pmfacilitymaintenanceplan.js'
  import * as apiByProject from '@/api/pmproject.js'
  import * as apiByBuilding from '@/api/pmbuilding.js'
  import * as apiByFacility from '@/api/pmfacility.js'
  import * as apiByRecord from '@/api/pmfacilitymaintenacerecord.js'
  import AddOrUpdateRecord from '../record/pmfacilitymaintenacerecord-add-and-update.vue'
  export default {
    components: {
      AddOrUpdateRecord
    },
    dicts: ['maintenance_type'],
    data () {
      return {
        visible: false,
        dataForm: {
          id: 0,
          facilityId: '' ,
          buildingId: '' ,
          projectId: '' ,
          maintenanceType: '' ,
          cycleDays: 0 ,
          nextExecTime: '' ,
          maintenanceContent: '' ,
          executorDept: '' ,
          remark: '' ,
        },
        projectList: [],
        buildingList: [],
        facilityList: [],
        maintenanceRecords: [],
        addOrUpdateRecordVisible: false,
        dataRule: {
          facilityId: [
            { required: true, message: '设施名称  为必填项', trigger: 'blur' }
          ],
          buildingId: [
            { required: true, message: '楼栋名称  为必填项', trigger: 'blur' }
          ],
          projectId: [
            { required: true, message: '项目名称  为必填项', trigger: 'blur' }
          ],
          maintenanceType: [
            { required: true, message: '维保类型  为必填项', trigger: 'blur' }
          ],
          cycleDays: [
            { required: true, message: '维保周期  为必填项', trigger: 'blur' }
          ],
          nextExecTime: [
            { required: true, message: '下次执行时间  为必填项', trigger: 'change' }
          ],
        }
      }
    },
    methods: {
      // 获取项目列表
      getProjectList() {
        apiByProject.pmprojectListByAllApi().then(res => {
          try {
            this.projectList = Array.isArray(res) ? res : (res.list || [])
          } catch (processingErr) {
            this.projectList = []
          }
        }).catch(err => {
          this.projectList = []
        })
      },
      // 获取楼栋列表
      getBuildingList(projectId) {
        const params = projectId ? { projectId } : {}
        apiByBuilding.pmbuildingListByAllApi(params).then(res => {
          try {
            this.buildingList = Array.isArray(res) ? res : (res.list || [])
          } catch (processingErr) {
            this.buildingList = []
          }
        }).catch(err => {
          this.buildingList = []
        })
      },
      // 获取设施列表
      getFacilityList(projectId, buildingId) {
        const params = {}
        if (projectId) params.projectId = projectId
        if (buildingId) params.buildingId = buildingId
        apiByFacility.pmfacilityListByAllApi(params).then(res => {
          try {
            this.facilityList = Array.isArray(res) ? res : (res.list || [])
          } catch (processingErr) {
            this.facilityList = []
          }
        }).catch(err => {
          this.facilityList = []
        })
      },
      // 项目选择变化处理
      handleProjectChange(projectId) {
        this.dataForm.buildingId = '' // 重置楼栋选择
        this.dataForm.facilityId = '' // 重置设施选择
        this.getBuildingList(projectId)
        this.getFacilityList(projectId, '') // 获取该项目下的所有设施
      },
      // 楼栋选择变化处理
      handleBuildingChange(buildingId) {
        this.dataForm.facilityId = '' // 重置设施选择
        this.getFacilityList(this.dataForm.projectId, buildingId) // 根据项目和楼栋获取设施
      },
      init (id) { // 初始化表单验证规则
        this.dataForm.id = id || 0
        this.visible = true
        // 获取项目列表
        this.getProjectList()
        this.$nextTick(function() {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            api.pmfacilitymaintenanceplanDetailApi(id).then(function(res) {
              this.dataForm = res;
              // 获取该项目下的楼栋列表
              this.getBuildingList(res.projectId)
              // 获取该项目和楼栋下的设施列表
              this.getFacilityList(res.projectId, res.buildingId)
              // 获取该计划的维保记录
              this.getMaintenanceRecords()
            }.bind(this))
          } else {
            // 新增计划时清空维保记录
            this.maintenanceRecords = []
          }
        }.bind(this))
      },
      // 获取维保记录列表
      getMaintenanceRecords() {
        if (!this.dataForm.id) return
        apiByRecord.pmfacilitymaintenacerecordListApi({
          planId: this.dataForm.id
        }).then(function(res) {
          try {
            this.maintenanceRecords = Array.isArray(res) ? res : (res.list || [])
          } catch (error) {
            this.maintenanceRecords = []
          }
        }.bind(this)).catch(function(err) {
          this.maintenanceRecords = []
        }.bind(this))
      },
      // 新增维保记录
      addMaintenanceRecord() {
        if (this.$refs.addOrUpdateRecord) {
          // 直接传递ID参数，由维保记录弹窗自己获取名称信息
          this.$refs.addOrUpdateRecord.init(0, this.dataForm.id, this.dataForm.facilityId, this.dataForm.buildingId, this.dataForm.projectId)
        }
      },
      // 编辑维保记录
      editMaintenanceRecord(id) {
        if (this.$refs.addOrUpdateRecord) {
          this.$refs.addOrUpdateRecord.init(id, this.dataForm.id)
        }
      },
      // 删除维保记录
      deleteMaintenanceRecord(id, index) {
        this.$confirm('确定要删除这条维保记录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (id) {
            // 已有ID的记录，调用API删除
            apiByRecord.pmfacilitymaintenacerecordDeleteApi([id]).then(() => {
              this.$message.success('删除成功')
              // 从列表中移除这条记录
              this.maintenanceRecords.splice(index, 1)
            }).catch(() => {
              this.$message.error('删除失败')
            })
          } else {
            // 还没有ID的新增记录，直接从列表中删除
            this.maintenanceRecords.splice(index, 1)
            this.$message.success('删除成功')
          }
        }).catch(() => {
          this.$message.info('已取消删除')
        })
      },
      // 保存维保记录（从维保记录弹窗接收）
      saveMaintenanceRecord(recordData) {
        if (!recordData) return

        // 检查是新增还是更新
        const existingIndex = this.maintenanceRecords.findIndex(record => record.id === recordData.id)

        if (existingIndex !== -1) {
          // 更新现有记录
          this.maintenanceRecords.splice(existingIndex, 1, recordData)
        } else {
          // 添加新记录
          this.maintenanceRecords.push(recordData)
        }
      },
      // 表单数据提交
      dataSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            // 创建一个包含维保记录的请求对象
            const requestData = {
              ...this.dataForm,
              pmFacilityMaintenaceRecordList: this.maintenanceRecords
            }

            if (this.dataForm.id) {
              api.pmfacilitymaintenanceplanUpdateApi(requestData).then(function(res) {
                this.$message.success('保存成功')
                this.visible = false
                this.$emit('refreshDataList')
              }.bind(this));
            } else {
              api.pmfacilitymaintenanceplanCreateApi(requestData).then(function(res) {
                this.$message.success('新增成功')
                this.visible = false
                this.$emit('refreshDataList')
              }.bind(this));
            }
          }
        })
      }
    }
  }
</script>
<style>
.maintenance-records-container {
  margin-top: 20px;
}

.no-data-tip {
  text-align: center;
  padding: 20px;
  color: #909399;
}
</style>
