<template>
  <div class="e-dialog">
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="70%" align-center :draggable="draggable">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>消费信息</span>
          </div>
        </template>
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
          <div v-show="showSearch" class="search">
            <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="auto" class="-mb-25px -mt-5px">
              <el-form-item label="消费时段" prop="consumeRange">
                <el-select
                  v-model="queryParams.consumeRange"
                  placeholder="请选择"
                  style="width: 150"
                  clearable
                  filterable
                  @change="consumeDateChange"
                  @clear="cleaConsumeRange"
                >
                  <el-option v-for="dict in query_date_range" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="消费设备" prop="termNo" class="form-select">
                <el-select v-model="queryParams.termNo" placeholder="请选择" style="width: 250px" clearable filterable @change="handleQuery">
                  <template #header>
                    <div class="consume-select-header">
                      <el-row>
                        <el-col :span="12"><span>设备名称</span></el-col>
                        <el-col :span="12" style="text-align: right"><span>设备机号</span></el-col>
                      </el-row>
                    </div>
                  </template>
                  <el-option v-for="item in termOptions" :key="item.termNo" :label="item.termName" :value="item.termNo">
                    <span style="float: left">{{ item.termName }}</span>
                    <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px">
                      {{ item.termNo }}
                    </span>
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="消费餐类" prop="mealType" class="form-select">
                <el-select v-model="queryParams.mealType" placeholder="请选择" style="width: 150px" clearable filterable @change="handleQuery">
                  <el-option v-for="item in mealOptions" :key="item.typeId" :label="item.mealName" :value="item.typeId"></el-option>
                </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>
          </div>
        </transition>
        <el-table
          ref="consumeDetailTableRef"
          v-loading="loading"
          :data="xfConsumeDetailList"
          stripe
          height="300"
          highlight-current-row
          @current-change="handleCurrentChange"
        >
          <el-table-column label="序列号" type="index" width="100" />
          <el-table-column label="消费时间" align="center" prop="consumeDate" width="250">
            <template #default="scope">
              <span>{{ parseTime(scope.row.consumeDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="消费金额" align="center" prop="consumeMoney" />
          <el-table-column label="设备名称" align="center" prop="termName" width="300" />
          <el-table-column label="设备编号" align="center" prop="termNo" />
          <el-table-column label="钱包类型" align="center" prop="bagType">
            <template #default="scope">
              <dict-tag :options="CARDBAGTYPE" :value="scope.row.bagType" />
            </template>
          </el-table-column>
          <el-table-column label="餐类名称" align="center" prop="mealName" />
          <el-table-column label="消费类型" align="center" prop="statusFlag">
            <template #default="scope">
              <dict-tag :options="consume_record_type" :value="scope.row.statusFlag" />
            </template>
          </el-table-column>
        </el-table>
        <!-- 翻页组件 -->
        <pagination
          v-show="total > 0"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          style="margin-top: 5px"
          :total="total"
          @pagination="getList"
        />
      </el-card>
      <el-card>
        <template #header>
          <div class="card-header">
            <span>补款信息</span>
          </div>
        </template>
        <el-form ref="formRef" :model="formData" :rules="formRules" :inline="true" label-width="6rem" class="-mb-25px -mt-6px" @submit="getList">
          <el-form-item label="消费时间" prop="consumeDate">
            <el-input v-model="formData.consumeDate" disabled></el-input>
          </el-form-item>

          <el-form-item label="消费设备" prop="termName">
            <el-input v-model="formData.termName" disabled></el-input>
          </el-form-item>
          <el-form-item label="消费金额" prop="consumeMoney">
            <el-input v-model="formData.consumeMoney" disabled style="width: 100px"></el-input>
          </el-form-item>
          <el-form-item label="消费钱包" prop="bagName">
            <el-input v-model="formData.bagName" disabled></el-input>
          </el-form-item>
          <el-form-item label="补款时间" prop="fillDate">
            <el-date-picker v-model="formData.fillDate" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请设置补款时间" />
          </el-form-item>
          <el-form-item label="补款金额" prop="operatorMoney" label-width="7rem">
            <template #label>
              补款金额:
              <el-tooltip content="消费金额为负数时,补款金额也要设置为负数" placement="left-start">
                <el-icon>
                  <question-filled />
                </el-icon>
              </el-tooltip>
            </template>
            <el-input v-model="formData.operatorMoney"></el-input>
          </el-form-item>
        </el-form>
      </el-card>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="formLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="dialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="RecompenseForm" lang="ts">
import * as api from '@/api/consumption/XfConsumeDetail';
import { dayjs, ElTable } from 'element-plus';
import { XfConsumeDetailForm, XfConsumeDetailVO } from '@/api/consumption/XfConsumeDetail/types';
import Decimal from 'decimal.js';
import useUserStore from '@/store/modules/user';
import { QuestionFilled } from '@element-plus/icons-vue';
import { XfTermVO } from '@/api/consumption/xfTerm/types';
import { PtMealTypeVO } from '@/api/basics/basicParameter/ptMealtype/types';
import { getAllPtMealType } from '@/api/basics/basicParameter/ptMealtype';
import { listAllXfTerm } from '@/api/consumption/xfTerm';

defineOptions({ name: 'RecompenseForm' });

/** 接收父组件传入属性 */
//const props = defineProps({resetName})

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
/** 当前页面引用的数据字典 */
const { CARDBAGTYPE, consume_record_type, query_date_range } = toRefs<any>(proxy?.useDict('CARDBAGTYPE', 'consume_record_type', 'query_date_range'));
// 对话框
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
// 窗体是否可以拖动
const draggable = ref(true);
// 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formLoading = ref(false);
// 表单的类型：create - 新增；update - 修改
const formType = ref('');
// 操作类型
const command = ref('');
// 表单引用
const formRef = ref<ElFormInstance>();
// 表单数据
const formData = ref<XfConsumeDetailForm>({
  userId: '',
  consumeId: '',
  consumeDate: undefined,
  consumeMoney: undefined,
  cardNo: undefined,
  bagType: '',
  mealType: undefined,
  mealName: '',
  fillDate: '',
  operatorMoney: undefined,
  termNo: undefined,
  termName: '',
  operatorId: '',
  operatorName: ''
});
// 表单校验规则
// fillDate: [{ required: true, message: '补款时间不能为空', trigger: 'blur' }],
const formRules = reactive({
  fillDate: [{ required: true, message: '补款时间不能为空', trigger: 'blur' }],
  operatorMoney: [
    { required: true, message: '补款金额不能为空', trigger: 'blur' },
    { pattern: /^\d+(\.\d{1,2})?$/, message: '补款金额只能为两位小数的数字', trigger: 'blur' }
  ]
});
const userIds = ref<string | number | Array<string | number>>();
const realNames = ref();
// 是否加载遮罩层
const loading = ref(false);
// 是否显示查询项
const showSearch = ref(true);
// 消费明细列表
const xfConsumeDetailList = ref<XfConsumeDetailVO[]>([]);
// 总记录数
const total = ref(0);
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
// 查询窗体Ref
const queryFormRef = ref<ElFormInstance>();
// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  consumeRange: undefined,
  userId: undefined,
  termNo: undefined,
  mealType: undefined,
  params: {}
});
// 当前选中的记录
const currentRow = ref();
// 表格Ref
const consumeDetailTableRef = ref<InstanceType<typeof ElTable>>();
// 消费设备清单
const termOptions = ref<XfTermVO[]>([]);
const mealOptions = ref<PtMealTypeVO[]>();
/** 当前组件方法 */
/** 窗体打开事件 */
const open = async (cmd: string, id?: string | number, name?: string) => {
  dialog.visible = true;
  dialog.title = '错扣补款';
  formType.value = 'edit';
  command.value = cmd;
  userIds.value = id;
  realNames.value = name;
  queryParams.userId = id;
  resetQuery();
};
// 查询时间范围选择
let beginTime: string;
const consumeDateChange = (val: string) => {
  switch (val) {
    case '0':
      beginTime = dayjs().subtract(1, 'month').format('YYYY-MM-DD HH:mm:ss');
      break;
    case '1':
      beginTime = dayjs().subtract(3, 'month').format('YYYY-MM-DD HH:mm:ss');
      break;
    case '2':
      beginTime = dayjs().subtract(6, 'month').format('YYYY-MM-DD HH:mm:ss');
      break;
    case '3':
      beginTime = dayjs().subtract(1, 'year').format('YYYY-MM-DD HH:mm:ss');
      break;
    default:
  }
  dateRange.value = [beginTime, dayjs().format('YYYY-MM-DD HH:mm:ss')];
  handleQuery();
};
const cleaConsumeRange = () => {
  dateRange.value = ['', ''];
};
//查询消费明细列表
const getList = async () => {
  resetForm();
  loading.value = true;
  const res = await api.listXfConsumeDetail(proxy?.addDateRange(queryParams, dateRange.value));
  xfConsumeDetailList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};
// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};
// 重置按钮操作
const resetQuery = () => {
  dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
};
// 单选选中
const handleCurrentChange = (val: XfConsumeDetailVO | undefined) => {
  if (val) {
    Object.assign(formData.value, val);
    const bag: DictDataOption = CARDBAGTYPE.value.find((p: DictDataOption) => p.value == formData.value.bagType);
    formData.value.bagName = bag.label;
    formData.value.operatorMoney = val.consumeMoney;
    formData.value.consumeId = val.consumeId;
    formData.value.fillDate = dayjs().format('YYYY-MM-DD HH:mm:ss');
  }
  currentRow.value = val;
};

/** 表单重置 */
const resetForm = () => {
  formData.value = {
    userId: '',
    consumeId: '',
    consumeDate: undefined,
    consumeMoney: undefined,
    cardNo: undefined,
    bagType: '',
    mealType: undefined,
    mealName: '',
    fillDate: undefined,
    operatorMoney: undefined,
    termNo: undefined,
    termName: '',
    operatorId: '',
    operatorName: ''
  };
  formRef.value?.resetFields();
};

/** 传回给父组件的属性与方法 */
// 提供 open 方法，用于打开弹窗
defineExpose({ open });

/** 触发父组件的事件 */
// 定义 success 事件，用于操作成功后的回调
const emit = defineEmits(['success']);
/** 提交按钮 */
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return;
  const valid = await formRef.value?.validate();
  if (!valid) return;
  // 提交请求
  formLoading.value = true;
  try {
    const data = formData.value as unknown as XfConsumeDetailForm;
    if (!data.termName) {
      proxy?.$modal.alertWarning('请选择要补款的消费记录！');
      return;
    }
    const consumeValue = new Decimal(data.consumeMoney);
    const operatorValue = new Decimal(data.operatorMoney);
    if (consumeValue.comparedTo(operatorValue) === -1) {
      proxy?.$modal.alertWarning('补款金额不能大于消费金额！');
      return;
    }
    data.operatorId = useUserStore().userId;
    data.operatorName = useUserStore().realName;
    await api.recompenseConsumeDetail(data).then((res) => {
      proxy?.$modal.msgSuccess(res.msg);
    });
    dialog.visible = false;
    // 发送操作成功的事件
    emit('success');
  } finally {
    formLoading.value = false;
  }
};

