<template>
  <div class="app-container design-report-page">
    <el-card>
      <div class="search-container" @keyup.enter="searchTable">
        <span class="show-text">任务ID:</span>
        <el-input v-model="searchForm.did" clearable size="small" style="width: 90px; margin-right: 8px" />
        <span class="show-text">项目号:</span>
        <el-select
          v-model="searchForm.projectNo"
          clearable
          filterable
          remote
          :remote-method="queryProjects"
          size="small"
          style="width: 170px; margin-right: 8px"
          @clear="loadDefaultProjectOptions"
          @visible-change="handleProjectVisibleChange"
        >
          <el-option
            v-for="item in projectOptions"
            :key="item.项目号"
            :label="formatProjectLabel(item)"
            :value="item.项目号"
          />
        </el-select>
        <span class="show-text">物料编码:</span>
        <el-select
          v-model="searchForm.itemCode"
          clearable
          filterable
          remote
          :remote-method="queryMaterialOptions"
          size="small"
          style="width: 190px; margin-right: 8px"
        >
          <el-option
            v-for="item in materialOptions"
            :key="item.物料编码"
            :label="formatMaterialLabel(item)"
            :value="item.物料编码"
          />
        </el-select>
        <span class="show-text">图号:</span>
        <el-input v-model="searchForm.drawingNo" clearable size="small" style="width: 120px; margin-right: 8px" />
        <span class="show-text">父件编码:</span>
        <el-select
          v-model="searchForm.parentItemCode"
          clearable
          filterable
          remote
          :remote-method="queryParentMaterialOptions"
          size="small"
          style="width: 190px; margin-right: 8px"
        >
          <el-option
            v-for="item in parentMaterialOptions"
            :key="item.物料编码"
            :label="formatMaterialLabel(item)"
            :value="item.物料编码"
          />
        </el-select>
        <span class="show-text">类别:</span>
        <el-input v-model="searchForm.category" clearable size="small" style="width: 120px; margin-right: 8px" />
        <span class="show-text">状态:</span>
        <el-select v-model="searchForm.status" clearable size="small" style="width: 110px; margin-right: 8px">
          <el-option label="全部" value="全部" />
          <el-option label="待开始" value="待开始" />
          <el-option label="执行中" value="执行中" />
          <el-option label="已结束" value="已结束" />
          <el-option label="已完成" value="已完成" />
        </el-select>
        <el-button :loading="loading" icon="el-icon-search" plain size="small" type="primary" @click="searchTable">查询</el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        border
        height="74vh"
        highlight-current-row
        size="mini"
        style="width: 100%; margin-top: 12px"
      >
        <el-table-column align="center" fixed label="DID" prop="DID" width="70" />
        <el-table-column align="center" fixed label="状态" prop="单据状态" width="90">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.单据状态)" size="mini">{{ scope.row.单据状态 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="left" label="项目号" prop="项目号" width="120" show-overflow-tooltip />
        <el-table-column align="left" label="物料编码" prop="物料编码" width="170" show-overflow-tooltip />
        <el-table-column align="left" label="物料名称" prop="物料名称" width="180" show-overflow-tooltip />
        <el-table-column align="left" label="图号" prop="图号" width="120" show-overflow-tooltip />
        <el-table-column align="left" label="类别" prop="类别" width="120" show-overflow-tooltip />
        <el-table-column align="left" label="任务描述" prop="任务描述" width="220" show-overflow-tooltip />
        <el-table-column align="left" label="指派对象" prop="指派对象" width="180" show-overflow-tooltip />
        <el-table-column align="center" label="预计开始" prop="预计开始时间" width="150" />
        <el-table-column align="center" label="预计结束" prop="预计结束时间" width="150" />
        <el-table-column align="center" label="报工次数" prop="报工次数" width="90" />
        <el-table-column align="center" label="未结束" prop="未结束报工数" width="80" />
        <el-table-column align="left" label="未结束人员" prop="未结束报工人员" width="150" show-overflow-tooltip />
        <el-table-column align="center" label="最后开始" prop="最后开始时间" width="150" />
        <el-table-column align="center" label="最后结束" prop="最后结束时间" width="150" />
        <el-table-column align="left" label="设计要求" prop="设计要求" width="220" show-overflow-tooltip />
        <el-table-column align="center" fixed="right" label="操作" width="210">
          <template slot-scope="scope">
            <div class="design-action-buttons">
              <el-button type="text" size="mini" :disabled="!canStart(scope.row)" @click="startTask(scope.row)">开始</el-button>
              <el-button type="text" size="mini" :disabled="!canEnd(scope.row)" @click="endTask(scope.row)">结束</el-button>
              <el-button type="text" size="mini" :disabled="!canComplete(scope.row)" @click="completeTask(scope.row)">完成</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      :visible.sync="endDialogVisible"
      title="结束报工"
      width="620px"
      center
      :close-on-click-modal="false"
    >
      <el-form :model="endForm" label-width="100px" size="small">
        <el-form-item label="DID">
          <el-input v-model="endForm.DID" disabled />
        </el-form-item>
        <el-form-item label="物料编码">
          <el-input v-model="endForm.物料编码" disabled />
        </el-form-item>
        <el-form-item label="物料名称">
          <el-input v-model="endForm.物料名称" disabled />
        </el-form-item>
        <el-form-item label="任务描述">
          <el-input v-model="endForm.任务描述" type="textarea" :rows="2" disabled />
        </el-form-item>
        <el-form-item label="进度说明">
          <el-input
            v-model="endForm.进度说明"
            type="textarea"
            :rows="4"
            maxlength="500"
            show-word-limit
            placeholder="请输入本次报工进度说明"
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="endDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="actionLoading" @click="confirmEndTask">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'DesignReportWork',
  data() {
    return {
      loading: false,
      actionLoading: false,
      endDialogVisible: false,
      tableData: [],
      projectOptions: [],
      materialOptions: [],
      parentMaterialOptions: [],
      endForm: {
        DID: '',
        物料编码: '',
        物料名称: '',
        任务描述: '',
        进度说明: ''
      },
      searchForm: {
        did: '',
        projectNo: '',
        itemCode: '',
        drawingNo: '',
        parentItemCode: '',
        category: '',
        status: ''
      }
    }
  },
  created() {
    this.loadDefaultProjectOptions()
    this.loadDefaultMaterialOptions()
    this.searchTable()
  },
  methods: {
    loadDefaultProjectOptions() {
      this.queryProjects('')
    },
    loadDefaultMaterialOptions() {
      this.queryMaterialOptions('')
      this.queryParentMaterialOptions('')
    },
    handleProjectVisibleChange(visible) {
      if (visible && this.projectOptions.length === 0) {
        this.loadDefaultProjectOptions()
      }
    },
    buildSearchParams() {
      return [
        ['DID', this.searchForm.did || 0],
        ['项目号', this.searchForm.projectNo || ''],
        ['物料编码', this.searchForm.itemCode || ''],
        ['图号', this.searchForm.drawingNo || ''],
        ['类别', this.searchForm.category || ''],
        ['关联父件物料编码', this.searchForm.parentItemCode || ''],
        ['预计开始时间_Start', ''],
        ['预计开始时间_End', ''],
        ['预计结束时间_Start', ''],
        ['预计结束时间_End', ''],
        ['单据状态', this.searchForm.status || ''],
        ['当前操作人ID', this.currentUserId()],
        ['当前操作人', this.currentUserName()]
      ]
    },
    async searchTable() {
      this.loading = true
      const data = this.CreateData('11', '设计报工_任务_查询', this.buildSearchParams())
      try {
        const response = await this.ExecDatabase(data)
        this.tableData = response.data || []
      } catch (error) {
        console.error('设计报工任务查询失败:', error)
        this.$message.error('查询失败')
      } finally {
        this.loading = false
      }
    },
    async queryProjects(query) {
      const data = this.CreateData('11', '设计报工_项目查询', [['过滤', query || '']])
      try {
        const response = await this.ExecDatabase(data)
        this.projectOptions = response.data || []
      } catch (error) {
        this.projectOptions = []
      }
    },
    async queryMaterialOptions(query) {
      const data = this.CreateData('11', '设计报工_物料查询', [['过滤', query || '']])
      try {
        const response = await this.ExecDatabase(data)
        this.materialOptions = response.data || []
      } catch (error) {
        this.materialOptions = []
      }
    },
    async queryParentMaterialOptions(query) {
      const data = this.CreateData('11', '设计报工_物料查询', [['过滤', query || '']])
      try {
        const response = await this.ExecDatabase(data)
        this.parentMaterialOptions = response.data || []
      } catch (error) {
        this.parentMaterialOptions = []
      }
    },
    canStart(row) {
      return row.单据状态 !== '已完成' && Number(row.当前用户未结束报工数 || 0) === 0
    },
    canEnd(row) {
      return Number(row.当前用户未结束报工数 || 0) > 0
    },
    canComplete(row) {
      return row.单据状态 !== '已完成' && Number(row.报工次数 || 0) > 0
    },
    async startTask(row) {
      const latest = await this.getLatestTask(row.DID)
      if (!latest) return
      Object.assign(row, latest)
      if (latest.单据状态 === '已完成') {
        this.$message.error('任务已完成，不能开始')
        this.searchTable()
        return
      }
      if (Number(latest.当前用户未结束报工数 || 0) > 0) {
        this.$message.warning('当前人员已存在未结束的报工记录')
        return
      }
      this.runAction('设计报工_任务_开始', [
        ['DID', latest.DID],
        ['操作人ID', this.currentUserId()],
        ['操作人', this.currentUserName()]
      ], '开始成功')
    },
    async endTask(row) {
      const latest = await this.getLatestTask(row.DID)
      if (!latest) return
      Object.assign(row, latest)
      if (Number(latest.当前用户未结束报工数 || 0) <= 0) {
        this.$message.warning('当前人员没有未结束的报工记录')
        this.searchTable()
        return
      }
      this.endForm = {
        DID: latest.DID,
        物料编码: latest.物料编码 || '',
        物料名称: latest.物料名称 || '',
        任务描述: latest.任务描述 || '',
        进度说明: ''
      }
      this.endDialogVisible = true
    },
    async confirmEndTask() {
      if (!this.endForm.DID) return
      const success = await this.runAction('设计报工_任务_结束', [
        ['DID', this.endForm.DID],
        ['操作人ID', this.currentUserId()],
        ['操作人', this.currentUserName()],
        ['进度说明', this.endForm.进度说明 || '']
      ], '结束成功')
      if (success) {
        this.endDialogVisible = false
      }
    },
    async completeTask(row) {
      const latest = await this.getLatestTask(row.DID)
      if (!latest) return
      Object.assign(row, latest)
      if (Number(latest.未结束报工数 || 0) > 0) {
        const people = latest.未结束报工人员 || '有人员'
        this.$message.warning(`${people} 还未点击结束，不能完成任务`)
        return
      }
      if (latest.单据状态 === '已完成') {
        this.$message.warning('任务已完成')
        this.searchTable()
        return
      }
      if (!this.canComplete(latest)) {
        this.$message.warning('任务未产生已结束报工，不能完成')
        return
      }
      this.$confirm(`确定完成设计任务 DID ${latest.DID} 吗？`, '提示', { type: 'warning' })
        .then(() => {
          this.runAction('设计报工_任务_完成', [
            ['DID', latest.DID],
            ['操作人', this.currentUserName()]
          ], '完成成功')
        })
        .catch(() => {})
    },
    async getLatestTask(did) {
      const params = [
        ['DID', did || 0],
        ['项目号', ''],
        ['物料编码', ''],
        ['图号', ''],
        ['类别', ''],
        ['关联父件物料编码', ''],
        ['预计开始时间_Start', ''],
        ['预计开始时间_End', ''],
        ['预计结束时间_Start', ''],
        ['预计结束时间_End', ''],
        ['单据状态', ''],
        ['当前操作人ID', this.currentUserId()],
        ['当前操作人', this.currentUserName()]
      ]
      const data = this.CreateData('11', '设计报工_任务_查询', params)
      try {
        const response = await this.ExecDatabase(data)
        const rows = response.data || []
        if (rows.length === 0) {
          this.$message.error('任务不存在或已被删除')
          this.searchTable()
          return null
        }
        return rows[0]
      } catch (error) {
        console.error('设计报工任务实时查询失败:', error)
        this.$message.error('完成前校验失败')
        return null
      }
    },
    async runAction(procedure, params, defaultMessage) {
      if (this.actionLoading) return
      this.actionLoading = true
      const data = this.CreateData('12', procedure, params)
      try {
        const response = await this.ExecDatabase(data)
        const result = this.getResult(response)
        if (String(result.result) === '1') {
          this.$message.success(result.message || defaultMessage)
          this.searchTable()
          return true
        } else {
          this.$message.error(result.message || '操作失败')
          return false
        }
      } catch (error) {
        console.error(`${procedure}失败:`, error)
        this.$message.error('操作失败')
        return false
      } finally {
        this.actionLoading = false
      }
    },
    getResult(response) {
      const data = response && response.data
      if (Array.isArray(data)) return data[0] || {}
      if (data && Array.isArray(data.result)) return data.result[0] || {}
      return data || {}
    },
    currentUserId() {
      return (this.$store && this.$store.getters && this.$store.getters.id) || ''
    },
    currentUserName() {
      return (this.$store && this.$store.getters && this.$store.getters.name) || ''
    },
    formatMaterialLabel(item) {
      return item.物料名称 ? `${item.物料编码} | ${item.物料名称}` : item.物料编码
    },
    formatProjectLabel(item) {
      return item.项目名称 ? `${item.项目号} | ${item.项目名称}` : item.项目号
    },
    getStatusType(status) {
      if (status === '已完成') return 'success'
      if (status === '执行中') return 'warning'
      if (status === '已结束') return 'primary'
      return 'info'
    }
  }
}
</script>

<style scoped>
.design-report-page {
  padding: 12px;
}

.search-container {
  line-height: 34px;
}

.show-text {
  margin-right: 4px;
}

.design-action-buttons {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  flex-wrap: nowrap;
  gap: 10px;
  width: 100%;
  white-space: nowrap;
}

.design-action-buttons ::v-deep .el-button {
  margin: 0;
  padding: 0;
  min-width: 32px;
}

.design-action-buttons ::v-deep .el-button + .el-button {
  margin-left: 0;
}
</style>
