<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="manufacturerId">
            <el-select
              clearable
              @clear="zzClear"
              v-model="formData.manufactureName"
              :placeholder="t('deviceForm.mfgHolder')"
              @click="openCustomerZz"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结算方式" prop="payment">
            <el-input v-model="formData.payment" placeholder="请输入结算方式" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="合同名称" prop="contractName">
            <el-input v-model="formData.contractName" placeholder="请输入合同名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同编号" prop="contractCode">
            <el-input v-model="formData.contractCode" placeholder="请输入合同编号" />
          </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="请输入工作量总数" />
          </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="选择开始时间"
            />
          </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="选择完成时间"
            />
          </el-form-item>
        </el-col>
      </el-row>
<!--      <el-row>
        <el-col :span="12">
          <el-form-item label="施工地点" prop="location">
            <el-input v-model="formData.location" placeholder="请输入施工地点" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="施工工艺" prop="technique">
            <el-input v-model="formData.technique" placeholder="请输入施工工艺" />
          </el-form-item>
        </el-col>
      </el-row>-->
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" type="textarea" />
      </el-form-item>
    </el-form>
  </ContentWrap>
<!--  <ContentWrap>
    <el-form>
      <el-button
        type="primary"
        plain
        @click="openForm('create')"
        v-hasPermi="['rq:iot-project-info:create']"
      >
        <Icon icon="ep:plus" class="mr-5px" />任务拆分
      </el-button>
    </el-form>
    <el-table v-loading="loading" :data="taskList" :stripe="true" :show-overflow-tooltip="true">
      &lt;!&ndash; 添加序号列 &ndash;&gt;
      <el-table-column
        type="index"
        label="序号"
        width="60"
        align="center"
      />
      <el-table-column label="井号" align="center" prop="wellName" />
      <el-table-column label="井型/井别" align="center" prop="wellType" />
      <el-table-column label="施工地点" align="center" prop="location" />
      <el-table-column label="施工工艺" align="center" prop="technique" />
      <el-table-column label="设计工作量" align="center" prop="workloadDesign" />
      <el-table-column label="所属队伍" align="center" prop="deptList" />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <div style="display: flex; justify-content: center; align-items: center; width: 100%">
            &lt;!&ndash; 新增配置按钮 &ndash;&gt;
            <div style="margin-left: 12px">
              <el-button
                link
                type="primary"
                @click="openConfigDialog(scope.row)"
              >
                推迟保养
              </el-button>
            </div>
            <div style="margin-left: 12px">
              <el-button
                link
                type="primary"
                @click="openMaterialForm(scope.row)"
              >
                选择物料
              </el-button>
            </div>
            <div style="margin-left: 12px">
              <el-button
                link
                type="primary"
                @click="handleView(scope.row.bomNodeId)"
              >
                物料详情
              </el-button>
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>-->

  <CustomerList ref="customerZzFormRef" @choose="customerZzChoose" />
<!--  <IotProjectTaskForm ref="formRef1" @success="getList" />-->
<!--  <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="暂无数据">
&lt;!&ndash;          <el-table-column prop="id" label="ID" width="80">
            <template #default="{ row }">
              <span v-if="!row.editing">{{ row.id }}</span>
              <el-input v-else v-model="row.editData.id" disabled class="edit-input" />
            </template>
          </el-table-column>&ndash;&gt;

          <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 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 IotProjectTaskForm from '@/views/pms/iotprojectinfo/IotProjectTaskForm.vue'
import CustomerList from '@/views/pms/device/CustomerList.vue'
import {ref} from "vue";
/** 项目信息 表单 */
defineOptions({ name: 'IotProjectInfo' })
const { params, name } = useRoute() // 查询参数
import {useUserStore} from "@/store/modules/user";
import {IotProjectTaskApi, IotProjectTaskVO} from "@/api/pms/iotprojecttask";
import {ElMessageBox} from "element-plus";
import {updateConfig} from "@/api/infra/config";
import {useTagsViewStore} from "@/store/modules/tagsView";
const id = params.id
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 formType = ref('') // 表单的类型：create - 新增；update - 修改
const loading = ref(true) // 列表的加载中
const formData = ref({
  id: undefined,
  deptId: useUserStore().getUser.deptId,
  deptName: undefined,
  contractName: undefined,
  contractCode: undefined,
  workloadTotal: undefined,
  workloadFinish: undefined,
  startTime: undefined,
  endTime: undefined,
  location: undefined,
  technique: undefined,
  payment: undefined,
  userName: useUserStore().getUser.name,
  userId: useUserStore().getUser.userId,
})
const close = () => {
  delView(unref(currentRoute))
  push({ name: 'iotProjectInfo', params:{}})
}

const queryParams = reactive({
  projectId:undefined
})
const formRules = reactive({
  manufacturerId: [{ required: true, message: '客户不能为空', trigger: 'blur' }],
  payment: [{ required: true, message: '结算方式不能为空', trigger: 'blur' }],
  contractName: [{ required: true, message: '合同名称不能为空', trigger: 'blur' }],
  contractCode: [{ required: true, message: '合同编码不能为空', trigger: 'blur' }],
  workloadTotal: [{ required: true, message: '工作量总数不能为空', trigger: 'blur' }],
  startTime: [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
  endTime: [{ required: true, message: '结束时间不能为空', trigger: 'blur' }],
})
const formRef1 = ref() // 表单 Ref
const openForm = (type: string, id?: number) => {
  formRef1.value.open(type, id)
}
const zzClear = () =>{
  formData.value.manufacturerId = undefined
  formData.value.manufactureName = undefined
}

const customerZzChoose = (row) => {
  formData.value.manufacturerId = row.id
  // zzLabel.value = row.name
  formData.value.manufactureName = row.name
}
const customerZzFormRef = ref()
const openCustomerZz = () => {
  customerZzFormRef.value.open()
}
// 根据部门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,
    wellName: '',
    wellType: '',
    location: '',
    technique: '',
    workloadDesign: '',
    deptIds: [],
    remark:'',
    editData: {},
    editing:true,
    originalData: {},
    errors: {}
  },
]);
let deptInfo: any[] = "";
/** 打开弹窗 */
const open = async () => {
 /* dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type*/
  resetForm()
  // 修改时，设置数据
  if (id) {
    formType.value = 'update';
    formLoading.value = true
    try {
      formData.value = await IotProjectInfoApi.getIotProjectInfo(id)
      /*queryParams.projectId = id;
      const data = await IotProjectTaskApi.getIotProjectTaskPage(queryParams);
      tableData.value = data.list
      tableData.value.forEach(item=>{
        item.deptIds = [167,168];
        item.editData={};
        item.originalData={};
        item.errors={};
      })*/
    } finally {
      formLoading.value = false
    }
  }else{
    formType.value = 'create';
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const formRef = ref() // 表单 Ref
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    formData.value.deptId = useUserStore().getUser.deptId;
    const data = {
      projectData: formData.value as unknown as IotProjectInfoVO,
      //taskList:tableData.value
    }
    if (formType.value === 'create') {
      await IotProjectInfoApi.createIotProjectInfo(data)
      message.success(t('common.createSuccess'))
    } else {
      await IotProjectInfoApi.updateIotProjectInfo(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
    close()
  } finally {
    formLoading.value = false
  }
}

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

const showCloumn = false;
// 表格数据

// 计算正在编辑的行数
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.name = '井号不能为空';
    valid = false;
  }

  if (!row.editData.wellType || row.editData.wellType.trim() === '') {
    row.errors.email = '井型不能为空';
    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>
