<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="$t('warehousing_state')">
              <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="$t('package_name')">
              <el-input v-model="searchForm.name" clearable :placeholder="$t('place')+$t('package_name')"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="flex justify-end">
        <el-button class="mr-3" @click="searchEvent">{{$t('search')}}</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">{{$t('add')}}</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="$t('package_name')" />
        <el-table-column prop="money" :label="$t('package_money')" />
        <el-table-column prop="day" :label="$t('package_day')" />
        <el-table-column prop="user_num" :label="$t('package_user_num')" />
        <el-table-column prop="use_able" :label="$t('warehousing_state')">
          <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="$t('package_remark')" />
        <el-table-column :label="$t('operate')" fixed="right" width="300">
          <template #default="scope">
            <el-button size="default" v-if="checkPermission(['warehouse:update'])" @click="handleEditWarehouse(scope.$index, scope.row)">{{$t('edit')}}</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 ? $t('edit') : $t('add')"
      v-model="dialogVisible"
      width="500px"
      @open="handleDialogOpen"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      class="!rounded-lg"
    >
      <el-form :model="packageForm" :rules="stockRules" ref="packageFormRef" label-width="120px">
        <el-form-item :label="$t('package_role')+':'" prop="role_id">
          <el-select v-model="packageForm.role_id" clearable :placeholder="$t('place')+$t('package_role')">
            <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="$t('package_name')+':'" prop="name">
          <el-input v-model="packageForm.name" :minlength="2" :maxlength="20" clearable :placeholder="$t('place')+$t('package_name')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('package_money')+':'" prop="money">
          <el-input v-model="packageForm.money" :minlength="2" :maxlength="20" clearable :placeholder="$t('place')+$t('package_money')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('package_day')+':'" prop="day">
          <el-input v-model="packageForm.day" :minlength="2" :maxlength="20" clearable :placeholder="$t('place')+$t('package_day')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('package_user_num')+':'" prop="user_num">
          <el-input v-model="packageForm.user_num" :minlength="2" :maxlength="20" clearable :placeholder="$t('place')+$t('package_user_num')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('warehousing_state')+':'" prop="use_able">
          <el-switch v-model="packageForm.use_able" inline-prompt active-text="启用" inactive-text="禁用" />
        </el-form-item>
        <el-form-item :label="$t('package_remark')+':'" prop="remark">
          <el-input v-model="packageForm.remark" type="textarea" :autosize="{ minRows: 3, maxRows: 4 }" :placeholder="$t('place')+$t('package_remark')"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">{{$t('cancel')}}</el-button>
          <el-button type="primary" @click="submitPackageForm">{{$t('submit')}}</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';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();

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:t('change')+t('package_role')+'!', trigger: 'change' }],
  name: [{ required: true, message: t('place')+t('package_name')+'!', trigger: 'blur' }],
  money: [{ required: true, message: t('place')+t('package_money')+'!', trigger: 'blur' }],
  day: [{ required: true, message: t('place')+t('package_day')+'!', trigger: 'blur' }],
  use_able: [{ required: true, message:t('change')+t('warehousing_state')+'!', trigger: 'change' }],
  user_num: [{ required: true, message: t('place')+t('package_user_num')+'!', 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(t('edit_success')+'!');
          GET_PackageList();
        });
      } else {
        API_Package.submitPackage(params).then(() => {
          dialogVisible.value = false;
          ElMessage.success(t('add_success')+'!');
          GET_PackageList();
        });
      }
    } else {
      ElMessage.error(t('form_erroe'));
      /*    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>