<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="status">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                <el-option v-for="dict in activation_code_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" prop="expireDateRange" class="form-item-compact">
              <el-date-picker
                v-model="queryParams.createTimeRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD"
                style="width: 280px"
                size="default"
              />
            </el-form-item>
            <el-form-item label="过期时间" prop="expiryDateRange" class="form-item-compact">
              <el-date-picker
                v-model="queryParams.expiryDateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD"
                style="width: 280px"
                size="default"
              />
            </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="1.5">
            <el-button type="primary" plain @click="handleAdd" v-hasPermi="['system:codeSetting:add']">生成激活码</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['system:codeSetting:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['system:codeSetting:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:codeSetting:export']">导出</el-button>
          </el-col> -->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="codeSettingList" @selection-change="handleSelectionChange">
        <el-table-column label="序号" type="index" width="80px" align="center" />
        <el-table-column label="激活码" align="center" prop="activationCode" width="360" />
        <el-table-column label="作用天数" align="center" prop="effectDays" />

        <el-table-column label="价格" align="center" prop="price" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="activation_code_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="200">
          <template #default="scope">
            <span>{{ scope.row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="过期时间" align="center" prop="expiryDate" width="200">
          <template #default="scope">
            <span>{{ scope.row.expiryDate }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" @click="handleDelete(scope.row)" v-hasPermi="['system:codeSetting: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>
    <!-- 添加或修改激活码对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="550px" append-to-body>
      <el-form ref="codeSettingFormRef" :model="form" :rules="rules" label-width="85px">
        <el-form-item label="有效天数" prop="indate">
          <el-input v-model="form.indate" type="number" style="width: 85%" oninput="value=value.replace(/[^\d]/g,'')"
            ><template #append> 天 </template>
          </el-input>
        </el-form-item>
        <el-form-item label="作用天数" prop="effectDays">
          <el-input v-model="form.effectDays" type="number" style="width: 85%" oninput="value=value.replace(/[^\d]/g,'')">
            <template #append> 天 </template></el-input
          >
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="form.price" type="number" style="width: 85%"> <template #append> 元 </template></el-input>
        </el-form-item>
        <el-form-item label="生成几个" prop="buildNum">
          <el-input v-model="form.buildNum" type="number" style="width: 85%" oninput="value=value.replace(/[^\d]/g,'')">
            <template #append> 个 </template></el-input
          >
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确定生成</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CodeSetting" lang="ts">
import { listCodeSetting, getCodeSetting, delCodeSetting, addCodeSetting, updateCodeSetting } from '@/api/setting/codeSetting/index';
import { CodeSettingVO, CodeSettingQuery, CodeSettingForm } from '@/api/setting/codeSetting/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { activation_code_status } = toRefs<any>(proxy?.useDict('activation_code_status'));

const codeSettingList = ref<CodeSettingVO[]>([]);
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 queryFormRef = ref<ElFormInstance>();
const codeSettingFormRef = ref<ElFormInstance>();

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

const initFormData: CodeSettingForm = {
  id: undefined,
  activationCode: undefined,
  status: undefined,
  effectDays: undefined,
  price: undefined,
  expiryDate: undefined,
  remark: undefined,
  indate: undefined,
  buildNum: undefined,
  createTimeRange: undefined,
  expiryDateRange: undefined
};
const data = reactive<PageData<CodeSettingForm, CodeSettingQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    activationCode: undefined,
    status: undefined,
    effectDays: undefined,
    price: undefined,
    createTimeRange: undefined,
    expiryDateRange: undefined,
    params: {}
  },
  rules: {
    indate: [{ required: true, message: '有效天数不能为空', trigger: 'blur' }],
    effectDays: [{ required: true, message: '作用天数不能为空', trigger: 'blur' }],
    price: [{ required: true, message: '价格不能为空', trigger: 'blur' }],
    buildNum: [{ required: true, message: '生成个数不能为空', trigger: 'blur' }]
  }
});

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

/** 查询激活码列表 */
const getList = async () => {
  loading.value = true;
  const res = await listCodeSetting(queryParams.value);
  codeSettingList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

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

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

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

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

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '生成激活码';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: CodeSettingVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getCodeSetting(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改激活码';
};

/** 提交按钮 */
const submitForm = () => {
  codeSettingFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        let res;
        if (form.value.id) {
          res = await updateCodeSetting(form.value);
        } else {
          res = await addCodeSetting(form.value);
        }

        // 根据返回的code判断是否成功
        if (res.code === 200) {
          proxy?.$modal.msgSuccess('操作成功');
          dialog.visible = false;
          await getList();
        } else {
          proxy?.$modal.msgError(res.msg || '操作失败');
        }
      } catch (error) {
        proxy?.$modal.msgError('操作失败');
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

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

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

onMounted(() => {
  getList();
});
</script>
<style lang="scss" scoped>
:deep(.no-number-arrow::-webkit-outer-spin-button),
:deep(.no-number-arrow::-webkit-inner-spin-button) {
  -webkit-appearance: none;
  margin: 0;
}

:deep(.no-number-arrow) {
  -moz-appearance: textfield;
}
</style>
