<template>
  <div>
    <el-dialog
      :title="!dataForm.id ? '新建' : '编辑'"
      :visible.sync="dialogVisible"
      width="1200px"
      :close-on-click-modal="false"
      @close="handleClose"
    >
    <el-form ref="formRef" :model="dataForm" :rules="dataRule" size="small" label-width="120px" label-position="right">
      <template v-if="!loading">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="设备名称" prop="eqCode">
              <el-input v-model="dataForm.eqName" placeholder="请选择设备" clearable readonly :disabled="!!dataForm.id" @click.native="selectEquipment">
                <i slot="suffix" class="el-input__icon el-icon-search" style="cursor: pointer;"></i>
              </el-input>
            </el-form-item>
          </el-col>
           <el-col :span="8">
            <el-form-item label="类型" prop="mainType">
              <JnpfSelect v-model="dataForm.mainType" placeholder="请选择类型" :options="mainTypeOptions" :disabled="!!dataForm.id" :props="mainTypeProps" clearable :style="{ width: '100%' }">
              </JnpfSelect>
            </el-form-item>
          </el-col>
            <el-col :span="8">
            <el-form-item label="方案名称" prop="mainName">
              <JnpfInput v-model="dataForm.mainName" placeholder="请输入方案名称" clearable>
              </JnpfInput>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
           <el-col :span="8">
            <el-form-item label="周期" prop="cycleUnit">
              <JnpfSelect v-model="dataForm.cycleUnit" placeholder="请选择周期单位" :options="cycleUnitOptions" :props="cycleUnitProps" clearable :style="{ width: '100%' }">
              </JnpfSelect>
            </el-form-item>
          </el-col>
             <el-col :span="8">
            <el-form-item label="下次执行时间" prop="planStartDtime">
              <JnpfDatePicker v-model="dataForm.planStartDtime"
                              placeholder="请选择下次执行时间"
                              clearable
                              :style='{ "width": "100%" }'
                              format="yyyy-MM-dd HH:mm"
                              type="datetime">
              </JnpfDatePicker>
            </el-form-item>
          </el-col>
        <el-col :span="8">
            <el-form-item label="启用状态" prop="enabledStatus">
              <JnpfSelect v-model="dataForm.enabledStatus" placeholder="请选择启用状态" :options="enabledStatusOptions" :props="enabledStatusProps" :style="{ width: '100%' }">
              </JnpfSelect>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="责任部门" prop="deptId">
              <el-select v-model="dataForm.deptId" placeholder="请选择责任部门" clearable ref="deptSelect"
                          :style="{ width: '100%' }" @clear="deptIdLabel = ''">
                <el-option :value="dataForm.deptId" :label="deptIdLabel" style="height: auto; padding: 0;">
                  <el-tree
                    :data="deptOptions"
                    :props="{ children: 'children', label: 'name' }"
                    @node-click="handleDeptSelect"
                    node-key="id"
                    default-expand-all
                    :expand-on-click-node="true">
                  </el-tree>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="责任人" prop="userId">
              <JnpfSelect v-model="dataForm.userId" placeholder="请选择责任人" filterable clearable
                          :style="{ width: '100%' }" :options="userIdOptions"
                          :props="userIdProps" @change="handleUserChange">
              </JnpfSelect>
            </el-form-item>
          </el-col>
            <el-col :span="8">
            <el-form-item label="负责岗位" prop="mainPost">
              <JnpfInput v-model="dataForm.mainPost" placeholder="请输入负责岗位" clearable>
              </JnpfInput>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <JnpfTextarea v-model="dataForm.remark" placeholder="请输入备注" :autoSize="{ minRows: 2, maxRows: 2 }" type="textarea">
              </JnpfTextarea>
            </el-form-item>
          </el-col>
        </el-row>
        <div style="display: flex; align-items: center; margin-bottom: 10px;">
              <span style="font-weight: bold;">项目信息</span>
              <el-button type="primary" size="small" icon="el-icon-plus" @click="addItem" style="margin-left: 10px;">新增</el-button>
        </div>
        <el-row :gutter="20">
          <el-col :span="24" style="overflow-x: hidden;">
            <el-table :data="dataForm.itemList" border :show-header="true" style="width: 100%; table-layout: fixed;">
              <el-table-column type="index" label="序号" width="60" align="center"/>
              <el-table-column prop="itemName" label="*保养项目" min-width="150" align="center">
                <template slot-scope="scope">
                  <JnpfInput v-model="scope.row.itemName" clearable>
                  </JnpfInput>
                </template>
              </el-table-column>
              <el-table-column prop="checkPart" label="*检查/保养部位" min-width="150" align="center">
                <template slot-scope="scope">
                  <JnpfInput v-model="scope.row.checkPart" clearable>
                  </JnpfInput>
                </template>
              </el-table-column>
              <el-table-column prop="checkMethod" label="*检查/保养方法" min-width="150" align="center">
                <template slot-scope="scope">
                  <JnpfInput v-model="scope.row.checkMethod" clearable>
                  </JnpfInput>
                </template>
              </el-table-column>
              <el-table-column prop="qualifiedStand" label="标准/要求" min-width="150" align="center">
                <template slot-scope="scope">
                  <JnpfInput v-model="scope.row.qualifiedStand" clearable>
                  </JnpfInput>
                </template>
              </el-table-column>
              <el-table-column prop="checkTool" label="所需工具" min-width="120" align="center">
                <template slot-scope="scope">
                  <JnpfInput v-model="scope.row.checkTool" clearable>
                  </JnpfInput>
                </template>
              </el-table-column>
              <el-table-column prop="seqNo" label="*项目序号" width="100" align="center">
                <template slot-scope="scope">
                  <JnpfInput v-model="scope.row.seqNo" type="number" :step="1">
                  </JnpfInput>
                </template>
              </el-table-column>
              <el-table-column prop="remark" label="备注" min-width="170" align="center">
                <template slot-scope="scope">
                  <JnpfInput v-model="scope.row.remark" clearable>
                  </JnpfInput>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80" align="center">
                <template slot-scope="scope">
                  <el-button type="text" class="JNPF-table-delBtn" @click="deleteItem(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </template>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="dataFormSubmit()" :loading="btnLoading">保 存</el-button>
      <el-button @click="handleClose">取 消</el-button>
    </div>

  </el-dialog>
  <EquipmentSelect v-if="equipmentSelectVisible" :visible.sync="equipmentSelectVisible" @select="handleEquipmentSelect"/>
  </div>
