<template>
  <div class="p-2">
    <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="100px">
            <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="arrivalDate">
              <el-date-picker
                v-model="arrivalDateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                clearable
              />
            </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="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['oa/erp:projectReceiving:add']">新增</el-button>
          </el-col>
          <!-- 顶部修改按钮已停用，改由操作列提供入口 -->
          <!-- <el-col :span="1.5">
                        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['oa/erp:projectReceiving:edit']">修改</el-button>
                    </el-col> -->
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['oa/erp:projectReceiving:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['oa/erp:projectReceiving:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" :search="true" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="projectReceivingList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="50" align="center" v-if="columns[0].visible" />
        <el-table-column label="收货确认编号" align="center" prop="receivingCode" v-if="columns[1].visible" />
        <el-table-column label="项目号" align="center" prop="projectCode" v-if="columns[2].visible" />
        <el-table-column label="项目名称" align="center" prop="projectName" v-if="columns[3].visible" />
        <el-table-column label="项目经理" align="center" prop="projectManagerName" v-if="columns[4].visible">
          <template #default="scope">
            <span>{{ scope.row.projectManagerName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="到货日期" align="center" prop="arrivalDate" width="180" v-if="columns[5].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.arrivalDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="收货单附件" align="center" v-if="columns[6].visible">
          <template #default="scope">
            <el-button v-if="scope.row.ossId" link type="primary" icon="Download" @click="downloadOss(scope.row.ossId)"></el-button>
            <span v-else style="color: #999">暂无附件</span>
          </template>
        </el-table-column>
        <el-table-column label="部门负责人" align="center" prop="chargeName" v-if="columns[7].visible" />
        <el-table-column label="分管副总" align="center" prop="deputyName" v-if="columns[8].visible" />
        <el-table-column label="备注" align="center" prop="remark" v-if="columns[9].visible" />
        <el-table-column label="全部到货标识" align="center" prop="isAllReceiving" v-if="columns[10].visible">
          <template #default="scope">
            <dict-tag :options="is_all_receiving" :value="scope.row.isAllReceiving || ''" />
          </template>
        </el-table-column>
        <el-table-column label="业务状态" align="center" prop="receivingStatus" v-if="columns[11].visible">
          <template #default="scope">
            <dict-tag :options="receiving_status" :value="scope.row.receivingStatus || ''" />
          </template>
        </el-table-column>
        <el-table-column label="流程状态" align="center" v-if="columns[12].visible">
          <template #default="scope">
            <dict-tag :options="wf_business_status" :value="scope.row.flowStatus || 'draft'" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip
              content="修改"
              placement="top"
              v-if="!scope.row.flowStatus || scope.row.flowStatus === 'draft' || scope.row.flowStatus === 'back' || scope.row.flowStatus === 'cancel'"
            >
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['oa/erp:projectReceiving:edit']"></el-button>
            </el-tooltip>
            <el-tooltip
              content="查看"
              placement="top"
              v-if="scope.row.flowStatus && scope.row.flowStatus !== 'draft' && scope.row.flowStatus !== 'back'"
            >
              <el-button link type="info" icon="DocumentChecked" @click="handleView(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip
              content="删除"
              placement="top"
              v-if="!scope.row.flowStatus || scope.row.flowStatus === 'draft' || scope.row.flowStatus === 'back' || scope.row.flowStatus === 'cancel'"
            >
              <el-button
                link
                type="danger"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['oa/erp:projectReceiving:remove']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="审批记录" placement="top" v-if="scope.row.flowStatus && scope.row.flowStatus !== 'draft'">
              <el-button link type="warning" icon="Histogram" @click="handleApprovalRecord(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <ApprovalRecord ref="approvalRecordRef" />
  </div>
</template>

<script setup name="ProjectReceiving" lang="ts">
import { delProjectReceiving, listProjectReceiving } from '@/api/oa/erp/projectReceiving';
import { ProjectReceivingForm, ProjectReceivingQuery, ProjectReceivingVO } from '@/api/oa/erp/projectReceiving/types';

import { useRoute, useRouter } from 'vue-router';
import { onActivated } from 'vue';
import ApprovalRecord from '@/components/Process/approvalRecord.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const router = useRouter();
const route = useRoute();
const { wf_business_status, receiving_status, is_all_receiving } = toRefs<any>(
  proxy?.useDict('wf_business_status', 'receiving_status', 'is_all_receiving')
);

const projectReceivingList = ref<ProjectReceivingVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const selectedRow = ref<ProjectReceivingVO | null>(null);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const projectReceivingFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `序号`, visible: true },
  { key: 1, label: `收货确认编号`, visible: true },
  { key: 2, label: `项目号`, visible: false },
  { key: 3, label: `项目名称`, visible: true },
  { key: 4, label: `项目经理`, visible: true },
  { key: 5, label: `到货日期`, visible: true },
  { key: 6, label: `收货单附件`, visible: true },
  { key: 7, label: `部门负责人`, visible: true },
  { key: 8, label: `分管副总`, visible: true },
  { key: 9, label: `备注`, visible: true },
  { key: 10, label: `全部到货标识`, visible: true },
  { key: 11, label: `业务状态`, visible: true },
  { key: 12, label: `流程状态`, visible: false }
]);

