<template>
  <div>
    <div class="search bg-white p-3">
      <el-form :model="searchForm" label-width="100px">
        <el-row>
          <el-col :span="5">
            <el-form-item label="状态">
              <el-select v-model="searchForm.use_able" clearable>
                <el-option label="启用" :value="true" />
                <el-option label="禁用" :value="false" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="套餐名称">
              <el-input v-model="searchForm.name" clearable placeholder="请输入套餐名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="flex justify-end">
        <el-button class="mr-3" @click="searchEvent"> 搜索 </el-button>
      </div>
    </div>
    <en-table-layout :tableData="tableData.records" :loading="loading">
      <template #toolbar>
        <div class="inner-toolbar w-11/12 flex justify-between">
          <div class="toolbar-btns">
            <el-button size="default" v-if="checkPermission(['warehouse:add'])" type="primary" @click="handleAddWarehouse">新增</el-button>
          </div>
          <!-- <div class="toolbar-search">
            <en-table-search @search="searchEvent" placeholder="请输入关键字搜索" />
          </div> -->
        </div>
      </template>

      <template #table-columns>
        <el-table-column prop="name" label="套餐名称" />
        <el-table-column prop="money" label="套餐金额" />
        <el-table-column prop="day" label="天数" />
        <el-table-column prop="user_num" label="可创建用户数" />
        <el-table-column prop="use_able" label="状态">
          <template #default="scope">
            <el-switch v-model="scope.row.use_able" inline-prompt active-text="启用" inactive-text="禁用" @change="switchUseAble($event, scope.row)" />
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="套餐说明" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="default" v-if="checkPermission(['warehouse:update'])" @click="handleEditWarehouse(scope.$index, scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </template>
      <template #pagination>
        <el-pagination
          v-if="tableData.records && tableData.records.length"
          @size-change="handlePageSizeChange"
          @current-change="handlePageCurrentChange"
          :current-page="tableData.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="tableData.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total"
        >
        </el-pagination>
      </template>
    </en-table-layout>

    <el-dialog
      :title="packageForm.id ? '编辑套餐' : '添加套餐'"
      v-model="dialogVisible"
      width="500px"
      @open="handleDialogOpen"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="packageForm" :rules="stockRules" ref="packageFormRef" label-width="120px">
        <el-form-item label="权限:" prop="role_id">
          <el-select v-model="packageForm.role_id" clearable placeholder="请选择权限">
            <el-option v-for="item in roleArray" :key="item.role_id" :label="item.role_name" :value="item.role_id" />
          </el-select>
        </el-form-item>
        <el-form-item label="套餐名称:" prop="name">
          <el-input v-model="packageForm.name" :minlength="2" :maxlength="20" clearable placeholder="请输入套餐名称"></el-input>
        </el-form-item>
        <el-form-item label="套餐金额:" prop="money">
          <el-input v-model="packageForm.money" :minlength="2" :maxlength="20" clearable placeholder="请输入套餐金额"></el-input>
        </el-form-item>
        <el-form-item label="购买天数:" prop="day">
          <el-input v-model="packageForm.day" :minlength="2" :maxlength="20" clearable placeholder="请输入套餐天数"></el-input>
        </el-form-item>
        <el-form-item label="可创建用户数:" prop="user_num">
          <el-input v-model="packageForm.user_num" :minlength="2" :maxlength="20" clearable placeholder="请输入可创建用户数"></el-input>
        </el-form-item>
        <el-form-item label="状态:" prop="use_able">
          <el-switch v-model="packageForm.use_able" inline-prompt active-text="启用" inactive-text="禁用" />
        </el-form-item>
        <el-form-item label="套餐说明:" prop="remark">
          <el-input v-model="packageForm.remark" type="textarea" :autosize="{ minRows: 3, maxRows: 4 }" placeholder="请输入"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitPackageForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
  
  <script lang="ts" setup>
import { ref, onMounted, reactive } from 'vue';
import { useStore } from 'vuex';
import { ElMessageBox, FormInstance, ElMessage } from 'element-plus';
import * as API_BasicSetting from '@/api/basicSetting';
import * as API_Auth from '@/api/auth';
import * as API_Package from '@/api/package';
import Storage from '@/utils/storage';
import router from '@/router';

const store = useStore();
const tableData = ref<any>({});
const loading = ref(false);
const dialogVisible = ref(false);
const packageForm = ref<any>({
  role_id: '',
  name: '',
  money: '',
  day: '',
  use_able: false,
  remark: '',
});
const stockRules = ref<any>({
  role_id: [{ required: true, message: '请选择权限!', trigger: 'change' }],
  name: [{ required: true, message: '请输入套餐名称', trigger: 'blur' }],
  money: [{ required: true, message: '请输入套餐金额', trigger: 'blur' }],
  day: [{ required: true, message: '请输入套餐天数', trigger: 'blur' }],
  use_able: [{ required: true, message: '请选择状态', trigger: 'change' }],
  user_num: [{ required: true, message: '请输入可创建用户数', trigger: 'blur' }],
});
const marketingList = ref<any[]>([]);

const params = ref({
  data: [],
  page_no: 1,
  page_size: 10,
});
const roleArray = ref<any[]>([]);

const packageFormRef = ref();
const checkPermission = (permissions: string[]): boolean => {
  return true;
};
/* 启用禁用 */
const switchUseAble = (event, row) => {
  API_Package.switchPackage(row.id).then((res) => {
    GET_PackageList();
  });
};
/* 打开新增窗口 */
const handleAddWarehouse = () => {
  packageForm.value = {};
  dialogVisible.value = true;
};
/* 打开编辑窗口 */
const handleEditWarehouse = (index: number, row: any) => {
  packageForm.value = { ...row };
  dialogVisible.value = true;
};
/* 搜索 */
const searchForm = reactive({
  use_able: '',
  name: '',
});
const searchEvent = () => {
  Object.assign(params.value, searchForm);
  console.log(params);
  params.value.page_no = 1;
  GET_PackageList();
};
/* 更改条数 */
const handlePageSizeChange = (size: number) => {
  params.value.page_size = size;
  GET_PackageList();
};
/* 更改页数 */
const handlePageCurrentChange = (page: number) => {
  params.value.page_no = page;
  GET_PackageList();
};

const handleDialogOpen = () => {
  setTimeout(() => {
    packageFormRef.value.clearValidate();
  });
};

/* 提交套餐表单 */
const submitPackageForm = () => {
  packageFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const { id } = packageForm.value;
      const params = { ...packageForm.value };
      if (id) {
        API_Package.editPackage(id, params).then(() => {
          dialogVisible.value = false;
          ElMessage.success('修改成功！');
          GET_PackageList();
        });
      } else {
        API_Package.submitPackage(params).then(() => {
          dialogVisible.value = false;
          ElMessage.success('添加成功!');
          GET_PackageList();
        });
      }
    } else {
      ElMessage.error('表单填写有误，请核对！');
      /*    store.dispatch('showMessage', { message: '表单填写有误，请核对！', type: 'error' }); */
      return false;
    }
  });
};
/* 获取套餐列表 */
const GET_PackageList = () => {
  console.log(params);
  loading.value = true;
  API_Package.packageList(params.value)
    .then((response) => {
      loading.value = false;
      tableData.value = response;
    })
    .catch(() => {
      loading.value = false;
    });
};
/* 获取权限列表 */
const GET_RoleList = () => {
  API_Auth.getPackageRoleList({ page_no: 1, page_size: 10000 }).then((res) => {
    roleArray.value = res.records;
  });
};

onMounted(() => {
  GET_PackageList();
  GET_RoleList();
});
</script>