<script setup>
import { orderStatusDict, orderTypeDict } from "@/constant/dict";
import { reactive, ref, toRefs } from "vue";
import InfiniteSelect from "@/components/InfiniteSelect";
import {
  addBrokerDealLog,
  brokerDealLogDetail,
  brokerDealLogList,
  deleteBrokerDealLog,
  updateBrokerDealLog,
} from "@/api/order/broker-order";
import dayjs from "dayjs";
import { agentList } from "@/api/dataList/agent";
import { ElMessage, ElMessageBox } from "element-plus";
import DictTag from "@/components/DictTag/index.vue";
import RightToolbar from "@/components/RightToolbar/index.vue";

const showSearch = ref(true);
const loading = ref(false);
const dataList = ref([]);
const total = ref(0);
const dialogVisible = ref(false);
const dialogTitle = ref("");
const invoiceDialogVisible = ref(false);
const invoiceDialogTitle = ref("");

const formRef = ref(null);
const invoiceFormRef = ref(null);
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    // orderNumber: undefined,
    // enterpriseName: undefined,
    // orderType: undefined,
    // status: undefined,
    // payTime: undefined,
  },
  form: {},
  rules: {
    orderNumber: [{ required: true, message: "请输入订单号", trigger: "blur" }],
    enterpriseName: [
      { required: true, message: "请输入公司名称", trigger: "blur" },
    ],
    orderType: [
      { required: true, message: "请选择订单类型", trigger: "change" },
    ],
    status: [{ required: true, message: "请选择订单状态", trigger: "change" }],
    payTime: [{ required: true, message: "请选择支付时间", trigger: "change" }],
  },
  invoiceForm: {},
});
const { queryParams, form, rules, invoiceForm } = toRefs(data);

const getList = async () => {
  loading.value = true;
  const resp = await brokerDealLogList(queryParams.value);
  dataList.value = resp.rows;
  total.value = resp.total;
  loading.value = false;
};

const handleAdd = () => {
  reset();
  dialogTitle.value = "新增";
  dialogVisible.value = true;
};
const handleEdit = (id) => {
  reset();
  brokerDealLogDetail(id).then((resp) => {
    form.value = resp.data;
  });
  dialogTitle.value = "修改";
  dialogVisible.value = true;
};

const handleDelete = (id) => {
  ElMessageBox.confirm("确认删除该条记录吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deleteBrokerDealLog(id).then(() => {
      ElMessage.success("删除成功");
      getList();
    });
  });
};

/**
 * 提交按钮操作
 */
const submitForm = () => {
  formRef.value.validate().then((valid) => {
    if (valid) {
      if (form.value.id) {
        updateBrokerDealLog(form.value).then(() => {
          dialogVisible.value = false;
          ElMessage.success("修改成功");
          getList();
        });
      } else {
        addBrokerDealLog(form.value).then(() => {
          dialogVisible.value = false;
          ElMessage.success("新增成功");
          getList();
        });
      }
    }
  });
};

/**
 * 取消按钮操作
 */
const cancel = () => {
  reset();
  dialogVisible.value = false;
};
const reset = () => {
  form.value = {};
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

const handleConfirmSelect = (val) => {
  form.value.brokerName = val.name;
};

/**
 * 处理订单
 * @param id
 */
const handleDealOrder = (id) => {
  brokerDealLogDetail(id).then((resp) => {
    invoiceForm.value = resp.data;
    invoiceDialogTitle.value = "开票";
    invoiceDialogVisible.value = true;
  });
};

/**
 * 开票
 */
const confirmInvoice = () => {
  ElMessageBox.confirm("确认处理吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    updateBrokerDealLog({
      id: invoiceForm.value.id,
      status: "2",
    }).then(() => {
      invoiceDialogVisible.value = false;
      ElMessage.success("开票成功");
      getList();
    });
  });
};

/**
 * 加载经纪人下拉框数据
 * @param query
 * @return {Promise<AxiosResponse<any>>}
 */
const loadBrokerOptions = (query) => agentList(query).then((resp) => resp.rows);
getList();
</script>

<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          icon="plus"
          plain
          size="default"
          type="primary"
          @click="handleAdd"
          >新增
        </el-button>
      </el-col>
      <right-toolbar v-model:show-search="showSearch" @query-table="getList" />
    </el-row>
    <el-table v-loading="loading" :data="dataList">
      <el-table-column align="center" label="订单号" prop="orderNumber" />
      <el-table-column align="center" label="经纪人名称" prop="brokerName" />
      <el-table-column align="center" label="订单类型">
        <template #default="{ row }">
          {{
            orderTypeDict.find((item) => item.value === row.orderType)?.label
          }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="金额" prop="amount" />
      <el-table-column align="center" label="数量" prop="total" />
      <el-table-column align="center" label="充值时间" prop="payTime">
        <template #default="{ row }">
          {{ dayjs(row.payTime).format("YYYY-MM-DD HH:mm:ss") }}
        </template>
      </el-table-column>
      <!--订单状态-->
      <el-table-column align="center" label="订单状态">
        <template #default="{ row }">
          <dict-tag :options="orderStatusDict" :value="row.status" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template #default="{ row }">
          <el-button
            icon="edit"
            size="small"
            type="text"
            @click="handleEdit(row.id)"
            >修改
          </el-button>
          <!--处理按钮-->
          <el-button
            :disabled="row.status === '2' || row.status === '0'"
            icon="check"
            size="small"
            type="text"
            @click="handleDealOrder(row.id)"
            >处理
          </el-button>
          <el-button
            icon="delete"
            size="small"
            type="text"
            @click="handleDelete(row.id)"
            >删除
          </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"
    />
    <!--   订单-->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="38%">
      <el-form ref="formRef" :labelWidth="100" :model="form" :rules="rules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="经纪人名称" prop="brokerId">
              <infinite-select
                v-model="form.brokerId"
                :default-label="form.brokerName"
                :prop="{ label: 'name', value: 'brokerId' }"
                :query="{
                  page: 'pageNum',
                  size: 'pageSize',
                  searchKey: 'name',
                }"
                :remote-method="loadBrokerOptions"
                prefix-icon="user"
                @confirm="handleConfirmSelect"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单类型" prop="orderType">
              <el-select v-model="form.orderType">
                <el-option
                  v-for="item in orderTypeDict"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="订单号" prop="orderNumber">
              <el-input
                v-model="form.orderNumber"
                placeholder="请输入订单号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="金额" prop="amount">
              <el-input-number v-model="form.amount"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="充值时间" prop="payTime">
              <el-date-picker
                v-model="form.payTime"
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="选择充值时间"
                type="datetime"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数量" prop="total">
              <el-input-number v-model="form.total"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!--处理发票-->
    <el-dialog
      v-model="invoiceDialogVisible"
      :title="invoiceDialogTitle"
      width="38%"
    >
      <el-form ref="invoiceFormRef" :labelWidth="100" :model="invoiceForm">
        <el-form-item label="公司名称" prop="companyName">
          <el-input v-model="invoiceForm.companyName"></el-input>
        </el-form-item>
        <el-form-item label="公司税号" prop="taxNumber">
          <el-input v-model="invoiceForm.taxNumber"></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="invoiceForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="invoiceForm.phone" maxlength="11"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="invoiceForm.address"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="invoiceDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmInvoice">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

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