<script setup>
import { computed, reactive, ref, toRefs } from "vue";
import Pagination from "@/components/Pagination/index.vue";
import { applyBill, brokerDealLogList } from "@/api/admin/agent/order";
import { invoiceStatusDict, orderTypeDict } from "@/constant/dict";
import dayjs from "dayjs";
import { ElMessage } from "element-plus";
import DictTag from "@/components/DictTag/index.vue";
import RightToolbar from "@/components/RightToolbar/index.vue";

import { useI18n } from "vue-i18n";

const { t, locale } = useI18n();
const showSearch = ref(true);
const tableData = ref([]); // 表格数据
const total = ref(0); // 总条数
const loading = ref(false); // 遮罩层
const dialogVisible = ref(false); // 是否显示弹出层
const dialogTitle = ref(""); // 弹出层标题
const formRef = ref(null);
const queryRef = ref(null);
const ids = ref([]); // 批量删除的id集合
const data = reactive({
  form: {}, // 表单数据
  queryParams: {
    // 查询条件
    pageSize: 10,
    pageNum: 1,
    timeRange: [],
  },
  rules: {
    // 表单验证规则
    orderNumber: [
      {
        required: true,
        /*"请输入订单号"*/
        message: computed(() =>
          t("admin.form.placeholder", {
            type: t("admin.form.order"),
          })
        ),
        trigger: "blur",
      },
    ],
    companyName: [
      {
        required: true,
        /*"请输入公司名称"*/
        message: computed(() =>
          t("admin.form.placeholder", {
            type: t("admin.form.name", {
              type: t("admin.common.company"),
            }),
          })
        ),
        trigger: "blur",
      },
    ],
    // 税号
    taxNumber: [
      {
        required: true,
        message: computed(() =>
          t("admin.form.placeholder", {
            type: t("admin.form.companyTaxNumber"),
          })
        ),
        trigger: "blur",
      },
    ],
    email: [
      {
        required: true,
        message: computed(() =>
          t("admin.form.placeholder", {
            type: t("admin.form.email"),
          })
        ),
        trigger: "blur",
      },
      // email 正则验证
      {
        pattern: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/,
        message: computed(() => t("webContact.emailFormat")),
        trigger: "blur",
      },
    ],
    phone: [
      {
        required: true,
        message: computed(() => t("webContact.phone")),
        trigger: "blur",
      },
    ],
  },
});
const { form, queryParams, rules } = toRefs(data); // 解构响应式对象

/**
 * 获取列表数据
 */
const getList = () => {
  brokerDealLogList(queryParams.value).then((resp) => {
    tableData.value = resp.rows;
    total.value = resp.total;
  });
};

/**
 * 重置查询条件
 */
const resetQuery = () => {
  queryRef.value.resetFields();
  handleQuery();
};

/**
 * 查询列表数据
 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/**
 * 申请开票
 * @param row
 */
const handleApplyInvoice = (row) => {
  reset();
  form.value.id = row.id;
  console.log(row.value);
  dialogTitle.value = t("admin.table.applyInvoice");
  dialogVisible.value = true;
};

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

/**
 * 删除一条记录
 * @param id
 */
const handleDelete = (id) => {
  // const ids = id || ids.value
};

/**
 * 取消
 * @param id
 */
const handleCancel = (id) => {
  reset();
  dialogVisible.value = false;
};

/**
 * 提交表单
 */
const submit = () => {
  formRef.value.validate().then((valid) => {
    if (valid) {
      applyBill(form.value).then(() => {
        dialogVisible.value = false;
        ElMessage.success(
          t("admin.common.success", {
            action: t("identity.entrance.apply"),
          })
        );
        getList();
      });
    }
  });
};

const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id);
};

getList();
</script>

<template>
  <div class="app-container">
    <!--   搜索 订单号 查询  -->
    <el-form
      v-show="showSearch"
      ref="queryRef"
      :model="queryParams"
      class="query-form"
      inline
      @keydown="handleQuery"
      @submit.prevent
    >
      <el-form-item :label="t('admin.form.orderNumber')" prop="orderNumber">
        <el-input
          v-model="queryParams.orderNumber"
          :placeholder="
            t('admin.form.placeholder', { type: t('admin.form.orderNumber') })
          "
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery"
          >{{ t("admin.common.search") }}
        </el-button>
        <el-button @click="resetQuery">
          {{ t("admin.common.reset") }}
        </el-button>
      </el-form-item>
    </el-form>
    <el-row class="mb8">
      <right-toolbar v-model:show-search="showSearch" @query-table="getList" />
    </el-row>
    <!--    表格数据-->
    <el-table v-loading="loading" :data="tableData">
      <el-table-column
        :label="t('admin.form.orderNumber')"
        align="center"
        prop="orderNumber"
      ></el-table-column>
      <el-table-column
        :label="t('admin.form.orderType')"
        align="center"
        prop="orderType"
      >
        <template #default="{ row }">
          {{
            orderTypeDict.find((item) => item.value === row.orderType)?.[
              locale
            ] ?? "-"
          }}
        </template>
      </el-table-column>
      <el-table-column
        :label="t('admin.form.amount')"
        align="center"
        prop="amount"
      ></el-table-column>
      <el-table-column
        :label="t('admin.form.quantity')"
        align="center"
        prop="total"
      ></el-table-column>
      <el-table-column :label="t('admin.form.rechargeTime')" align="center">
        <template #default="{ row }">
          {{ dayjs(row.payTime).format("YYYY-MM-DD HH:mm:ss") }}
        </template>
      </el-table-column>
      <!--      状态-->
      <el-table-column :label="t('common.status')" align="center" prop="status">
        <template #default="{ row }">
          <dict-tag :options="invoiceStatusDict" :value="row.status" />
        </template>
      </el-table-column>
      <el-table-column :label="t('admin.common.operation')">
        <template #default="{ row }">
          <el-button
            :disabled="row.status !== '0'"
            type="text"
            @click="handleApplyInvoice(row)"
            >{{ t("admin.table.applyInvoice") }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />

    <!--    申请开票dialog-->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      append-to-body
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-position="left"
        label-width="100px"
      >
        <el-form-item
          :label="t('admin.form.name', { type: t('admin.common.company') })"
          prop="companyName"
        >
          <el-input v-model="form.companyName"></el-input>
        </el-form-item>
        <el-form-item
          :label="t('admin.form.companyTaxNumber')"
          prop="taxNumber"
        >
          <el-input v-model="form.taxNumber"></el-input>
        </el-form-item>
        <el-form-item
          :label="t('admin.form.placeholder', { type: t('admin.form.email') })"
          prop="email"
        >
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item
          :label="t('admin.form.placeholder', { type: t('webContact.phone') })"
          prop="phone"
        >
          <!--          maxlength="11"-->
          <el-input v-model="form.phone"></el-input>
        </el-form-item>
        <el-form-item :label="t('admin.form.address')" prop="address">
          <el-input v-model="form.address"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="default" @click="handleCancel"
            >{{ t("admin.common.cancel") }}
          </el-button>
          <el-button type="primary" @click="submit"
            >{{ t("admin.common.submit") }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped></style>