const initFormData: ProjectReceivingForm = {
  receivingId: undefined,
  projectCode: undefined,
  projectName: undefined,
  managerId: undefined,
  arrivalDate: undefined,
  ossId: undefined,
  chargeId: undefined,
  deputyId: undefined,
  remark: undefined,
  isAllReceiving: undefined
};
const data = reactive<PageData<ProjectReceivingForm, ProjectReceivingQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectCode: undefined,
    projectName: undefined,
    managerId: undefined,
    arrivalDate: undefined,
    ossId: undefined,
    chargeId: undefined,
    deputyId: undefined,
    params: {}
  },
  rules: {
    projectCode: [{ required: true, message: '项目号不能为空', trigger: 'blur' }],
    projectName: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
    arrivalDate: [{ required: true, message: '到货日期不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);
const arrivalDateRange = ref<string[]>();

const approvalRecordRef = ref<InstanceType<typeof ApprovalRecord>>();
const refreshFlagKey = 'projectReceivingListShouldRefresh';

/** 查询项目收货确认列表 */
const getList = async () => {
  loading.value = true;
  const res = await listProjectReceiving(queryParams.value);
  projectReceivingList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  // reset();
  // dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  // form.value = {...initFormData};
  // projectReceivingFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  if (arrivalDateRange.value && arrivalDateRange.value.length === 2) {
    queryParams.value.params.beginTime = arrivalDateRange.value[0];
    queryParams.value.params.endTime = arrivalDateRange.value[1];
  } else {
    if (queryParams.value.params) {
      queryParams.value.params.beginTime = undefined as any;
      queryParams.value.params.endTime = undefined as any;
    }
  }
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  arrivalDateRange.value = undefined; // 清空日期范围
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ProjectReceivingVO[]) => {
  ids.value = selection.map((item) => item.receivingId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  selectedRow.value = selection.length === 1 ? selection[0] : null;
};

/** 新增按钮操作（与项目信息保持一致） */
const handleAdd = () => {
  proxy?.$tab.closePage(route);
  router.push({
    path: '/project/projectReceiving/edit',
    query: { type: 'add' }
  });
};

/** 修改按钮操作（与项目信息保持一致） */
const handleUpdate = async (row?: ProjectReceivingVO) => {
  const target = row || (selectedRow.value as any);
  if (!target) return;
  proxy?.$tab.closePage(route);
  router.push({
    path: '/project/projectReceiving/edit',
    query: { id: target.receivingId, type: 'update' }
  });
};

/** 查看按钮操作（与项目信息保持一致） */
const handleView = (row: ProjectReceivingVO) => {
  proxy?.$tab.closePage(route);
  router.push({
    path: '/project/projectReceiving/edit',
    query: { id: row.receivingId, type: 'view' }
  });
};

/** 提交按钮 */
// const submitForm = () => { /* 对话框流程已停用，改用编辑页 */ }

// const submitAndStartFlow = async () => { /* 对话框流程已停用，改用编辑页 */ }

/** 删除按钮操作 */
const handleDelete = async (row?: ProjectReceivingVO) => {
  const _receivingIds = row?.receivingId || ids.value;
  await proxy?.$modal.confirm('是否确认删除项目收货确认编号为"' + _receivingIds + '"的数据项？').finally(() => (loading.value = false));
  await delProjectReceiving(_receivingIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'oa/erp/projectReceiving/export',
    {
      ...queryParams.value
    },
    `projectReceiving_${new Date().getTime()}.xlsx`
  );
};

/** 检查是否需要刷新列表 */
const checkShouldRefresh = () => {
  const flag = sessionStorage.getItem(refreshFlagKey);
  if (flag) {
    sessionStorage.removeItem(refreshFlagKey);
    handleQuery();
  }
};

onMounted(() => {
  getList();
  checkShouldRefresh();
});

onActivated(() => {
  checkShouldRefresh();
});

const downloadOss = (ossId: string | number) => {
  proxy?.$download.oss(ossId as any);
};

const handleApprovalRecord = (row: ProjectReceivingVO) => {
  approvalRecordRef.value?.init(row.receivingId as any);
};
</script>
