<script setup>
import { ref, reactive, onMounted, toRefs } from "vue";
import { Plus, Edit, Delete, ArrowDown } from "@element-plus/icons-vue";

import { getProductList, updateProduct, deleteProduct } from "@/api/product";
import { getCateList } from "@/api/category";

import { useRouter, useRoute } from "vue-router";
const route = useRoute();
const router = useRouter();

const CateOptions = ref([])

const props = {
  emitPath: false,
}

const state = reactive({
  page: 1,
  pageSize: 10,
  search: {
    cat_id: null,
    keyword: '',
  }
});

const { page, pageSize } = toRefs(state);
const total = ref(0);
const loading = ref(false);

const showFormDraw = ref(false);

const tableData = ref([]);

onMounted(async () => {
  let res = await getCateList();
  if (res.code === 200) {
    CateOptions.value = res.data.map((item) => {
      return {
        value: item.id,
        label: item.name,
        children: item.children.map((item2) => {
          return {
            value: item2.id,
            label: item2.name,
          };
        }),
      };
    });
  }

  getTableData();
});

const handleSearch = () => {
  getTableData();
};

const getTableData = async () => {
  loading.value = true;
  let res = await getProductList(state);
  if (res.code === 200) {
    tableData.value = res.data.list;
    total.value = res.data.total;
  }
  loading.value = false;
};


const handleAdd = () => {
  editid.value = 0;
  // showFormDraw.value = true;
  router.push({
    path: '/product/list/form',
  });
};

const handleEdit = (id) => {
  editid.value = id;
  // showFormDraw.value = true;
  router.push({
    path: '/product/list/form',
    query: {
      id: id
    }
  });
};

const handleDelete = (id) => {
  ElMessageBox.confirm('確認刪除此紀錄?')
    .then(async () => {
      let res = await deleteProduct(id);
      if (res.code === 200) {
        ElMessage({
          message: '刪除成功.',
          type: 'success',
        });
        getTableData();

      } else {
        ElMessage({
          message: '刪除失敗.',
          type: 'error',
        });
      }
    })
    .catch(() => {
    })
};

// Pagination
const handleSizeChange = (val) => {
  state.pageSize = val;
  getTableData();
};

const handleCurrentChange = (val) => {
  state.page = val;
  getTableData();
};

const handlePrevClick = (val) => {
  state.page = val;
  getTableData();
};

const handleNextClick = (val) => {
  state.page = val;
  getTableData();
};


// 編輯排序
const editOrderId = ref(0);

const handleEditItem = (id) => {
  editOrderId.value = id;
}

const handleUpdateItem = async (row) => {

  let res = await updateProduct(row);
  if (res.code === 200) {
    ElMessage({
      message: '修改成功.',
      type: 'success',
    });
    getTableData();
  } else {
    ElMessage({
      message: '修改失敗.',
      type: 'error',
    });
  }
  editOrderId.value = 0;
}

const handleCloseEditItem = () => {
  editOrderId.value = 0;
}

// Drawer

const editid = ref(0);

const handleCloseFormDraw = (val) => {

  showFormDraw.value = false;
  if (val) {
    getTableData();
  }
};
</script>

<template>
  <div class="main">
    <!-- Breadcrumb: Start -->
    <div class="breadcrumb-section">
      <div>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item> 產品管理 </el-breadcrumb-item>
          <el-breadcrumb-item> 產品列表 </el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div>
        <el-button type="primary" :icon="Plus" @click="handleAdd">新增產品</el-button>
      </div>
    </div>
    <!-- Breadcrumb: End -->
    <el-card>
      <div class="search-section">
        <el-row :gutter="15">
          <el-col :sm="20" :lg="21">
            <el-row :gutter="15">
              <el-col :sm="8">
              </el-col>
              <el-col :sm="8">
                <el-cascader v-model="state.search.cat_id" 
                :options="CateOptions" 
                :props="props"
                clearable/>
              </el-col>
              <el-col :sm="8">
                <el-input v-model="state.search.keyword" placeholder="請輸入產品名稱" style="width: 100%;" />
              </el-col>
            </el-row>
          </el-col>
          <el-col :sm="4" :lg="3">
            <el-button type="primary" style="width: 100%;height: 100%;" @click="handleSearch">搜尋</el-button>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <el-card :body-style="{ padding: '0px' }">
      <div v-loading="loading">
        <el-table :data="tableData" style="width: 100%">
          <el-table-column label="#" prop="id" width="50" />
          <el-table-column label="產品圖片">
            <template #default="scope">
              <el-image style="width: 150px; height: 80px" :src="scope.row.imageurl" fit="cover" :crossorigin="null" />
            </template>
          </el-table-column>
          <el-table-column label="產品類別" prop="cat_name" />
          <el-table-column label="產品名稱" prop="name" />
          <el-table-column label="建立時間" prop="create_time" />
          <el-table-column prop="sort" label="排序" width="80">
            <template #default="scope">
              <div @dblclick="handleEditItem(scope.row.id)" v-if="scope.row.id !== editOrderId">
                {{ scope.row.sort_order }}
              </div>
              <el-input v-model="scope.row.sort_order" :style="{ width: '50px' }"
                @keyup.enter="handleUpdateItem(scope.row)" @blur="handleCloseEditItem()" :autoFocus="true"
                v-focus="scope.row.id === editOrderId" v-else />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="105" fixed="right">
            <template #default="scope">
              <el-dropdown>
                <el-button type="danger">
                  操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :icon="Edit" @click="handleEdit(scope.row.id)">編輯</el-dropdown-item>
                    <el-dropdown-item v-if="scope.row.is_main !== 1" :icon="Delete"
                      @click="handleDelete(scope.row.id)">刪除</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-block">
          <el-pagination v-model:current-page="page" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
            layout="->,total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" @prev-click="handlePrevClick" @next-click="handleNextClick" />
        </div>
      </div>
    </el-card>
  </div>
  <!-- <div>
    <el-drawer ref="drawerRef" v-model="showFormDraw" :destroy-on-close="true" title="新增管理員" direction="rtl" size="70%">
      <asc-form :editid="editid" @close="handleCloseFormDraw" />
    </el-drawer>
  </div> -->
</template>

<style scoped>
.el-cascader{
  width: 100%;
}
</style>