<template>
  <div class="app-container">
    <!-- <el-form
      v-show="showSearch"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="企业名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入企业名称"
          clearable
          size="default"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属站点" prop="tenantId">
        <SiteOptions v-model="queryParams.tenantId" :site-list="siteList" />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="search"
          size="default"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="refresh" size="default" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form> -->

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="plus"
          size="default"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="upload"
          size="default"
          @click="handleImport"
          >导入</el-button
        >
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="download"
          size="default"
          @click="handleExport"
          >导出</el-button
        >
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataList">
      <el-table-column label="订单号" align="center" prop="orderNumber" />
      <el-table-column label="公司名称" align="center" prop="enterpriseName" />
      <el-table-column label="订单类型" align="center">
        <template #default="{ row }">
          {{ orderTypeDic[row.orderType] }}
        </template>
      </el-table-column>
      <el-table-column label="金额" align="center" prop="amount" />
      <el-table-column label="数量" align="center" prop="total" />
      <!-- <el-table-column label="申请状态" align="center" prop="status" /> -->
      <el-table-column label="充值时间" align="center" prop="payTime" />

      <el-table-column label="操作" align="center">
        <template #default="{ row }">
          <el-button
            size="small"
            type="text"
            icon="edit"
            @click="handleEdit(row.id)"
            >修改</el-button
          >
          <el-button
            size="small"
            type="text"
            icon="delete"
            @click="handleDelete(row.id)"
            >删除</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-dialog :title="upload.title" v-model="showEditDialog" append-to-body>
      <el-form
        :model="queryParams"
        ref="queryFormRef"
        :rules="rules"
        :labelWidth="140"
      >
        <!-- <el-row>
          <el-col :span="12">
            <el-form-item label="企业ID" prop="enterpriseId">
              <el-select v-model="form.enterpriseId">
                <el-option
                  v-for="item in [1, 2, 3, 4, 5]"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业名称" prop="enterpriseName">
              <el-input v-model="form.enterpriseName"></el-input>
            </el-form-item>
          </el-col>
        </el-row> -->
        <div
          style="
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
          "
        >
          <el-form-item label="企业名称" prop="enterpriseId">
            <el-select
              v-model="form.enterpriseId"
              :disabled="!enterpriseList.length"
            >
              <el-option
                v-for="item in enterpriseList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="订单号" prop="orderNumber">
            <el-input v-model="form.orderNumber"></el-input>
          </el-form-item>
          <el-form-item label="住址" prop="address">
            <el-input v-model="form.address"></el-input>
          </el-form-item>
          <el-form-item label="金额" prop="amount">
            <el-input-number v-model="form.amount"></el-input-number>
          </el-form-item>
          <el-form-item label="电子邮箱" prop="email">
            <el-input v-model="form.email"></el-input>
          </el-form-item>
          <el-form-item label="充值时间" prop="payTime">
            <el-date-picker
              v-model="form.payTime"
              type="datetime"
              format="YYYY-MM-DD HH:mm:ss"
              placeholder="选择充值时间"
            />
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input v-model="form.phone"></el-input>
          </el-form-item>
          <el-form-item label="公司税号" prop="taxNumber">
            <el-input v-model="form.taxNumber"></el-input>
          </el-form-item>
          <el-form-item label="数量" prop="total">
            <el-input-number v-model="form.total"></el-input-number>
          </el-form-item>
          <el-form-item label="订单类型" prop="orderType">
            <el-select v-model="form.orderType">
              <el-option label="创新币充值" value="1" />
              <el-option label="活动报名" value="2" />
            </el-select>
          </el-form-item>
        </div>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitOrderForm">提 交</el-button>
          <el-button @click="showEditDialog = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="OrderList">
import { companyList } from "@/api/dataList/enterprise";
import dayjs from "dayjs";
import {
  casDealLogList,
  addDealLog,
  DealLogDetail,
  updateDealLog,
} from "@/api/order";
import { getToken } from "@/utils/auth";
import SiteOptions from "@/views/components/SiteOptions";
// import axios from "axios";
// import { download } from "@/utils/request";
// import dayjs from "dayjs";
import { tansParams, blobValidate } from "@/utils/ruoyi";
import { saveAs } from "file-saver";
import { tenantSelect } from "@/api/subPlatform/tenant";
import { reactive, ref, toRefs } from "vue";
import { useRouter } from "vue-router";
import { enterpriseOptions } from "@/utils/parameter";
import { ElLoading, ElMessage, ElMessageBox } from "element-plus";

const router = useRouter();
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    // examine_status: 2,
    // name: undefined,
    // tenantId: undefined,
  },
  rules: {},
  form: {},
});
const orderTypeDic = {
  1: "创新币充值",
  2: "活动报名",
};
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  // updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/business/enterprise/importData",
});

const { queryParams, form, rules } = toRefs(data);
const showSearch = ref(true);
const siteList = ref([]);
const loading = ref(true);
const total = ref(0);
const dataList = ref([]);
const showEditDialog = ref(false);
const enterpriseList = ref([]);
const queryFormRef = ref();
const formRef = ref();
/** 查询订单列表 */
const getList = async () => {
  loading.value = true;
  const resp = await casDealLogList(queryParams.value);
  dataList.value = resp.rows;
  total.value = resp.total;
  loading.value = false;
};

// 表单重置
const reset = () => {
  form.value = {};
  if (formRef.value) {
    formRef.value.resetFields();
  }
};
// 获取站点列表
const getSiteList = async () => {
  const resp = await tenantSelect();
  siteList.value = resp.rows;
};
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = [];
  if (queryFormRef.value) {
    queryFormRef.value.resetFields();
  }
  handleQuery();
};
const handleAdd = async () => {
  reset();
  const resp = await companyList();
  enterpriseList.value = resp.rows;
  showEditDialog.value = true;
};
const handleEdit = async (id) => {
  reset();
  const orderInfo = await DealLogDetail(id);
  console.log(orderInfo);
  form.value = orderInfo.data;
  const resp = await companyList();
  enterpriseList.value = resp.rows;
  showEditDialog.value = true;
};
const handleDetail = (id) => {
  router.push({
    path: "/dataList/enterprise/add",
    query: { id },
  });
};
const uploadRef = ref(null);
/** 导入按钮操作 */
function handleImport() {
  upload.title = "用户导入";
  upload.open = true;
}
/** 下载模板操作 */
function importTemplate() {
  proxy.download(
    "system/user/importTemplate",
    {},
    `user_template_${new Date().getTime()}.xlsx`
  );
}
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value.handleRemove(file);
  ElMessageBox.alert(
    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
      response.msg +
      "</div>",
    "导入结果",
    { dangerouslyUseHTMLString: true }
  );
  getList();
};
/** 提交订单记录 */
const submitOrderForm = async () => {
  await queryFormRef.value.validate();
  form.value.payTime = dayjs(form.value.payTime).format("YYYY-MM-DD HH:mm:ss");
  form.value.enterpriseName = enterpriseList.value.find(
    (item) => form.value.enterpriseId == item.id
  )?.name;
  if (form.value.id) {
    await updateDealLog(form.value);
    showEditDialog.value = false;
    ElMessage.success("修改成功");
    getList();
  } else {
    await addDealLog(form.value);
    showEditDialog.value = false;
    ElMessage.success("新增成功");
    getList();
  }
};
const handleDelete = async (id) => {
  ElMessageBox.confirm(`是否确认删除编号为${id}的数据项？`)
    .then(async () => {
      await companyDelete(id);
      getList();
      ElMessage.success("删除成功");
    })
    .catch(() => {});
};

getList();
</script>
