<template>
  <div>
    <el-dialog v-model="projectSelectDialog.visible.value" :title="projectSelectDialog.title.value" width="80%" append-to-body>
      <el-row :gutter="20">
        <el-col :span="24">
          <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
            <div v-show="showSearch" 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" style="width: 150px"/>
                  </el-form-item>
                  <el-form-item label="项目名称" prop="projectName">
                    <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter="handleQuery" style="width: 200px"/>
                  </el-form-item>
                  <el-form-item label="项目类别" prop="projectCategory">
                    <el-select v-model="queryParams.projectCategory" placeholder="请选择项目类别" clearable style="width: 200px">
                      <el-option v-for="dict in project_category" :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-card shadow="hover">
            <vxe-table
              ref="tableRef"
              height="300px"
              border
              show-overflow
              :data="projectInfoList"
              :loading="loading"
              :row-config="{ keyField: 'projectId', isHover: true }"
              :checkbox-config="{ reserve: true, trigger: 'row', highlight: true, showHeader: prop.multiple }"
              @checkbox-all="handleCheckboxAll"
              @checkbox-change="handleCheckboxChange"
            >
              <vxe-column type="checkbox" width="50" align="center" />
              <vxe-column key="projectCode" title="项目编码" align="center" field="projectCode" width="120" />
              <vxe-column key="projectName" title="项目名称" align="center" field="projectName" width="300" />
              <vxe-column key="projectCategory" title="项目类别" align="center" field="projectCategory" width="150">
                <template #default="scope">
                  <dict-tag :options="project_category" :value="scope.row.projectCategory" />
                </template>
              </vxe-column>
              <vxe-column key="managerName" title="项目经理" align="center" field="managerName" width="120" />
              <vxe-column key="deptName" title="部门" align="center" field="deptName" width="120" />
              <vxe-column key="chargeName" title="部门负责人" align="center" field="chargeName" width="120" />
              <vxe-column key="deputyName" title="分管副总" align="center" field="deputyName" width="120" />
              <!-- <vxe-column key="business_direction" title="业务方向" align="center" field="business_direction" width="120" /> -->
              <!-- <vxe-column key="customerName" title="客户名称" align="center" field="customerName" width="120" />
              <vxe-column key="saleMaterialName" title="销售物料名称" align="center" field="saleMaterialName" width="120" /> -->
              <!--              <vxe-column key="purchasePrice" title="采购单价(元)" align="center" field="purchasePrice" width="120" />-->
              <!--              <vxe-column key="foreignPrice" title="售前对外单价(元)" align="center" field="foreignPrice" width="140" />-->
              <!--              <vxe-column key="stockingPeriod" title="备货期" align="center" field="stockingPeriod" />-->
              <!--              <vxe-column key="activeFlag" title="激活标识" align="center">-->
              <!--                <template #default="scope">-->
              <!--                  <dict-tag :options="active_flag" :value="scope.row.activeFlag"></dict-tag>-->
              <!--                </template>-->
              <!--              </vxe-column>-->
            </vxe-table>

            <pagination
              v-show="total > 0"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              :total="total"
              @pagination="pageList"
            />
          </el-card>
        </el-col>
      </el-row>

      <template #footer>
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { VxeTableInstance } from 'vxe-table';
import useDialog from '@/hooks/useDialog';
import { ProjectInfoVO, ProjectInfoQuery, ProjectInfoForm } from '@/api/oa/erp/projectInfo/types';
import { listProjectInfo } from '@/api/oa/erp/projectInfo';

interface PropType {
  modelValue?: ProjectInfoVO[] | ProjectInfoVO | undefined;
  multiple?: boolean;
  data?: string | number | (string | number)[] | undefined;
}

const prop = withDefaults(defineProps<PropType>(), {
  multiple: true,
  modelValue: undefined,
  data: undefined
});
const emit = defineEmits(['update:modelValue', 'confirmCallBack']);

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { project_category } = toRefs<any>(proxy?.useDict('project_category'));

const loading = ref(false);
const showSearch = ref(true);
const total = ref(0);
// 所有项目数据
const projectInfoList = ref<ProjectInfoVO[]>([]);
// 选中项目数据
const selectProjectList = ref<ProjectInfoVO[]>([]);

const queryFormRef = ref<ElFormInstance>();
const tableRef = ref<VxeTableInstance<ProjectInfoVO>>();

const projectSelectDialog = useDialog({
  title: '选择项目'
});

const initFormData: ProjectInfoForm = {
  projectId: undefined,
  contractFlag: undefined,
  projectCode: undefined,
  projectName: undefined,
  businessDirection: undefined,
  projectCategory: undefined,
  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,
  remark: undefined,
  activeFlag: undefined
};
const projectSelectData = reactive<PageData<ProjectInfoForm, ProjectInfoQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    contractFlag: undefined,
    projectCode: undefined,
    projectName: undefined,
    businessDirection: undefined,
    projectCategory: undefined,
    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: {}
  },
  rules: {}
});

const { queryParams, form, rules } = toRefs(projectSelectData);

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

/** 重置按钮操作 */
const resetQuery = (refresh = true) => {
  queryFormRef.value?.resetFields();
  queryParams.value.pageNum = 1;
  refresh && handleQuery();
};

// 处理单行选中
const handleCheckboxChange = (checked) => {
  // 单选模式且用户已选中时取消已选中的
  if (!prop.multiple && checked.checked) {
    tableRef.value.setCheckboxRow(selectProjectList.value, false);
    selectProjectList.value = [];
  }
  const row = checked.row;
  if (checked.checked) {
    selectProjectList.value.push(row);
  } else {
    selectProjectList.value = selectProjectList.value.filter((item) => {
      return item.projectId !== row.projectId;
    });
  }
};

const handleCheckboxAll = (checked) => {
  const rows = projectInfoList.value;
  if (checked.checked) {
    rows.forEach((row) => {
      if (!selectProjectList.value.some((item) => item.projectId === row.projectId)) {
        selectProjectList.value.push(row);
      }
    });
  } else {
    selectProjectList.value = selectProjectList.value.filter((item) => {
      return !rows.some((row) => row.projectId === item.projectId);
    });
  }
};

// 分页以及让表格显示选中某行
const pageList = async () => {
  await getList();
  const projectInfo = projectInfoList.value.filter((item) => {
    return selectProjectList.value.some((projectInfo) => projectInfo.projectId === item.projectId);
  });
  await tableRef.value.setCheckboxRow(projectInfo, true);
};

const close = () => {
  emit('confirmCallBack', []);
  projectSelectDialog.closeDialog();
};

// 选择框确定
const confirm = () => {
  emit('update:modelValue', selectProjectList.value);
  emit('confirmCallBack', selectProjectList.value);
  projectSelectDialog.closeDialog();
};

/** 查询项目信息 */
const getList = async () => {
  loading.value = true;
  const res = await listProjectInfo(queryParams.value);
  projectInfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

watch(
  () => projectSelectDialog.visible.value,
  async (newValue: boolean) => {
    if (newValue) {
      await getList(); // 初始化列表数据
    } else {
      tableRef.value.clearCheckboxReserve();
      tableRef.value.clearCheckboxRow();
      resetQuery(false);
      selectProjectList.value = [];
    }
  }
);

defineExpose({
  open: projectSelectDialog.openDialog,
  close: projectSelectDialog.closeDialog
});
</script>
