<template>
  <ele-modal
    :centered="true"
    :visible.sync="dispatchDialog"
    title="派单"
    :close-on-click-modal="false"
    width="1000px"
    append-to-body
    @close="handleClose"
  >
    <el-form
      ref="addFormRef"
      :model="addForm"
      label-width="120px"
      class="add_form"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="编码" prop="code">
            <el-input
              v-model="addForm.code"
              size="small"
              placeholder="请输入"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="计划名称"
            prop="name"
            :rules="{
              required: true,
              message: '请输入计划名称',
              trigger: 'change'
            }"
          >
            <el-input
              v-model="addForm.name"
              size="small"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="自动派单" prop="isSyncBill">
            <el-select
              v-model="addForm.isSyncBill"
              size="small"
              style="width: 100%"
            >
              <el-option :value="1" label="是"></el-option>
              <el-option :value="0" label="否"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item 
            label="预计售后时长" 
            prop="duration"
            :rules="{
              required: true,
              message: '请输入预计售后时长',
              trigger: 'change'
            }"
          >
            <div style="display: flex">
              <el-input
                type="number"
                v-model="addForm.duration"
                size="small"
                placeholder="请输入"
                min="1"
                @input="formDataDurationTime"
              >
                <template #suffix>
                  <el-select
                    v-model="addForm.durationUnit"
                    size="small"
                    style="width: 120px"
                  >
                    <el-option :value="'1'" label="分钟"></el-option>
                    <el-option :value="'2'" label="小时"></el-option>
                    <el-option :value="'3'" label="天"></el-option>
                  </el-select>
                </template>
              </el-input>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="部门"
            prop="executeGroupId"
            :rules="{
              required: true,
              message: '请选择部门',
              trigger: 'change'
            }"
          >
            <deptSelect
              v-model="addForm.executeGroupId"
              @changeGroup="searchDeptNodeClick"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="工单执行人"
            prop="executeUserId"
            :rules="{
              required: true,
              message: '请选择执行人',
              trigger: 'change'
            }"
          >
            <el-select
              v-model="addForm.executeUserId"
              size="small"
              style="width: 100%"
              filterable
              @change="changeUser"
            >
              <el-option
                v-for="item in executorList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item 
            label="紧急程度" 
            prop="urgent"
            :rules="{
              required: true,
              message: '请选择紧急程度',
              trigger: 'change'
            }"
          >
            <DictSelection
              dictName="紧急程度"
              clearable
              v-model="addForm.urgent"
            ></DictSelection>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注" prop="remark">
            <el-input
              type="textarea"
              resize="none"
              v-model="addForm.remark"
              :rows="2"
              placeholder="请详细说明"
              size="small"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="footer">
      <el-button type="primary" @click="handleSubmit" :loading="loading">确认</el-button>
      <el-button @click="handleClose" :loading="loading">取消</el-button>
    </div>
  </ele-modal>
</template>

<script>
import deptSelect from '@/components/CommomSelect/dept-select.vue';
import { getUserPage } from '@/api/system/organization';
import { getCurrentUser } from '@/utils/token-util';
import { demanDispatch } from '@/api/salesServiceManagement/index';
let submitData = {};

