<template>
  <el-dialog v-model="dialogVisible" title="选择项目" width="980px">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="80px">
            <el-form-item label="项目号" prop="projectCode">
              <el-input v-model="queryParams.projectCode" placeholder="请输入项目编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="项目状态" prop="projectStatus">
              <el-select v-model="queryParams.projectStatus" placeholder="请选择项目状态" clearable>
                <el-option v-for="dict in project_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-table
      :data="projectList"
      border
      style="width: 100%"
      v-loading="projectLoading"
      row-key="projectId"
      :row-class-name="tableRowClassName"
      @row-click="handleRowClick"
      @expand-change="handleExpandChange"
      default-expand-all
    >
      <el-table-column type="expand" width="50">
        <template #default="props">
          <div v-if="props.row.contractFlag === '1'" class="p-3 bg-gray-50">
            <el-table
              :data="props.row.erpContractInfoVoList"
              border
              size="small"
              @row-click="handleContractRowClick($event, props.row)"
              highlight-current-row
            >
              <el-table-column width="50">
                <template #default="scope">
                  <el-radio
                    v-model="selectedContractMap[props.row.contractId]"
                    :label="scope.row.contractId"
                    @click.stop="selectContract(props.row, scope.row)"
                  >
                    <span></span>
                  </el-radio>
                </template>
              </el-table-column>
              <el-table-column prop="contractCode" label="合同编号" width="150" />
              <el-table-column prop="contractName" label="合同名称" width="150" />
              <el-table-column prop="oneCustomerName" label="客户名称" min-width="150" />
              <el-table-column prop="totalPrice" label="合同金额" width="120">
              </el-table-column>
              <el-table-column prop="contractDate" label="签订日期" width="150" />
              <el-table-column prop="contractStatus" label="合同状态" width="100">
                <template #default="props">
                  <dict-tag :options="contract_status" :value="props.row.contractStatus" />
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div v-else class="p-3 text-center text-gray-500">
            暂无合同信息
          </div>
        </template>
      </el-table-column>

      <el-table-column width="50">
        <template #default="scope">
          <el-radio
            v-model="selectedProjectId"
            :label="scope.row.projectId"
            @click.stop="selectProject(scope.row)"
            :disabled="scope.row.contractFlag === '1'"
          >
            <span></span>
          </el-radio>
        </template>
      </el-table-column>

      <el-table-column prop="projectCode" label="项目号" width="130" />
      <el-table-column prop="projectName" label="项目名称" min-width="150" />
      <el-table-column prop="amount" label="项目金额" width="110" />
      <el-table-column prop="managerName" label="项目经理" width="110" />
      <el-table-column prop="businessDirection" label="业务方向" width="110">
        <template #default="scope">
          <dict-tag :options="business_direction" :value="scope.row.businessDirection" />
        </template>
      </el-table-column>
      <el-table-column prop="contractFlag" label="有无合同" width="100">
        <template #default="scope">
          <dict-tag :options="contract_flag" :value="scope.row.contractFlag" />
        </template>
      </el-table-column>
      <el-table-column prop="projectStatus" label="项目状态" width="100">
        <template #default="scope">
          <dict-tag :options="project_status" :value="scope.row.projectStatus" />
        </template>
      </el-table-column>
    </el-table>

    <div class="mt-4 flex justify-between items-center">
      <pagination
        v-show="projectTotal > 0"
        :total="projectTotal"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getProjectList"
      />
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="confirmProjectSelection">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="ProjectSelectDialog">
import { ref, reactive, toRefs, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { getErpProjectWithContractList } from '@/api/oa/erp/projectInfo';
import { ProjectInfoVO, ProjectInfoQuery } from '@/api/oa/erp/projectInfo/types';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  projectCategory: {
    type: String,
    default: ''
  }
});

const emit = defineEmits(['update:visible', 'project-selected']);

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { business_direction, project_status, project_category, contract_status, contract_flag } = toRefs<any>(
  proxy?.useDict('business_direction', 'project_status', 'project_category', 'contract_status', 'contract_flag')
);

