<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">
            <el-form-item label="关键字" prop="searchValue">
              <el-input v-model="queryParams.searchValue" placeholder="客户名称/编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="单据日期" prop="createTime">
              <el-input v-model="queryParams.createTime" placeholder="请选择单据日期" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="单据编号" prop="orderRevenueCode">
              <el-input v-model="queryParams.orderRevenueCode" placeholder="请输入单据编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="业务员" prop="businessStaff">
              <el-input v-model="queryParams.businessStaff" placeholder="请输入业务员" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="客服" prop="customerService">
              <el-input v-model="queryParams.customerService" placeholder="请输入客服" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="关联费用" prop="isPrwTax">
              <el-select v-model="queryParams.isPrwTax" clearable>
                <el-option v-for="dict in sys_platform_yes_no" :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="22"> 收入申请单信息列表 </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['order:revenueHeader:add']">新增</el-button>
          </el-col>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="revenueHeaderList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="单据日期" align="center" prop="createTime">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="单据编号" align="center" prop="orderRevenueCode" />
        <el-table-column label="客户名称" align="center" prop="customerName" />
        <el-table-column label="业务员" align="center" prop="businessStaff" />
        <el-table-column label="客服" align="center" prop="customerService" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="是否关联" align="center" prop="isPrwTax">
          <template #default="scope">
            <dict-tag :options="sys_platform_yes_no" :value="scope.row.isPrwTax" />
          </template>
        </el-table-column>
        <el-table-column label="审核状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="check_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleAudit(scope.row)"
              v-if="scope.row.status == '0'"
              v-hasPermi="['order:revenueHeader:edit']"
              >审核</el-button
            >
            <el-button link type="primary" icon="Edit" @click="handleExpenseApply(scope.row)" v-hasPermi="['order:revenueHeader:edit']"
              >费用申请</el-button
            >
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['order:revenueHeader:edit']">编辑</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['order:revenueHeader:remove']">删除</el-button>
          </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>
    <!-- 添加或修改收入单主对话框 -->
  </div>
</template>

<script setup name="RevenueHeader" lang="ts">
import {
  listRevenueHeader,
  getRevenueHeader,
  delRevenueHeader,
  addRevenueHeader,
  updateRevenueHeader,
  changeStatus
} from '@/api/order/revenueHeader';
import { RevenueHeaderVO, RevenueHeaderQuery, RevenueHeaderForm } from '@/api/order/revenueHeader/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_platform_yes_no, check_status, revenue_type } = toRefs<any>(proxy?.useDict('sys_platform_yes_no', 'check_status', 'revenue_type'));

const revenueHeaderList = ref<RevenueHeaderVO[]>([]);
const buttonLoading = ref(false);
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 router = useRouter();
const queryFormRef = ref<ElFormInstance>();
const revenueHeaderFormRef = ref<ElFormInstance>();

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

const initFormData: RevenueHeaderForm = {
  id: undefined,
  revenueType: undefined,
  orderRevenueCode: undefined,
  incomeOrderCode: undefined,
  otherRevenueType: undefined,
  customerId: undefined,
  supplierId: undefined,
  isPrwTax: undefined,
  currencyId: undefined,
  pushStatus: undefined,
  orderFile: undefined,
  status: undefined,
  remark: undefined
};
const data = reactive<PageData<RevenueHeaderForm, RevenueHeaderQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    revenueType: '0',
    orderRevenueCode: undefined,
    incomeOrderCode: undefined,
    otherRevenueType: undefined,
    customerId: undefined,
    supplierId: undefined,
    isPrwTax: undefined,
    currencyId: undefined,
    pushStatus: undefined,
    orderFile: undefined,
    status: undefined,
    platformCode: undefined,
    params: {}
  },
  rules: {
    customerId: [{ required: true, message: '客户id不能为空', trigger: 'blur' }]
  }
});

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

/** 查询收入单主列表 */
const getList = async () => {
  loading.value = true;
  const res = await listRevenueHeader(queryParams.value);
  revenueHeaderList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

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

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

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

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

/** 新增按钮操作 */
const handleAdd = () => {
  router.push({
    path: '/order-center/order-revenue-add',
    query: { revenueType: '0' } // 收入申请
  });
};

/** 费用申请按钮操作 */
const handleExpenseApply = (row?: RevenueHeaderVO) => {
  router.push({
    path: '/order-center/order-revenue-add',
    query: { revenueType: '1' } // 费用申请
  });
};

/** 修改按钮操作 */
const handleUpdate = async (row?: RevenueHeaderVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  router.push({
    path: '/order-center/order-revenue-add',
    query: { revenueType: row.revenueType, id: _id }
  });
};

/** 审核按钮操作 */
const handleAudit = async (row: RevenueHeaderVO) => {
  try {
    await proxy?.$modal.confirm('是否确认审核该收入单？');

    // 更新状态为已审核
    await changeStatus(row.id, '1');

    proxy?.$modal.msgSuccess('审核成功');
    await getList();
  } catch (error) {
    console.error('审核失败:', error);
  }
};

/** 提交按钮 */
const submitForm = () => {
  revenueHeaderFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateRevenueHeader(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addRevenueHeader(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

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

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

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

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