export default {
  components: { deptSelect },
  computed: {
    loginChangeGroupVOList() {
      return this.$store.state.user?.info?.loginChangeGroupVOList;
    }
  },
  data() {
    return {
      dispatchDialog: false,
      addForm: {
        code: '', // 编码
        name: '', // 计划名称
        isSyncBill: 1, // 是否自动派单
        duration: null, // 原始时长值
        durationUnit: '1', // 时长单位（1:分钟 2:小时 3:天）
        executeGroupId: '', // 执行部门ID
        executeGroupName: '', // 执行部门名称
        executeUserId: '', // 执行人ID
        executeUserName: '', // 执行人名称
        urgent: null, // 紧急程度
        remark: '' // 备注
      },
      loading: false,
      executorList: [],
      submitSource: 1 // 1:新增；2：修改
    };
  },
  methods: {
    handleClose() {
      this.dispatchDialog = false;
      this.addForm = {
        code: '',
        name: '',
        isSyncBill: 1,
        duration: null,
        durationUnit: '1',
        executeGroupId: '',
        executeGroupName: '',
        executeUserId: '',
        executeUserName: '',
        urgent: null,
        remark: ''
      };
      this.$refs.addFormRef?.resetFields();
    },
    open(data, type) {
      this.submitSource = type === 'add' ? 1 : 2;
      this.dispatchDialog = true;
      submitData = { ...data }; // 深拷贝避免原数据污染
      
      const currentUser = getCurrentUser();
      if (this.loginChangeGroupVOList && this.loginChangeGroupVOList.length > 0) {
        const obj = this.loginChangeGroupVOList.find(
          el => el.groupId === currentUser.currentGroupId
        );
        this.addForm.executeGroupId = currentUser.currentGroupId || '';
        this.searchDeptNodeClick(currentUser.currentGroupId, {
          name: obj?.groupName || ''
        });
      }
    },
    // 选择部门后获取部门人员
    searchDeptNodeClick(groupId, data) {
      if (groupId) {
        this.addForm.executeGroupId = groupId;
        this.addForm.executeGroupName = data?.name || '';
        // 获取部门下的人员列表
        this.getUserList({ groupId });
      } else {
        this.addForm.executeGroupId = '';
        this.addForm.executeGroupName = '';
        this.executorList = [];
        this.addForm.executeUserId = '';
        this.addForm.executeUserName = '';
      }
    },
    // 获取部门人员列表
    async getUserList(params) {
      try {
        const res = await getUserPage({
          pageNum: 1,
          size: -1,
          ...params
        });
        this.executorList = res.list || [];
      } catch (error) {
        this.executorList = [];
        console.error('获取人员列表失败：', error);
      }
    },
    // 选择执行人
    changeUser(val) {
      if (!val) {
        this.addForm.executeUserName = '';
        return;
      }
      const user = this.executorList.find(item => item.id === val);
      this.addForm.executeUserName = user?.name || '';
    },
    // 处理时长输入（去除前置0）
    formDataDurationTime(value) {
      if (value && value > 0) {
        this.addForm.duration = Number(value.toString().replace(/^0+/, ''));
      } else {
        this.addForm.duration = null;
      }
    },
    // 转换时长为小时（后端要求）
    calculateDuration() {
      if (this.addForm.duration === null) return null;
      const duration = Number(this.addForm.duration);
      switch (this.addForm.durationUnit) {
        case '1': // 分钟转小时（向上取整）
          return Math.ceil(duration / 60);
        case '2': // 小时直接使用
          return duration;
        case '3': // 天转小时
          return duration * 24;
        default:
          return duration;
      }
    },
    // 提交表单
    handleSubmit() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (valid) {
          // 构造后端要求的参数结构
          const planAddPO = {
            workOrderExecuteUserId: this.addForm.executeUserId ? Number(this.addForm.executeUserId) : null,
            workOrderExecuteUserName: this.addForm.executeUserName,
            workOrderExecuteGroupId: this.addForm.executeGroupId ? Number(this.addForm.executeGroupId) : null,
            workOrderExecuteGroupName: this.addForm.executeGroupName,
            workOrderUrgent: this.addForm.urgent ? Number(this.addForm.urgent) : null,
            workOrderRemark: this.addForm.remark,
            duration: this.calculateDuration() // 转换为小时
          };

          const submitParams = {
            ...submitData,
            planAddPO,
            submitSource: this.submitSource
          };

          this.loading = true;
          try {
            const res = await demanDispatch(submitParams);
            if (res) {
              this.$message.success('派单成功');
              this.handleClose();
              this.$emit('savExit');
            }
          } catch (error) {
            this.$message.error('派单失败：' + (error.message || '未知错误'));
          } finally {
            this.loading = false;
          }
        } else {
          this.$message.warning('请完善表单信息');
          return false;
        }
      });
    }
  }
};
</script>

<style scoped lang="scss">
.add_form {
  .el-col-12 {
    padding-bottom: 13px;
  }
}
.footer {
  text-align: center;
}
</style>