<template>
  <div class="app-container">
    <!-- 列表 -->
    <el-card>
      <el-row class="mb8" :gutter="10" justify="end">
        <el-col :span="4">
          <span style="font-size: 20px; font-weight: 800">申请列表</span>
        </el-col>
        <el-col v-if="!routerParams.isView" :span="20" style="display: flex; justify-content: flex-end">
          <el-button type="primary" @click="handleNumDialog">添加</el-button>
          <el-button type="primary" @click="submit">确认申请</el-button>
        </el-col>
      </el-row>

      <el-table
          v-loading="isLoading"
          :data="tableList"
          highlight-current-row
          border
          stripe
          :max-height="650"
          style="width: 100%"
      >
        <!-- 序号列 -->
        <el-table-column
            type="index"
            width="55"
            label="序号"
            align="center"
            :index="(index) => (queryParams.pageNum - 1) * queryParams.pageSize + index + 1"
        />

        <!-- 动态列 -->
        <el-table-column
            v-for="(column, index) in tableColumns"
            :key="index"
            :label="column.label"
            :prop="column.prop"
            :width="column.width"
            :min-width="column.minWidth"
            align="center"
            show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span v-if="!column.render">{{ scope.row[column.prop] }}</span>
            <component
                v-else
                :is="{ render: (h) => column.render(h, { row: scope.row }) }"
            />
          </template>
        </el-table-column>

        <el-table-column label="附件" align="center" width="90" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div style="display: flex; align-items: center; justify-content: space-between">
              <el-upload
                  ref="upload"
                  :limit="3"
                  :headers="upload.headers"
                  :action="upload.url"
                  :show-file-list="false"
                  accept=".png, .jpg, .jpeg, .pdf, .doc, .docx"
                  :on-success="handleFileSuccess2"
                  :auto-upload="true"
              >
                <el-button size="mini" type="text" @click="beforeFileUpload(scope.row)">上传</el-button>
              </el-upload>
              <el-button
                  size="mini"
                  type="text"
                  @click="picturePreview(scope.row)"
                  v-if="scope.row.bmFileInfos && scope.row.bmFileInfos.length > 0"
              >
                查看
              </el-button>
            </div>
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column label="操作" align="center" width="80px" v-if="!routerParams.isView">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" style="color: red">
              删除
            </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"
      />
    </el-card>

    <!-- 插入选择工具的弹窗 -->
    <SelectToolDialog ref="addNum" @confirm="handleAddFromDialog" />

    <!-- 图片查看弹窗 -->
    <el-dialog :visible.sync="dialogVisible" width="500px" height="500px">
      <img width="100%" height="500px" :src="dialogImageUrl" />
    </el-dialog>
  </div>
</template>

<script>
import { getListByApplyIdApi, deleteToolApi, updateToolApplyApi } from '@/api/toolsManage'
import SelectToolDialog from './SelectToolDialog.vue'
import { getToken } from "@/utils/auth";
import {addRepairData} from "@/api/equipmentRepair";

