<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="mailingApplyCode">
              <el-input v-model="queryParams.mailingApplyCode" placeholder="请输入" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="经手人" prop="handlerName">
              <el-input v-model="queryParams.handlerName" placeholder="请输入" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="邮寄类型" prop="mailingType">
              <el-select v-model="queryParams.mailingType" placeholder="请选择" clearable>
                <el-option v-for="dict in mailing_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="申请状态" prop="mailingApplyStatus">
              <el-select v-model="queryParams.mailingApplyStatus" placeholder="请选择" clearable>
                <el-option v-for="dict in mailing_apply_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="物流状态" prop="logisticsStatus">
              <el-select v-model="queryParams.logisticsStatus" placeholder="请选择" clearable>
                <el-option v-for="dict in logistics_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-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/crm:crmMailingApply:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['oa/crm:crmMailingApply:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['oa/crm:crmMailingApply:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['oa/crm:crmMailingApply: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="crmMailingApplyList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
<!--        <el-table-column label="序号" type="index" width="60" align="center" />-->
        <el-table-column label="申请编号" align="center" prop="mailingApplyCode" min-width="140" />
        <el-table-column label="申请日期" align="center" prop="applicationDate" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.applicationDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="快递单号" align="center" prop="expressNo" width="140" />
        <el-table-column label="经手人" align="center" prop="handlerName" width="100" />
        <el-table-column label="部门" align="center" prop="deptName" width="120" />
        <el-table-column label="省份" align="center" prop="province" width="80" />
        <el-table-column label="重量(kg)" align="center" prop="weight" width="80" />
        <el-table-column label="邮寄类型" align="center" prop="mailingType" width="140">
          <template #default="scope">
            <dict-tag :options="mailing_type" :value="scope.row.mailingType" />
          </template>
        </el-table-column>
        <el-table-column label="邮寄费用" align="center" prop="mailingFee" width="90" />
        <el-table-column label="项目名称" align="center" prop="projectName" min-width="150" show-overflow-tooltip />
        <el-table-column label="申请状态" align="center" prop="mailingApplyStatus" width="100">
          <template #default="scope">
            <dict-tag :options="mailing_apply_status" :value="scope.row.mailingApplyStatus" />
          </template>
        </el-table-column>
        <el-table-column label="物流状态" align="center" prop="logisticsStatus" width="90">
          <template #default="scope">
            <dict-tag :options="logistics_status" :value="scope.row.logisticsStatus" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="120" class-name="small-padding fixed-width">
          <template #default="scope">
            <!-- 查看按钮：非草稿状态显示 -->
            <el-tooltip content="查看" placement="top" v-if="scope.row.mailingApplyStatus !== '1'">
              <el-button link type="primary" icon="DocumentChecked" @click="handleView(scope.row)" v-hasPermi="['oa/crm:crmMailingApply:query']"></el-button>
            </el-tooltip>
            <!-- 修改按钮：仅草稿状态显示 -->
            <el-tooltip content="修改" placement="top" v-if="scope.row.mailingApplyStatus === '1'">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['oa/crm:crmMailingApply:edit']"></el-button>
            </el-tooltip>
            <!-- 审批记录按钮：审批中或已审批状态显示 -->
<!--            <el-tooltip content="审批记录" placement="top" v-if="scope.row.mailingApplyStatus === '2' || scope.row.mailingApplyStatus === '3'">-->
<!--              <el-button-->
<!--                link-->
<!--                type="primary"-->
<!--                icon="Tickets"-->
<!--                @click="handleApprovalRecord(scope.row)"-->
<!--                v-hasPermi="['oa/crm:crmMailingApply:query']"-->
<!--              ></el-button>-->
<!--            </el-tooltip>-->
            <!-- 删除按钮：仅草稿状态显示 -->
            <el-tooltip content="删除" placement="top" v-if="scope.row.mailingApplyStatus === '1'">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['oa/crm:crmMailingApply:remove']"
              ></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="CrmMailingApply" lang="ts">
import { delCrmMailingApply, listCrmMailingApply } from '@/api/oa/crm/crmMailingApply';
import { CrmMailingApplyQuery, CrmMailingApplyVO } from '@/api/oa/crm/crmMailingApply/types';
import ApprovalRecord from '@/components/Process/approvalRecord.vue';
import { parseTime } from '@/utils/ruoyi';

const router = useRouter();
const route = useRoute();
const approvalRecordRef = ref<InstanceType<typeof ApprovalRecord>>();

const { proxy } = getCurrentInstance() as any;
const { mailing_apply_status, wf_business_status, logistics_status, mailing_type } = toRefs<any>(
  proxy?.useDict('mailing_apply_status', 'wf_business_status', 'logistics_status', 'mailing_type')
);

const crmMailingApplyList = ref<CrmMailingApplyVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();

// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `申请编号`, visible: true },
  { key: 1, label: `申请日期`, visible: true },
  { key: 2, label: `经手人`, visible: true },
  { 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 }
]);

const queryParams = ref<CrmMailingApplyQuery>({
  pageNum: 1,
  pageSize: 10,
  mailingApplyCode: undefined,
  handlerName: undefined,
  mailingType: undefined,
  mailingApplyStatus: undefined,
  logisticsStatus: undefined,
  params: {}
});

/** 获取编辑页路由地址（兼容动态菜单路由与静态路由） */
const getEditPath = () => {
  const currentPath = route.path || '';
  if (currentPath.startsWith('/mailing/')) {
    return '/mailing/crmMailingApply/edit';
  }
  return '/oa/crm/crmMailingApply/edit';
};

/** 查询邮寄申请列表 */
const getList = async () => {
  loading.value = true;
  const res = await listCrmMailingApply(queryParams.value);
  crmMailingApplyList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: CrmMailingApplyVO[]) => {
  ids.value = selection.map((item) => item.mailingApplyId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 - 跳转到编辑页 */
const handleAdd = () => {
  proxy.$tab.closePage(route);
  router.push({
    path: getEditPath(),
    query: { type: 'add' }
  });
};

/** 修改按钮操作 - 跳转到编辑页 */
const handleUpdate = async (row?: CrmMailingApplyVO) => {
  const _mailingApplyId = row?.mailingApplyId || ids.value[0];
  proxy.$tab.closePage(route);
  router.push({
    path: getEditPath(),
    query: {
      id: _mailingApplyId,
      type: 'update'
    }
  });
};

/** 查看按钮操作 - 跳转到查看页 */
const handleView = (row: CrmMailingApplyVO) => {
  proxy.$tab.closePage(route);
  router.push({
    path: getEditPath(),
    query: {
      id: row.mailingApplyId,
      type: 'view'
    }
  });
};

/** 审批记录按钮操作 */
const handleApprovalRecord = (row: CrmMailingApplyVO) => {
  approvalRecordRef.value?.init(row.mailingApplyId);
};

/** 删除按钮操作 */
const handleDelete = async (row?: CrmMailingApplyVO) => {
  const _mailingApplyIds = row?.mailingApplyId || ids.value;
  await proxy?.$modal.confirm('是否确认删除邮寄申请编号为"' + _mailingApplyIds + '"的数据项？').finally(() => (loading.value = false));
  await delCrmMailingApply(_mailingApplyIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

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

onMounted(() => {
  getList();
});
</script>
