<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="t('iotDevice.company')" prop="deptId">
            <el-tree-select
              :disabled="isDeptDisabled"
              v-model="formData.deptId"
              :data="deptList"
              :props="defaultProps"
              check-strictly
              node-key="id"
              filterable
              placeholder="请选择所属公司"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="责任人" prop="responsiblePerson">
            <span v-if="selectedUserNames" class="user-names">
              {{ selectedUserNames }}
            </span>
            <el-button
              type="primary"
              size="small"
              @click="openUserDialog"
              style="margin-left: 10px;"
              :disabled="!formData.deptId"
            >
              选择责任人
            </el-button>
            <div v-if="!formData.deptId" class="el-form-item__error">请先选择所属公司</div>
          </el-form-item>
        </el-col>

      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" placeholder="请输入备注" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </ContentWrap>

  <CustomerList ref="customerZzFormRef" @choose="customerZzChoose" />

  <!-- 责任人选择对话框 -->
  <el-dialog
    v-model="userDialogVisible"
    title="选择责任人"
    width="1000px"
    :before-close="handleUserDialogClose"
    class="user-select-dialog"
  >
    <div class="transfer-container">
      <el-transfer
        v-model="selectedUserIds"
        :data="userList"
        :titles="['可选人员', '已选人员']"
        :props="{ key: 'id', label: 'nickname' }"
        filterable
        class="transfer-component"
      >
        <template #default="{ option }">
          <el-tooltip
            effect="dark"
            placement="top"
            :content="`${option.nickname} - ${option.deptName || '未分配部门'}`"
          >
            <span class="transfer-option-text">
              {{ option.nickname }} - {{ option.deptName || '未分配部门' }}
            </span>
          </el-tooltip>
        </template>
      </el-transfer>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleUserDialogClose">取消</el-button>
        <el-button type="primary" @click="confirmUserSelection">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <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";
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";
import * as UserApi from "@/api/system/user";
import {UserVO} from "@/api/system/user";

/** 项目信息 表单 */
defineOptions({ name: 'IotProjectInfo' })

const { params, name } = useRoute() // 查询参数
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 simpleUsers = ref<UserVO[]>([])     // 责任人列表

// 添加责任人相关变量
const userDialogVisible = ref(false);
const userList = ref([]); // 所有用户列表
const selectedUserIds = ref([]); // 选中的用户ID
const selectedUserNames = ref(''); // 选中的用户名称显示
const selectedUserList = ref([]); // 存储选中的用户对象列表

const formData = ref({
  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: 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()
}

// 格式化用户名称显示
const formatUserNames = (users) => {
  if (!users || users.length === 0) return '';

  const names = users.map(user => user.nickname);

  if (names.length <= 2) {
    return names.join(', ');
  } else {
    return `${names[0]}, ${names[1]}...`;
  }
};

// 根据用户ID获取用户信息
const fetchUserInfoByIds = async (userIds) => {
  if (!userIds || userIds.length === 0) {
    selectedUserList.value = [];
    selectedUserNames.value = '';
    return;
  }

  try {
    const params = {
      userIds: userIds
    };
    const response = await UserApi.companyDeptsEmployee(params); // 假设有这个API
    selectedUserList.value = response;
    selectedUserNames.value = formatUserNames(response);
  } catch (error) {
    console.error('获取用户信息失败:', error);
    ElMessage.error('获取用户信息失败');
  }
};

// 根据部门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 isDeptDisabled = computed(() => {
  return formType.value === 'update' || deptList.value.length === 1;
});

// 打开用户选择对话框
const openUserDialog = async () => {
  try {
    // 获取用户列表，传递部门ID参数
    const params = {
      deptIds: [formData.value.deptId] // 将部门ID转换为数组格式
    };
    // 获取用户列表
    const response = await UserApi.companyDeptsEmployee(params);
    userList.value = response;

    // 设置当前已选中的用户
    selectedUserIds.value = formData.value.responsiblePerson || [];

    userDialogVisible.value = true;

  } catch (error) {
    console.error('获取用户列表失败:', error);
    ElMessage.error('获取用户列表失败');
  }
};

// 确认用户选择
const confirmUserSelection = () => {
  // 更新表单数据
  formData.value.responsiblePerson = [...selectedUserIds.value];

  // 更新显示的用户名称
  updateSelectedUserNames();

  userDialogVisible.value = false;
};

// 更新显示的用户名称
const updateSelectedUserNames = () => {
  console.log('已经保存的责任人：' + formData.value.responsiblePerson)
  if (!formData.value.responsiblePerson || formData.value.responsiblePerson.length === 0) {
    selectedUserNames.value = '';
    return;
  }

  const selectedUsers = userList.value.filter(user =>
    formData.value.responsiblePerson.includes(user.id)
  );

  const names = selectedUsers.map(user => user.nickname);

  if (names.length <= 2) {
    selectedUserNames.value = names.join(', ');
  } else {
    selectedUserNames.value = `${names[0]}, ${names[1]}...`;
  }
};

// 关闭用户选择对话框
const handleUserDialogClose = () => {
  userDialogVisible.value = false;
};

const tableData = ref([
  {
    id: 1,
    wellName: '',
    wellType: '',
    location: '',
    technique: '',
    workloadDesign: '',
    deptIds: [],
    remark:'',
    editData: {},
    editing:true,
    originalData: {},
    errors: {}
  },
]);
let deptInfo: any[] = "";
/** 打开弹窗 */
const open = async () => {
  resetForm()
  // 修改时，设置数据
  if (id) {
    formType.value = 'update';
    formLoading.value = true
    try {
      formData.value = await IotProjectInfoApi.getIotProjectInfo(id)

      // 如果已有责任人数据，获取用户信息并显示
      if (formData.value.responsiblePerson && formData.value.responsiblePerson.length > 0) {
        await fetchUserInfoByIds(formData.value.responsiblePerson);
        selectedUserIds.value = [...formData.value.responsiblePerson];
      }

      // 如果已有责任人数据，更新显示
      if (formData.value.responsiblePerson) {
        // updateSelectedUserNames();
      }
    } finally {
      formLoading.value = false
    }
  } else {
    formType.value = 'create';
    // 如果只有一个部门，则自动选中
    if (deptList.value.length === 1) {
      formData.value.deptId = deptList.value[0].id;
    }
  }
}

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,
    responsiblePerson: [], // 重置责任人字段
  }
  selectedUserNames.value = '';
  formRef.value?.resetFields()
}
onMounted(async () => {
  // deptList.value = handleTree(await DeptApi.getSimpleDeptList())
  // 查询当前登录人所属的 公司级部门 如果部门列表只有一个值 默认选中
  deptList.value = await DeptApi.companyLevelDepts()

  // 如果只有一个部门，则自动选中
  if (deptList.value.length === 1) {
    formData.value.deptId = deptList.value[0].id;
  }
  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>

<style scoped>
.user-names {
  padding: 5px 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #f5f7fa;
  display: inline-block;
  min-width: 200px;
}

.transfer-container {
  text-align: center;
  padding: 20px 0;
}

/* 3. 直接调整 el-transfer 左右窗口的宽度 */
:deep(.el-transfer-panel) {
  width: 40% !important; /* 强制设置左右面板宽度，确保两侧面板对等 */
}

.transfer-component {
  width: 100%;
  min-width: 600px;
}

:deep(.el-transfer-panel__item) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100%;
  padding: 6px 6px;
}

.transfer-option-text {
  display: inline-block;
  max-width: 100%;
}

:deep(.el-transfer-panel__list) {
  width: 100% !important; /* 使面板内部内容宽度占满 */
}

</style>