</template>

<script>
import {createEqMainConfig, deleteEqMainConfig, getDeptList, getEqMainConfigInfo, getUserList, updateEqMainConfig} from './api'
import EquipmentSelect from '../equipment/select.vue'
import {enabledStatusOptions, dictProps, mainTypeOptions, cycleUnitOptions} from '../common/dict'
import { getLabel } from '../equipment/equipment'

export default {
  components: {
    EquipmentSelect
  },
  data() {
    return {
      dialogVisible: false,
      loading: false,
      btnLoading: false,
      equipmentSelectVisible: false,
      dataForm: {
        id: '',
        eqId: undefined,
        eqCode: undefined,
        eqName: undefined,
        mainName: undefined,
        mainType: undefined,
        cycleUnit: undefined,
        planStartDtime: undefined,
        deptId: undefined,
        deptName: undefined,
        userId: undefined,
        userName: undefined,
        mainPost: undefined,
        enabledStatus: "1",
        remark: undefined,
        itemList: []
      },
      dataRule: {
        eqCode: [
          {required: true, message: '请选择设备', trigger: 'change'},
        ],
        mainName: [
          {required: true, message: '请输入方案名称', trigger: 'blur'},
        ],
        mainType: [
          {required: true, message: '请选择类型', trigger: 'change'},
        ],
      },
      deptOptions: [],
      userIdOptions: [],
      userIdProps: { 'label': 'realName', 'value': 'id' },
      deptIdLabel: '',
      mainTypeOptions: mainTypeOptions,
      mainTypeProps: dictProps,
      cycleUnitOptions: cycleUnitOptions,
      cycleUnitProps: dictProps,
      enabledStatusOptions: enabledStatusOptions,
      enabledStatusProps: dictProps
    }
  },
  methods: {
    init(id) {
      this.dialogVisible = true
      this.loading = true
      // 重置表单数据
      this.resetForm()
      this.dataForm.id = id || ''
      this.loadDeptList().then(() => {
        if (id) {
          this.getInfo()
        } else {
          this.loading = false
        }
      })
    },
    resetForm() {
      this.dataForm = {
        id: '',
        eqId: undefined,
        eqCode: undefined,
        eqName: undefined,
        mainName: undefined,
        mainType: undefined,
        cycleUnit: undefined,
        planStartDtime: undefined,
        deptId: undefined,
        deptName: undefined,
        userId: undefined,
        userName: undefined,
        mainPost: undefined,
        enabledStatus: "1",
        remark: undefined,
        itemList: []
      }
      this.deptIdLabel = ''
      this.userIdOptions = []
    },
    getInfo() {
      getEqMainConfigInfo(this.dataForm.id).then((res) => {
        const data = res.data
        // 逐个赋值，保持响应式
        Object.keys(data).forEach(key => {
          if (key !== 'itemList') {
            if (key === 'enabledStatus') {
              this.dataForm[key] = String(data[key])
            } else {
              this.dataForm[key] = data[key]
            }
          }
        })
        // 处理 itemList，保持响应式数组
        if (data.itemList && Array.isArray(data.itemList)) {
          this.dataForm.itemList = [...data.itemList]
        } else {
          this.dataForm.itemList = []
        }
        // 设置责任部门名称
        if (this.dataForm.deptId) {
          this.deptIdLabel = this.findDeptNameById(this.dataForm.deptId, this.deptOptions)
          // 加载该部门下的用户
          getUserList(this.dataForm.deptId).then((res) => {
            this.userIdOptions = res.data || []
            // 设置责任人名称
            if (this.dataForm.userId) {
              const user = this.userIdOptions.find(item => String(item.id) === String(this.dataForm.userId))
              if (user) {
                this.dataForm.userName = user.realName
              }
            }
          })
        }
        this.loading = false
      }).catch((err) => {
        this.loading = false
        this.dialogVisible = false
        this.$message({
          type: 'error',
          message: err.message || '获取数据失败'
        })
      })
    },
    loadDeptList() {
      return new Promise((resolve) => {
        getDeptList().then((res) => {
          let data = res.data || []
          this.deptOptions = this.buildTree(data)
          resolve()
        }).catch(() => {
          resolve()
        })
      })
    },
    buildTree(list) {
      if (!list || !list.length) return []
      const tree = []
      const map = {}
      list.forEach(item => {
        map[item.id] = { ...item, children: [] }
      })
      list.forEach(item => {
        if (item.parentId && map[item.parentId]) {
          map[item.parentId].children.push(map[item.id])
        } else {
          tree.push(map[item.id])
        }
      })
      return tree
    },
    handleDeptSelect(data) {
      this.dataForm.deptId = String(data.id)
      this.deptIdLabel = data.name
      this.dataForm.deptName = data.name
      if (this.$refs.deptSelect) {
        this.$refs.deptSelect.visible = false
      }
      // 加载该部门下的用户
      this.userIdOptions = []
      this.dataForm.userId = undefined
      this.dataForm.userName = undefined
      if (data.id) {
        getUserList(data.id).then((res) => {
          this.userIdOptions = res.data || []
        })
      }
    },
    handleUserChange(val) {
      this.dataForm.userId = val
      const user = this.userIdOptions.find(item => String(item.id) === String(val))
      if (user) {
        this.dataForm.userName = user.realName
      } else {
        this.dataForm.userName = undefined
      }
    },
    findDeptNameById(id, tree) {
      for (const item of tree) {
        if (String(item.id) === String(id)) {
          return item.name
        }
        if (item.children && item.children.length > 0) {
          const found = this.findDeptNameById(id, item.children)
          if (found) {
            return found
          }
        }
      }
      return ''
    },
    selectEquipment() {
      this.equipmentSelectVisible = true
    },
    handleEquipmentSelect(data) {
      this.dataForm.eqId = data.eqId
      this.dataForm.eqCode = data.eqCode
      this.dataForm.eqName = data.eqName
      this.equipmentSelectVisible = false
    },
    addItem() {
      this.dataForm.itemList = [...this.dataForm.itemList, {
        id: '',
        itemName: undefined,
        checkPart: undefined,
        checkMethod: undefined,
        qualifiedStand: undefined,
        checkTool: undefined,
        seqNo: undefined,
        enabledStatus: 1,
        remark: undefined
      }]
    },
    deleteItem(index) {
      this.dataForm.itemList = this.dataForm.itemList.filter((_, i) => i !== index)
    },
    dataFormSubmit() {
      // 验证表格行数据
      if (!this.validateItemList()) {
        return
      }
      this.$refs.formRef.validate((valid) => {
        if (!valid) {
          return
        }
        this.btnLoading = true
        if (this.dataForm.id) {
          updateEqMainConfig(this.dataForm.id, this.dataForm).then(() => {
            this.$message.success('修改成功')
            this.dialogVisible = false
            this.btnLoading = false
            this.$emit('refresh')
          }).catch(() => {
            this.btnLoading = false
          })
        } else {
          createEqMainConfig(this.dataForm).then(() => {
            this.$message.success('新增成功')
            this.dialogVisible = false
            this.btnLoading = false
            this.$emit('refresh')
          }).catch(() => {
            this.btnLoading = false
          })
        }
      })
    },
    validateItemList() {
      // 检查非空
      for (let i = 0; i < this.dataForm.itemList.length; i++) {
        const item = this.dataForm.itemList[i]
        if (!item.itemName || item.itemName.trim() === '') {
          this.$message.warning(`第${i + 1}行保养项目不能为空`)
          return false
        }
        if (!item.checkPart || item.checkPart.trim() === '') {
          this.$message.warning(`第${i + 1}行检查/保养部位不能为空`)
          return false
        }
        if (!item.checkMethod || item.checkMethod.trim() === '') {
          this.$message.warning(`第${i + 1}行检查/保养方法不能为空`)
          return false
        }
        if (!item.seqNo && item.seqNo !== 0) {
          this.$message.warning(`第${i + 1}行项目序号不能为空`)
          return false
        }
      }
      // 检查保养项目重复
      const itemNameMap = {}
      for (let i = 0; i < this.dataForm.itemList.length; i++) {
        const itemName = this.dataForm.itemList[i].itemName.trim()
        if (itemNameMap[itemName]) {
          this.$message.warning('保养项目存在重复数据，请确认！')
          return false
        }
        itemNameMap[itemName] = true
      }
      return true
    },
    handleClose() {
      this.dialogVisible = false
      this.$emit('refresh',true)
    }
  },
  mounted() {
    // 由父组件调用 init() 方法初始化，不自动显示弹窗
  }
}
</script>
