<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-card shadow="never" style="margin-bottom: 20px;">
        <div slot="header" class="clearfix">
          <span>派工基本信息</span>
        </div>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="派工单号" prop="planCode">
              <el-input v-model="form.planCode" placeholder="自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单编号" prop="workOrderCode">
              <el-input v-model="form.workOrderCode" placeholder="请输入工单编号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备编号" prop="deviceCode">
              <el-input v-model="form.deviceCode" placeholder="请输入设备编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="deviceName">
              <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="派工类型" prop="dispatchType">
              <el-select v-model="form.dispatchType" placeholder="请选择派工类型" @change="handleDispatchTypeChange">
                <el-option
                  v-for="dict in dict.type.dms_dispatch_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="form.priority" placeholder="请选择优先级">
                <el-option
                  v-for="dict in dict.type.dms_priority"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 单人派工 -->
        <el-row :gutter="20" v-if="form.dispatchType === '1'">
          <el-col :span="12">
            <el-form-item label="执行人" prop="executorId">
              <el-select v-model="form.executorId" placeholder="请选择执行人" filterable @change="handleExecutorChange">
                <el-option
                  v-for="user in userList"
                  :key="user.userId"
                  :label="user.nickName || user.userName"
                  :value="user.userId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="要求开始时间" prop="requireStartTime">
              <el-date-picker
                v-model="form.requireStartTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择开始时间"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="要求完成时间" prop="requireEndTime">
              <el-date-picker
                v-model="form.requireEndTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择完成时间"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="派工说明" prop="dispatchNotes">
              <el-input v-model="form.dispatchNotes" type="textarea" :rows="3" placeholder="请输入派工说明" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 团队成员（团队派工时显示） -->
      <el-card shadow="never" v-if="form.dispatchType === '2'" style="margin-bottom: 20px;">
        <div slot="header" class="clearfix">
          <span>团队成员</span>
          <el-button style="float: right; padding: 3px 10px" type="primary" size="mini" @click="handleAddMember">添加成员</el-button>
        </div>
        
        <el-table :data="form.dispatchMembers" border>
          <el-table-column label="序号" type="index" width="50" align="center" />
          <el-table-column label="成员姓名" prop="userName" min-width="120">
            <template slot-scope="scope">
              <el-select v-model="scope.row.userId" placeholder="请选择成员" filterable @change="handleMemberChange(scope.row, scope.$index)">
                <el-option
                  v-for="user in userList"
                  :key="user.userId"
                  :label="user.nickName || user.userName"
                  :value="user.userId"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="成员角色" prop="memberRole" min-width="120">
            <template slot-scope="scope">
              <el-select v-model="scope.row.memberRole" placeholder="请选择角色">
                <el-option
                  v-for="dict in dict.type.dms_member_role"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="分配工时" prop="allocatedHours" min-width="100">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.allocatedHours" :min="0" :precision="1" style="width: 100%;" />
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" min-width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入备注" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="80">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="handleDeleteMember(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <el-form-item>
        <el-button type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getDispatchPlan, addDispatchPlan, updateDispatchPlan } from '@/api/dms/dispatchPlan'
import { selectUserList } from '@/api/system/user'

export default {
  name: 'DispatchPlanDetail',
  dicts: ['dms_dispatch_type', 'dms_priority', 'dms_member_role'],
  data() {
    return {
      form: {
        planId: null,
        planCode: null,
        workOrderId: null,
        workOrderCode: null,
        deviceId: null,
        deviceCode: null,
        deviceName: null,
        dispatchType: '1',
        executorId: null,
        executorName: null,
        teamId: null,
        teamName: null,
        requireStartTime: null,
        requireEndTime: null,
        priority: '3',
        dispatchNotes: null,
        dispatchMembers: []
      },
      userList: [],
      rules: {
        dispatchType: [{ required: true, message: '请选择派工类型', trigger: 'change' }],
        executorId: [{ required: true, message: '请选择执行人', trigger: 'change' }],
        requireStartTime: [{ required: true, message: '请选择要求开始时间', trigger: 'change' }],
        requireEndTime: [{ required: true, message: '请选择要求完成时间', trigger: 'change' }]
      }
    }
  },
  created() {
    this.loadUserList()
    const planId = this.$route.params && this.$route.params.planId
    if (planId && planId !== 'new') {
      this.loadData(planId)
    }
    // 从路由参数获取工单信息
    if (this.$route.query.workOrderId) {
      this.form.workOrderId = this.$route.query.workOrderId
      this.form.workOrderCode = this.$route.query.workOrderCode
      this.form.deviceCode = this.$route.query.deviceCode
      this.form.deviceName = this.$route.query.deviceName
    }
  },
  methods: {
    loadData(planId) {
      getDispatchPlan(planId).then(response => {
        this.form = response.data
        if (!this.form.dispatchMembers) {
          this.form.dispatchMembers = []
        }
      })
    },
    loadUserList() {
      selectUserList({}).then(response => {
        this.userList = response.rows
      })
    },
    handleDispatchTypeChange(val) {
      if (val === '1') {
        // 单人派工，清空团队成员
        this.form.dispatchMembers = []
        this.form.teamId = null
        this.form.teamName = null
      } else {
        // 团队派工，清空执行人
        this.form.executorId = null
        this.form.executorName = null
      }
    },
    handleExecutorChange(userId) {
      const user = this.userList.find(u => u.userId === userId)
      if (user) {
        this.form.executorName = user.nickName || user.userName
      }
    },
    handleAddMember() {
      this.form.dispatchMembers.push({
        userId: null,
        userName: null,
        memberRole: null,
        allocatedHours: 0,
        remark: null
      })
    },
    handleMemberChange(row, index) {
      const user = this.userList.find(u => u.userId === row.userId)
      if (user) {
        row.userName = user.nickName || user.userName
      }
    },
    handleDeleteMember(index) {
      this.form.dispatchMembers.splice(index, 1)
    },
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.planId) {
            updateDispatchPlan(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.cancel()
            })
          } else {
            addDispatchPlan(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.cancel()
            })
          }
        }
      })
    },
    cancel() {
      this.$router.back()
    }
  }
}
</script>