export default {
  name: 'AddEditTools',
  components: { SelectToolDialog },
  data() {
    return {
      routerParams: {},
      isLoading: false,
      showSearch: true,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        parentTypeName: null,
        typeName: null,
        manageType: null,
        applyId: null,
      },
      typeList: [
        { label: '数量管理', value: '0' },
        { label: '编码管理', value: '1' },
      ],
      upload: {
        headers: { Authorization: 'Bearer ' + getToken() },
        url: process.env.VUE_APP_BASE_API + '/file/upload'
      },
      currentRowId: null,
      dialogImageUrl: '',
      dialogVisible: false,
      tempMaCodeList: [],
      total: 0,
      tableList: [],
      tableColumns: [
        { label: '分类', prop: 'type', width: 75 },
        { label: '类目', prop: 'groupName' },
        { label: '名称', prop: 'typeName' },
        { label: '规格型号', prop: 'typeModelName' },
        {
          label: '管理模式',
          prop: 'manageType',
          width: '80',
          render: (h, { row }) => h('span', {}, row.manageType === '0' ? '数量管理' : '编码管理')
        },
        { label: '设备编码', prop: 'code' },
        { label: '维修数量', prop: 'repairNum', width: 80 },
        {
          label: '维修是否合格',
          prop: 'isScrap',
          width: '120',
          render: (h, { row }) =>
              h('el-select', {
                props: { value: row.isScrap || '' },
                on: {
                  input: val => {
                    this.$set(row, 'isScrap', val)

                    // === 新增：处理退役原因禁用/清空 ===
                    if (val === '0') {
                      // 选“是” → 清空并禁用退役原因
                      this.$set(row, 'reasonVal', '')
                      this.$set(row, 'reasonDisabled', true)
                    } else {
                      // 选“否” → 允许填写
                      this.$set(row, 'reasonDisabled', false)
                    }
                  }
                },
                style: 'width: 90px'
              }, [
                h('el-option', { props: { label: '是', value: '0' } }),
                h('el-option', { props: { label: '否', value: '1' } }),
              ])
        },
        {
          label: '维修日期',
          prop: 'repairTime',
          width: '180',
          render: (h, { row }) => h('el-date-picker', {
            props: {
              value: row.repairTime,
              type: 'date',
              placeholder: '选择日期',
              format: 'yyyy-MM-dd',
              'value-format': 'yyyy-MM-dd'
            },
            on: { input: val => this.$set(row, 'repairTime', val) },
            style: 'width: 140px'
          })
        },
        {
          label: '退役原因',
          prop: 'reasonVal',
          width: '120',
          render: (h, { row }) =>
              h('el-select', {
                props: {
                  value: row.reasonVal || '',
                  disabled: row.reasonDisabled === true   // ⭐ 根据维修是否合格禁用
                },
                on: { input: val => this.$set(row, 'reasonVal', val) },
                style: 'width: 90px'
              }, [
                h('el-option', { props: { label: '人为', value: '人为' } }),
                h('el-option', { props: { label: '自然', value: '自然' } })
              ])
        },
      ]
    }
  },
  created() {
    this.routerParams = this.$route.query
    let title = '新增维修'
    if (this.routerParams.isView) title = '查看工具'
    else if (this.routerParams.isEdit) title = '编辑工具'

    this.queryParams.applyId = this.routerParams.applyId || ''
    const obj = Object.assign({}, this.$route, { title })
    this.$tab.updatePage(obj)
    this.getList()
  },
  methods: {
    // 文件上传成功处理-编码弹窗上传
    // 文件上传成功处理
    handleFileSuccess2(response, file, fileList) {
      console.log('文件上传成功', response)
      if (response.code === 200) {
        let obj = {
          fileName: response.data.name,
          fileUrl: response.data.url
        }

        // 通过行ID找到对应的行
        if (this.currentRowId !== null) {
          // 在表格数据中查找对应的行
          const targetRow = this.tableList.find(item => item.keyId === this.currentRowId)
          if (targetRow) {
            // 如果当前行还没有 bmFileInfos 数组，先创建
            if (!targetRow.bmFileInfos) {
              this.$set(targetRow, 'bmFileInfos', [])
            }
            // 将文件对象添加到 bmFileInfos 中
            targetRow.bmFileInfos.push(obj)
            this.$message.success('文件上传成功')

            // 强制更新视图
            this.$forceUpdate()
          } else {
            this.$message.warning('未找到对应的行数据')
          }
          // 重置 currentRowId
          this.currentRowId = null
        } else {
          this.$message.warning('未找到对应的行数据')
        }
      } else {
        this.$message.error('文件上传失败：' + response.msg)
      }
    },

    // 上传前记录行ID
    beforeFileUpload(row) {
      this.currentRowId = row.keyId
      console.log('记录当前行ID:', row.keyId)
    },

    // 图片预览方法
    picturePreview(row) {
      console.log('预览行数据:', row)
      console.log('预览附件:', row.bmFileInfos)
      if (row.bmFileInfos && row.bmFileInfos.length > 0) {
        // 显示最新的文件（数组最后一个）
        const file = row.bmFileInfos[row.bmFileInfos.length - 1]
        console.log('预览文件:', file)
        this.dialogImageUrl = file.fileUrl.replaceAll('#', '%23')
        const parts = file.fileName.split('.')
        const extension = parts.pop().toLowerCase()
        if (['doc', 'docx', 'pdf'].includes(extension)) {
          const windowName = file.fileName
          window.open(file.fileUrl, windowName)
        } else {
          this.dialogVisible = true
        }
      } else {
        this.$message.warning('该行没有附件')
      }
    },
    handleQuery() { this.queryParams.pageNum = 1; this.getList() },
    handleReset() { this.queryParams.pageNum = 1; this.queryParams.pageSize = 10; this.$refs.queryForm.resetFields(); this.getList() },
    async getList() {
      this.isLoading = true
      try {
        const res = await getListByApplyIdApi({ ...this.queryParams })
        this.tableList = res.rows || []
        this.total = res.total || 0
      } finally { this.isLoading = false }
    },
    handleDelete(row) {
      this.$confirm('确定删除该条数据?', '提示', { type: 'warning' }).then(() => {
        this.tableList = this.tableList.filter(item => item.keyId !== row.keyId)
        if (this.$refs.addNum) {
          const dialog = this.$refs.addNum
          dialog.selectedMap.delete(row.keyId)
          dialog.tableList = dialog.tableList.filter(item => item.keyId !== row.keyId)
          dialog.$nextTick(() => dialog.restoreSelection())
        }
        this.total = this.tableList.length
        this.$message.success('删除成功')
      })
    },
    handleNumDialog() { if (this.$refs.addNum) this.$refs.addNum.openDialog(this.queryParams.applyId, this.tableList) },
    handleAddFromDialog(rows) {
      if (!rows || rows.length === 0) return
      const existingKeys = new Set(this.tableList.map(item => item.keyId))
      const newRows = rows.filter(item => !existingKeys.has(item.keyId))
      newRows.forEach(item => {
        if (item.manageMode === '编码管理') item.repairNum = 1
        else if (!item.repairNum) item.repairNum = 1
        if (this.$refs.addNum && this.$refs.addNum.selectedMap) this.$refs.addNum.selectedMap.set(item.keyId, item)
      })
      this.tableList = [...this.tableList, ...newRows]
      this.total = this.tableList.length
    },
    submit() {
      this.$confirm('是否确定提交申请?', '提示', { type: 'warning' }).then(async () => {
        // 校验：所有行必须填写合格字段、维修日期等（可选）
        for (const row of this.tableList) {
          if (!row.repairNum || row.repairNum === 0) {
            return this.$message.warning(`【${row.typeName}】维修数量不能为空或为0`)
          }
          if (!row.isScrap) {
            return this.$message.warning(`【${row.typeName}】请选择维修是否合格`)
          }
          if (!row.repairTime) {
            return this.$message.warning(`【${row.typeName}】请选择维修日期`)
          }
          // 只有维修不合格时才必须填写退役原因
          if (row.isScrap === '1' && !row.reasonVal) {
            return this.$message.warning(`【${row.typeName}】请选择退役原因`)
          }

        }

        const payload = {
          toBeRepairList: this.tableList
        }

        console.log("提交内容：", payload)

        this.isLoading = true
        try {
          const res = await addRepairData(payload)
          if (res.code ==200){
            this.$message.success('操作成功!')
            this.$tab.closeOpenPage({ path: './repairList' })
          } else {
            this.$message.error(res.msg || '申请失败')
          }
        } catch (error) {
          this.$message.error('申请失败')
        }finally {
          this.isLoading = false
        }
      })
    },
  }
}
</script>
