<template>
  <ContentWrap v-loading="formLoading">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >

      <el-row>
        <el-col :span="12">
          <el-form-item label="合同名称" prop="contractName">
            <el-select v-model="formData.contractId" placeholder="请选择" @change="getProjectInfo">
              <el-option
                v-for="item in projectList"
                :key="item.id"
                :label="item.contractName"
                :value="item.id"
                clearable
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同编号" prop="contractCode">
            <el-input v-model="formData.contractCode" placeholder="请输入合同编号" disabled/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="客户名称" prop="manufacturerId" >
            <el-select
              clearable
              @clear="zzClear"
              v-model="formData.manufacturerId"
              :placeholder="t('deviceForm.mfgHolder')"
              disabled
            >
              <el-option :label="formData.manufactureName" :value="formData.manufacturerId" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结算方式" prop="payment" >
            <el-input v-model="formData.payment" placeholder="请输入结算方式" disabled/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="总数" prop="workloadTotal">
            <el-input v-model="formData.workloadTotal" placeholder="请输入工作量总数" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="已完成" prop="workloadFinish">
            <el-input v-model="formData.workloadFinish" placeholder="已完成工作量" disabled/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
              style="width: 150%"
              v-model="formData.startTime"
              type="date"
              value-format="x"
              placeholder="选择开始时间"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="完成时间" prop="endTime">
            <el-date-picker
              style="width: 150%"
              v-model="formData.endTime"
              type="date"
              value-format="x"
              placeholder="选择完成时间"
              disabled
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" type="textarea" disabled/>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap>
    <div class="content">
      <div class="toolbar">
        <div class="actions">
          <el-button type="primary" @click="addNewRow" icon="plus" >
            新增行
          </el-button>
          <el-button type="success" @click="saveAll" :disabled="editingRowsCount === 0" icon="check">
            保存所有更改
          </el-button>
        </div>
      </div>

      <div class="table-container">
        <el-table :data="tableData" :row-class-name="rowClassName" empty-text="暂无数据">
          <el-table-column prop="wellName" label="井号">
            <template #default="{ row }">
              <span v-if="!row.editing">{{ row.wellName }}</span>
              <div v-else>
                <el-input v-model="row.editData.wellName" class="edit-input" placeholder="请输入井号" />
                <div v-if="row.errors.wellName" class="error-message">{{ row.errors.wellName }}</div>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="wellType" label="井型/井别">
            <template #default="{ row }">
              <span v-if="!row.editing">{{ row.wellType }}</span>
              <div v-else>
                <el-input v-model="row.editData.wellType" class="edit-input" placeholder="请输入井型/井别" />
                <div v-if="row.errors.wellType" class="error-message">{{ row.errors.wellType }}</div>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="location" label="施工地点" >
            <template #default="{ row }">
              <span v-if="!row.editing">{{ row.location }}</span>
              <div v-else>
                <el-input v-model="row.editData.location" class="edit-input" placeholder="请输入施工地点" />
                <div v-if="row.errors.location" class="error-message">{{ row.errors.location }}</div>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="technique" label="施工工艺" >
            <template #default="{ row }">
              <span v-if="!row.editing">{{ row.technique }}</span>
              <div v-else>
                <el-input v-model="row.editData.technique" class="edit-input" placeholder="请输入施工工艺" />
                <div v-if="row.errors.technique" class="error-message">{{ row.errors.technique }}</div>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="workloadDesign" label="设计工作量">
            <template #default="{ row }">
              <span v-if="!row.editing">{{ row.workloadDesign }}</span>
              <div v-else>
                <el-input v-model="row.editData.workloadDesign" class="edit-input" placeholder="请输入设计工作量" />
                <div v-if="row.errors.workloadDesign" class="error-message">{{ row.errors.workloadDesign }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="deptIds" label="所属队伍" >
            <template #default="{ row }">
              <span v-if="!row.editing">
                {{ getDeptNames(row.deptIds) }}
              </span>
              <div v-else>
                <el-tree-select
                  multiple
                  v-model="row.editData.deptIds"
                  :data="deptList"
                  :props="defaultProps"
                  check-strictly
                  node-key="id"
                  filterable
                  placeholder="请选择所在部门"
                  clearable
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注">
            <template #default="{ row }">
              <span v-if="!row.editing">{{ row.remark }}</span>
              <div v-else>
                <el-input v-model="row.editData.remark" class="edit-input" placeholder="请输入备注" />
                <div v-if="row.errors.remark" class="error-message">{{ row.errors.remark }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row, $index }">
              <div class="action-cell">
                <template v-if="!row.editing">
                  <el-button size="small" type="primary" @click="editRow(row)" icon="edit">编辑</el-button>
                  <el-button size="small" type="danger" @click="deleteRow($index)" icon="delete">删除</el-button>
                </template>
                <template v-else>
                  <el-button size="small" type="success" @click="saveRow(row)" icon="check">保存</el-button>
                  <el-button size="small" @click="cancelEdit(row)" icon="close">取消</el-button>
                </template>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </ContentWrap>
  <ContentWrap>
    <el-form style="float: right">
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="close">取 消</el-button>
    </el-form>
  </ContentWrap>
</template>
<script setup lang="ts">
import { IotProjectInfoApi, IotProjectInfoVO } from '@/api/pms/iotprojectinfo'
import {defaultProps,handleTree} from "@/utils/tree";
import * as DeptApi from "@/api/system/dept";
import CustomerList from '@/views/pms/device/CustomerList.vue'
import {ref, reactive, computed, onMounted} from "vue";
/** 项目信息 表单 */
defineOptions({ name: 'IotProjectTaskInfo' })
const { params, name } = useRoute() // 查询参数
import {useUserStore} from "@/store/modules/user";
import {IotProjectTaskApi, IotProjectTaskVO} from "@/api/pms/iotprojecttask";
import {ElMessageBox, ElMessage} from "element-plus";
import {useTagsViewStore} from "@/store/modules/tagsView";
const id = params.id
const projectId = params.projectId
const { delView } = useTagsViewStore() // 视图操作
const { currentRoute, push } = useRouter()
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const deptList = ref<Tree[]>([]) // 树形结构
const dialogVisible = ref(true) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const taskList = ref<IotProjectTaskVO[]>([]) // 列表的数据
const projectList = ref<IotProjectInfoVO[]>([])
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const loading = ref(true) // 列表的加载中
const formData = ref({
  id: undefined,
  contractId: undefined,
  contractName: undefined,
  contractCode: undefined,
  workloadTotal: undefined,
  workloadFinish: undefined,
  startTime: undefined,
  endTime: undefined,
  location: undefined,
  technique: undefined,
  payment: undefined,
  remark:undefined,
  manufactureName: undefined,
  manufacturerId: undefined,
  userName: undefined,
  userId: undefined,
})
const close = () => {
  delView(unref(currentRoute))
  push({ name: 'IotProjectTask', params:{}})
}

const getProjectInfo = (contractId: number) => {
  const project = projectList.value.find(item => item.id === contractId);
  if (project) {
    formData.value.contractName = project.contractName;
    formData.value.contractCode = project.contractCode;
    formData.value.payment = project.payment;
    formData.value.workloadTotal = project.workloadTotal;
    formData.value.startTime = project.startTime;
    formData.value.endTime = project.endTime;
    formData.value.remark = project.remark;
    formData.value.manufactureName = project.manufactureName;
    formData.value.manufacturerId = project.manufacturerId;
    formData.value.id = project.id;
  }
}

const queryParams = reactive({
  projectId:undefined,
  id:undefined
})
const formRules = reactive({
  contractId: [{ required: true, message: '合同名称不能为空', trigger: 'blur' }],
  manufacturerId: [{ required: true, message: '客户不能为空', trigger: 'blur' }],
  payment: [{ required: true, message: '结算方式不能为空', trigger: 'blur' }],
  workloadTotal: [{ required: true, message: '工作量总数不能为空', trigger: 'blur' }],
  startTime: [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
  endTime: [{ required: true, message: '结束时间不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

const zzClear = () =>{
  formData.value.manufacturerId = undefined
  formData.value.manufactureName = undefined
}

// 根据部门ID获取部门名称
const getDeptNames = (deptIds) => {
  if (!deptIds || deptIds.length === 0) return '';

  const names = [];
  const findDept = (list, id) => {
    for (const item of list) {
      if (item.id === id) {
        names.push(item.name);
        return true;
      }
      if (item.children && findDept(item.children, id)) {
        return true;
      }
    }
    return false;
  };

  deptIds.forEach(id => findDept(deptList.value, id));
  return names.join(', ');
};

const tableData = ref([
  {
    id: 1,
    deptId:'',
    wellName: '',
    wellType: '',
    location: '',
    technique: '',
    workloadDesign: '',
    deptIds: [],
    remark:'',
    editData: {},
    editing:true,
    originalData: {},
    errors: {},
    projectId: ''
  },
]);
/** 打开弹窗 */
const open = async () => {
  resetForm()
  // 修改时，设置数据
  if (id) {
    formType.value = 'update';
    formLoading.value = true
    try {
      queryParams.id = id;
      const data = await IotProjectTaskApi.getIotProjectTaskPage(queryParams);
      tableData.value = data.list
      tableData.value.forEach(item=>{
        item.editData={};
        item.originalData={};
        item.errors={};
      })
    } finally {
      formLoading.value = false
    }
  }else{
    formType.value = 'create';
  }
  // 如果有projectId参数，自动选中对应的合同
  if (projectId) {
    await autoSelectContract(projectId);
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 自动选择合同 */
const autoSelectContract = async (projectId: number) => {
  // 等待项目列表加载完成
  await waitForProjectList();

  // 查找匹配的合同
  const project = projectList.value.find(item => item.id === Number(projectId));
  if (project) {
    // 设置选中值
    formData.value.contractId = project.id;
    // 触发合同信息加载
    getProjectInfo(project.id);
  } else {
    ElMessage.warning('未找到指定的合同信息');
  }
}

/** 等待项目列表加载完成 */
const waitForProjectList = () => {
  return new Promise(resolve => {
    const checkInterval = setInterval(() => {
      if (projectList.value.length > 0) {
        clearInterval(checkInterval);
        resolve(true);
      }
    }, 100);
  });
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    tableData.value.forEach(item=>{
      item.projectId = formData.value.id;
      item.deptId = useUserStore().getUser.deptId;
    })

    const data = {
      taskList: tableData.value
    }
    if (formType.value === 'create') {
      await IotProjectTaskApi.createIotProjectTask(data)
      message.success(t('common.createSuccess'))
    } else {
      await IotProjectTaskApi.updateIotProjectTask(data)
      message.success(t('common.updateSuccess'))
    }
    // 发送操作成功的事件
    emit('success')
    close()
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    contractId: undefined,
    contractName: undefined,
    contractCode: undefined,
    workloadTotal: undefined,
    workloadFinish: undefined,
    startTime: undefined,
    endTime: undefined,
    location: undefined,
    technique: undefined,
    payment: undefined,
    remark: undefined,
    manufactureName: undefined,
    manufacturerId: undefined,
    userName: undefined,
    userId: undefined,
  }
  formRef.value?.resetFields()
}
onMounted(async () => {
  deptList.value = handleTree(await DeptApi.getSimpleDeptList())
  let deptId = useUserStore().getUser.deptId
  projectList.value = await IotProjectInfoApi.getIotProjectInfoUser(deptId);
  open();
})

// 计算正在编辑的行数
const editingRowsCount = computed(() => {
  return tableData.value.filter(row => row.editing).length;
});

// 格式化日期
const formatDate = (timestamp) => {
  const date = new Date(timestamp);
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
};

// 为编辑中的行添加特殊样式
const rowClassName = ({ row }) => {
  return row.editing ? 'editable-row' : '';
};

// 添加新行
const addNewRow = () => {
  const newId = tableData.value.length > 0
    ? Math.max(...tableData.value.map(item => item.id)) + 1
    : 1;

  const newRow = {
    id: newId,
    wellName: '',
    wellType: '',
    location: '',
    technique: '',
    workloadDesign: '',
    deptIds: [],
    remark:'',
    editing: true,
    editData: {
      wellName: '',
      wellType: '',
      location: '',
      technique: '',
      workloadDesign: '',
      deptIds: [],
      remark:'',
    },
    originalData: {},
    errors: {}
  };

  tableData.value.unshift(newRow);
};

// 编辑行
const editRow = (row) => {
  // 保存原始数据用于取消编辑时恢复
  row.originalData = {...row};
  // 设置编辑数据
  row.editData = {
    id: row.id,
    wellName: row.wellName,
    wellType: row.wellType,
    location: row.location,
    technique: row.technique,
    workloadDesign: row.workloadDesign,
    deptIds: row.deptIds,
    remark:row.remark,
  };
  // 进入编辑状态
  row.editing = true;
  // 清空错误信息
  row.errors = {};
};

// 验证行数据
const validateRow = (row) => {
  row.errors = {};
  let valid = true;

  if (!row.editData.wellName || row.editData.wellName.trim() === '') {
    row.errors.wellName = '井号不能为空';
    valid = false;
  }

  if (!row.editData.wellType || row.editData.wellType.trim() === '') {
    row.errors.wellType = '井型不能为空';
    valid = false;
  }

  return valid;
};

// 保存行
const saveRow = (row) => {
  if (!validateRow(row)) return;

  // 将编辑数据应用到行
  row.id = row.editData.id;
  row.wellName = row.editData.wellName;
  row.wellType = row.editData.wellType;
  row.location = row.editData.location;
  row.technique = row.editData.technique;
  row.workloadDesign = row.editData.workloadDesign;
  row.deptIds = row.editData.deptIds;
  row.remark = row.editData.remark;
  // 退出编辑状态
  row.editing = false;
};

// 保存所有更改
const saveAll = () => {
  let allValid = true;

  // 验证所有编辑中的行
  tableData.value.forEach(row => {
    if (row.editing && !validateRow(row)) {
      allValid = false;
    }
  });

  if (!allValid) {
    ElMessage.error('部分数据验证失败，请检查输入');
    return;
  }

  // 保存所有编辑中的行
  tableData.value.forEach(row => {
    if (row.editing) {
      row.id = row.editData.id;
      row.wellName = row.editData.wellName;
      row.wellType = row.editData.wellType;
      row.location = row.editData.location;
      row.technique = row.editData.technique;
      row.workloadDesign = row.editData.workloadDesign;
      row.deptIds = row.editData.deptIds;
      row.remark = row.editData.remark;
    }
  });

  ElMessage.success('所有更改已保存');
};

// 取消编辑
const cancelEdit = (row) => {
  // 恢复原始数据
  if (row.originalData.id) {
    row.id = row.originalData.id;
    row.wellName = row.originalData.wellName;
    row.wellType = row.originalData.wellType;
    row.location = row.originalData.location;
    row.technique = row.originalData.technique;
    row.workloadDesign = row.originalData.workloadDesign;
    row.deptIds = row.originalData.deptIds;
    row.remark = row.originalData.remark;
  } else {
    // 如果是新增行，则删除
    const index = tableData.value.indexOf(row);
    if (index !== -1) {
      tableData.value.splice(index, 1);
    }
  }

  row.editing = false;
};

// 删除行
const deleteRow = (index) => {
  tableData.value.splice(index, 1);
  ElMessage.success('行已删除');
};
</script>
