<template>
  <div class="app-container design-task-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: 150px; margin-right: 8px"
        >
          <el-option v-for="item in projectOptions" :key="item.项目号" :label="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-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>
        <br>
        <span class="show-text">预计开始:</span>
        <el-date-picker
          v-model="searchForm.planStartFrom"
          clearable
          size="small"
          type="date"
          value-format="yyyy-MM-dd"
          style="width: 140px; margin-right: 4px"
        />
        <span class="date-separator">至</span>
        <el-date-picker
          v-model="searchForm.planStartTo"
          clearable
          size="small"
          type="date"
          value-format="yyyy-MM-dd"
          style="width: 140px; margin-right: 8px"
        />
        <span class="show-text">预计结束:</span>
        <el-date-picker
          v-model="searchForm.planEndFrom"
          clearable
          size="small"
          type="date"
          value-format="yyyy-MM-dd"
          style="width: 140px; margin-right: 4px"
        />
        <span class="date-separator">至</span>
        <el-date-picker
          v-model="searchForm.planEndTo"
          clearable
          size="small"
          type="date"
          value-format="yyyy-MM-dd"
          style="width: 140px; margin-right: 8px"
        />
        <el-button :loading="loading" icon="el-icon-search" plain size="small" type="primary" @click="searchTable">查询</el-button>
        <el-button icon="el-icon-plus" plain size="small" type="success" @click="openAdd">新建</el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        border
        height="70vh"
        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="130" show-overflow-tooltip />
        <el-table-column align="left" label="任务描述" prop="任务描述" width="220" show-overflow-tooltip />
        <el-table-column align="left" label="父件物料编码" prop="关联父件物料编码" width="160" show-overflow-tooltip />
        <el-table-column align="left" label="设计要求" prop="设计要求" width="220" show-overflow-tooltip />
        <el-table-column align="left" label="研发立项号" prop="研发立项号" width="130" show-overflow-tooltip />
        <el-table-column align="left" label="研发目的" prop="研发目的" width="200" 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="center" label="创建日期" prop="创建日期" width="150" />
        <el-table-column align="left" label="创建人" prop="创建人" width="110" show-overflow-tooltip />
        <el-table-column align="left" label="备注" prop="备注" width="180" show-overflow-tooltip />
        <el-table-column align="center" fixed="right" label="操作" width="130">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="openEdit(scope.row)">编辑</el-button>
            <el-button type="text" size="mini" class="danger-action" @click="deleteTask(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      :visible.sync="dialogVisible"
      :title="isEdit ? '编辑设计任务' : '新建设计任务'"
      width="860px"
      center
      :close-on-click-modal="false"
    >
      <el-form ref="taskForm" :model="formData" :rules="rules" label-width="130px" size="small">
        <el-row :gutter="12">
          <el-col v-if="isEdit" :span="12">
            <el-form-item label="DID">
              <el-input v-model="formData.DID" disabled />
            </el-form-item>
          </el-col>
          <el-col v-if="isEdit" :span="12">
            <el-form-item label="创建日期">
              <el-input v-model="formData.创建日期" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目号">
              <el-select
                v-model="formData.项目号"
                allow-create
                clearable
                filterable
                remote
                default-first-option
                :remote-method="queryProjects"
                style="width: 100%"
              >
                <el-option v-for="item in projectOptions" :key="item.项目号" :label="item.项目号" :value="item.项目号" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料编码" prop="物料编码">
              <el-select
                v-model="formData.物料编码"
                clearable
                filterable
                remote
                :remote-method="queryMaterialOptions"
                style="width: 100%"
                @change="handleMaterialChange"
              >
                <el-option
                  v-for="item in materialOptions"
                  :key="item.物料编码"
                  :label="formatMaterialLabel(item)"
                  :value="item.物料编码"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料名称">
              <el-input v-model="formData.物料名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="图号">
              <el-input v-model="formData.图号" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="任务描述" prop="任务描述">
              <el-input v-model="formData.任务描述" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="父件物料编码">
              <el-select
                v-model="formData.关联父件物料编码"
                clearable
                filterable
                remote
                :remote-method="queryParentMaterialOptions"
                style="width: 100%"
                @change="handleParentMaterialChange"
              >
                <el-option
                  v-for="item in parentMaterialOptions"
                  :key="item.物料编码"
                  :label="formatMaterialLabel(item)"
                  :value="item.物料编码"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="父件物料名称">
              <el-input v-model="formData.关联父件物料名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="研发立项号">
              <el-input v-model="formData.研发立项号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="研发目的">
              <el-input v-model="formData.研发目的" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="指派对象" prop="assigneeIds">
              <el-select
                v-model="formData.assigneeIds"
                clearable
                filterable
                multiple
                remote
                :remote-method="queryPersonnel"
                style="width: 100%"
                @change="handleAssigneeChange"
              >
                <el-option
                  v-for="item in personnelOptions"
                  :key="item.人员编号"
                  :label="formatPersonLabel(item)"
                  :value="item.人员编号"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预计开始时间">
              <el-date-picker v-model="formData.预计开始时间" type="date" value-format="yyyy-MM-dd" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预计结束时间">
              <el-date-picker v-model="formData.预计结束时间" type="date" value-format="yyyy-MM-dd" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="设计要求">
              <el-input v-model="formData.设计要求" type="textarea" :rows="3" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="formData.备注" type="textarea" :rows="2" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submitForm">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'DesignReportTask',
  data() {
    return {
      loading: false,
      submitLoading: false,
      dialogVisible: false,
      isEdit: false,
      tableData: [],
      projectOptions: [],
      materialOptions: [],
      parentMaterialOptions: [],
      personnelOptions: [],
      searchForm: {
        did: '',
        projectNo: '',
        itemCode: '',
        drawingNo: '',
        parentItemCode: '',
        planStartFrom: '',
        planStartTo: '',
        planEndFrom: '',
        planEndTo: '',
        status: ''
      },
      formData: this.getEmptyForm(),
      rules: {
        物料编码: [{ required: true, message: '请选择物料编码', trigger: 'change' }],
        任务描述: [{ required: true, message: '请输入任务描述', trigger: 'blur' }],
        assigneeIds: [{ type: 'array', required: true, message: '请选择指派对象', trigger: 'change' }]
      }
    }
  },
  created() {
    this.queryProjects('')
    this.queryPersonnel('')
    this.searchTable()
  },
  methods: {
    getEmptyForm() {
      return {
        DID: '',
        项目号: '',
        物料编码: '',
        物料名称: '',
        图号: '',
        任务描述: '',
        关联父件物料编码: '',
        关联父件物料名称: '',
        设计要求: '',
        研发立项号: '',
        研发目的: '',
        指派对象ID: '',
        指派对象: '',
        assigneeIds: [],
        预计开始时间: '',
        预计结束时间: '',
        创建日期: '',
        备注: ''
      }
    },
    buildSearchParams() {
      return [
        ['DID', this.searchForm.did || 0],
        ['项目号', this.searchForm.projectNo || ''],
        ['物料编码', this.searchForm.itemCode || ''],
        ['图号', this.searchForm.drawingNo || ''],
        ['关联父件物料编码', this.searchForm.parentItemCode || ''],
        ['预计开始时间_Start', this.searchForm.planStartFrom || ''],
        ['预计开始时间_End', this.searchForm.planStartTo || ''],
        ['预计结束时间_Start', this.searchForm.planEndFrom || ''],
        ['预计结束时间_End', this.searchForm.planEndTo || ''],
        ['单据状态', this.searchForm.status || '']
      ]
    },
    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
      }
    },
    openAdd() {
      this.isEdit = false
      this.formData = this.getEmptyForm()
      this.dialogVisible = true
      this.$nextTick(() => this.$refs.taskForm && this.$refs.taskForm.clearValidate())
    },
    openEdit(row) {
      this.isEdit = true
      const assigneeIds = row.指派对象ID ? String(row.指派对象ID).split(',').filter(Boolean) : []
      this.formData = {
        ...this.getEmptyForm(),
        ...row,
        assigneeIds,
        预计开始时间: this.toDate(row.预计开始时间),
        预计结束时间: this.toDate(row.预计结束时间)
      }
      if (row.指派对象ID || row.指派对象) {
        const ids = assigneeIds
        const names = row.指派对象 ? String(row.指派对象).split(',') : []
        ids.forEach((id, index) => {
          if (!this.personnelOptions.some(item => item.人员编号 === id)) {
            this.personnelOptions.push({ 人员编号: id, 人员姓名: names[index] || id })
          }
        })
      }
      this.dialogVisible = true
      this.$nextTick(() => this.$refs.taskForm && this.$refs.taskForm.clearValidate())
    },
    submitForm() {
      this.$refs.taskForm.validate(async valid => {
        if (!valid) return
        this.submitLoading = true
        const procedure = this.isEdit ? '设计报工_任务_编辑' : '设计报工_任务_新增'
        const params = this.buildSaveParams()
        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 || '保存成功')
            this.dialogVisible = false
            this.searchTable()
          } else {
            this.$message.error(result.message || '保存失败')
          }
        } catch (error) {
          console.error('设计任务保存失败:', error)
          this.$message.error('保存失败')
        } finally {
          this.submitLoading = false
        }
      })
    },
    buildSaveParams() {
      const params = []
      if (this.isEdit) params.push(['DID', this.formData.DID || 0])
      params.push(['项目号', this.formData.项目号 || ''])
      params.push(['物料编码', this.formData.物料编码 || ''])
      params.push(['物料名称', this.formData.物料名称 || ''])
      params.push(['图号', this.formData.图号 || ''])
      params.push(['任务描述', this.formData.任务描述 || ''])
      params.push(['关联父件物料编码', this.formData.关联父件物料编码 || ''])
      params.push(['关联父件物料名称', this.formData.关联父件物料名称 || ''])
      params.push(['设计要求', this.formData.设计要求 || ''])
      params.push(['研发立项号', this.formData.研发立项号 || ''])
      params.push(['研发目的', this.formData.研发目的 || ''])
      params.push(['指派对象ID', this.formData.指派对象ID || ''])
      params.push(['指派对象', this.formData.指派对象 || ''])
      params.push(['预计开始时间', this.formData.预计开始时间 || ''])
      params.push(['预计结束时间', this.formData.预计结束时间 || ''])
      params.push([this.isEdit ? '最后编辑人' : '创建人', this.currentUserName()])
      params.push(['备注', this.formData.备注 || ''])
      return params
    },
    deleteTask(row) {
      this.$confirm(`确定删除设计任务 DID ${row.DID} 吗？已有报工记录的任务不能删除。`, '提示', { type: 'warning' })
        .then(async () => {
          const data = this.CreateData('12', '设计报工_任务_删除', [['DID', row.DID]])
          const response = await this.ExecDatabase(data)
          const result = this.getResult(response)
          if (String(result.result) === '1') {
            this.$message.success(result.message || '删除成功')
            this.searchTable()
          } else {
            this.$message.error(result.message || '删除失败')
          }
        })
        .catch(() => {})
    },
    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 = []
      }
    },
    async queryPersonnel(query) {
      const data = this.CreateData('11', '设计报工_人员查询', [['过滤', query || '']])
      try {
        const response = await this.ExecDatabase(data)
        this.personnelOptions = response.data || []
      } catch (error) {
        this.personnelOptions = []
      }
    },
    handleMaterialChange(value) {
      const selected = this.materialOptions.find(item => item.物料编码 === value)
      this.formData.物料名称 = selected ? selected.物料名称 : ''
    },
    handleParentMaterialChange(value) {
      const selected = this.parentMaterialOptions.find(item => item.物料编码 === value)
      this.formData.关联父件物料名称 = selected ? selected.物料名称 : ''
    },
    handleAssigneeChange(values) {
      const selected = this.personnelOptions.filter(item => values.includes(item.人员编号))
      this.formData.指派对象ID = values.join(',')
      this.formData.指派对象 = selected.map(item => item.人员姓名).join(',')
    },
    formatMaterialLabel(item) {
      return item.物料名称 ? `${item.物料编码} | ${item.物料名称}` : item.物料编码
    },
    formatPersonLabel(item) {
      return item.账号 ? `${item.人员姓名} | ${item.账号}` : item.人员姓名
    },
    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 || {}
    },
    toDate(value) {
      if (!value) return ''
      return String(value).split(' ')[0]
    },
    currentUserName() {
      return (this.$store && this.$store.getters && this.$store.getters.name) || ''
    },
    getStatusType(status) {
      if (status === '已完成') return 'success'
      if (status === '执行中') return 'warning'
      if (status === '已结束') return 'primary'
      return 'info'
    }
  }
}
</script>

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

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

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

.date-separator {
  margin-right: 4px;
  color: #606266;
}

.danger-action {
  color: #f56c6c;
}
</style>