// 响应式数据
const dialogVisible = ref(props.visible);
const selectedProject = ref<ProjectInfoVO | null>(null);
const selectedContract = ref<any>(null);
const selectedProjectId = ref<number | null>(null);
const selectedContractMap = ref<Record<number, number>>({});
const expandedRows = ref<number[]>([]);
const projectList = ref<ProjectInfoVO[]>([]);
const projectTotal = ref(0);
const projectLoading = ref(true);
const data = reactive<{ queryParams: ProjectInfoQuery }>({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    contractFlag: undefined,
    projectCode: undefined,
    projectName: undefined,
    businessDirection: undefined,
    projectCategory: props.projectCategory,
    spareFlag: undefined,
    projectTypeId: undefined,
    paymentMethod: undefined,
    deptId: undefined,
    managerId: undefined,
    chargeId: undefined,
    deputyId: undefined,
    peopleId: undefined,
    amount: undefined,
    projectStatus: undefined,
    flowStatus: undefined,
    sortOrder: undefined,
    contractId: undefined,
    activeFlag: undefined,
    params: {}
  }
});

const { queryParams } = toRefs(data);

const queryFormRef = ref<ElFormInstance>();

// 监听visible属性变化
watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal;
  if (newVal) {
    resetSelection();
    queryParams.value.projectCategory = props.projectCategory;
    getProjectList();
  }
});

// 监听dialogVisible变化，通知父组件
watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal);
});

// 重置选择
const resetSelection = () => {
  selectedProject.value = null;
  selectedContract.value = null;
  selectedProjectId.value = null;
  selectedContractMap.value = {};
  expandedRows.value = [];
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getProjectList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.projectCategory = props.projectCategory;
  handleQuery();
};

/** 查询项目信息列表 */
const getProjectList = async () => {
  projectLoading.value = true;
  try {
    const res = await getErpProjectWithContractList(queryParams.value);
    console.log(res)
    projectList.value = res.rows;
    projectTotal.value = res.total;

    // 初始化展开状态
    expandedRows.value = [];
    resetSelection();
  } catch (error) {
    console.error('获取项目列表失败:', error);
  } finally {
    projectLoading.value = false;
  }
};

// 表格行样式
const tableRowClassName = ({ row }: { row: ProjectInfoVO }) => {
  if (row.contractFlag === '1' && row.erpContractInfoVoList?.length) {
    return 'has-contract-row';
  }
  return '';
};

// 处理行点击（展开/收起）
const handleRowClick = (row: ProjectInfoVO, column: any, event: Event) => {
  // 如果点击的是展开列，不处理
  if (column.type === 'expand') return;

  // 如果有合同，自动展开
  if (row.contractFlag === '1' && row.erpContractInfoVoList?.length) {
    const index = expandedRows.value.indexOf(row.id);
    if (index === -1) {
      expandedRows.value.push(row.id);
    } else {
      expandedRows.value.splice(index, 1);
    }
  }
};

// 处理展开变化
const handleExpandChange = (row: ProjectInfoVO, expanded: boolean) => {
  if (expanded) {
    if (!expandedRows.value.includes(row.id)) {
      expandedRows.value.push(row.id);
    }
  } else {
    const index = expandedRows.value.indexOf(row.id);
    if (index > -1) {
      expandedRows.value.splice(index, 1);
    }
  }
};

// 选择项目
const selectProject = (row: ProjectInfoVO) => {
  // 如果有合同，不能直接选择项目
  if (row.contractFlag === '1' && row.erpContractInfoVoList?.length) {
    ElMessage.warning('该项目包含合同，请选择具体合同');
    return;
  }

  selectedProject.value = row;
  selectedContract.value = null;
  selectedProjectId.value = row.id;

  // 清除该项目的合同选择
  if (selectedContractMap.value[row.id]) {
    delete selectedContractMap.value[row.id];
  }
};

// 选择合同
const selectContract = (project: ProjectInfoVO, contract: any) => {
  selectedProject.value = project;
  selectedContract.value = contract;
  selectedProjectId.value = null; // 清除项目选择
  selectedContractMap.value[project.id] = contract.id;
};

// 处理合同行点击
const handleContractRowClick = (contract: any, project: ProjectInfoVO) => {
  selectContract(project, contract);
};

// 确认项目选择
const confirmProjectSelection = () => {
  if (!selectedProject.value) {
    ElMessage.warning('请选择一个项目或合同');
    return;
  }

  // 构建返回数据
  const result = {
    project: selectedProject.value,
    contract: selectedContract.value || null,
    type: selectedContract.value ? 'contract' : 'project'
  };

  emit('project-selected', result);
  dialogVisible.value = false;
};

// 取消操作
const handleCancel = () => {
  dialogVisible.value = false;
};
</script>

<style scoped>
:deep(.has-contract-row) {
  cursor: pointer;
}

:deep(.el-table__expanded-cell) {
  padding: 0 !important;
}

:deep(.el-radio) {
  margin-right: 0;
}

:deep(.el-radio__label) {
  display: none;
}
</style>