/** 初始化 */
onMounted(() => {
  listAllXfTerm().then((res) => {
    termOptions.value = res.data;
  });
  getAllPtMealType().then((res) => {
    mealOptions.value = res.data;
  });
});
</script>
<style scoped>
.e-dialog {
  .slide-fade-enter-active {
    transition: all 0.3s ease;
  }

  .slide-fade-leave-active {
    transition: all 0.3s cubic-bezier(1, 0.5, 0.8, 1);
  }

  .slide-fade-enter,
  .slide-fade-leave-to {
    opacity: 0;
  }
}

.card-header {
  color: #1c84c6;
  font-size: medium;
}

.consume-select-header {
  color: #1c84c6;
  font-size: medium;
}

:deep() .el-dialog {
  border-radius: 10px;
}

:deep() .el-dialog__body {
  padding: 1px 1px !important;
  max-height: 90vh !important;
}

:deep() .el-dialog__header {
  background: #1d78d5;
  border-radius: 6px 6px 5px 5px;
}

:deep() .el-dialog__title {
  color: white;
  margin-top: 1px;
}

:deep() .el-dialog__headerbtn .el-dialog__close {
  color: white !important;
  top: 15px;
  right: 10px;
}

:deep() .el-overlay .el-overlay-dialog .el-dialog .el-dialog__body {
  padding: 1px !important;
}
</style>
