<template>
  <div>
    <el-card class="good-container">
      <template #header>
        <div class="header flex justify-between">
          <el-button type="primary" :icon="Plus" @click="handleAdd"
            >新增商品</el-button
          >
          <div>
            <el-input
              style="width: 400px"
              class="ml-2 mr-2"
              v-model="query.key"
              clearable
              placeholder="商品名称"
            ></el-input>
            <el-select v-model="query.goodsSellStatus" placeholder="选择状态">
              <el-option label="全部状态" :value="-1"></el-option>
              <el-option label="已上架" :value="0"></el-option>
              <el-option label="已下架" :value="1"></el-option>
            </el-select>
            <el-select
              v-model="query.goodsCategoryId"
              filterable
              class="ml-2"
              placeholder="请选择分类"
            >
              <el-option label="全部商品分类" :value="-1"></el-option>

              <el-option
                v-for="item in categoryList"
                :key="item.categoryId"
                :label="item.categoryName"
                :value="item.categoryId"
              />
            </el-select>

            <!-- <el-select v-model="query.goodsSellStatus" placeholder="选择状态">
            <el-option label="全部审核状态" :value="-1"></el-option>
            <el-option label="带审核" :value="0"></el-option>
            <el-option label="审核通过" :value="1"></el-option>
            <el-option label="审核不通过" :value="2"></el-option>
          </el-select> -->
            <el-button type="primary" class="ml-2" @click="onSearch"
              >搜索</el-button
            >
          </div>
        </div>
      </template>
      <el-table
        :load="state.loading"
        :data="state.tableData"
        tooltip-effect="dark"
        style="width: 100%"
      >
        <!-- <el-table-column prop="mechanismId" label="商品编号"> </el-table-column> -->
        <el-table-column prop="goodsName" label="商品名"> </el-table-column>
        <el-table-column prop="goodsId" label="商品ID"> </el-table-column>
        <el-table-column label="所属店铺">
          <template #default="{ row }">
            <span v-for="item in row.shops" :key="item.id">{{
              item.name
            }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="goodsCategoryName" label="所属分类">
        </el-table-column>

        <el-table-column prop="goodsIntro" label="商品简介"> </el-table-column>
        <el-table-column label="商品图片" width="150px">
          <template #default="scope">
            <el-image
              :src="scope.row.goodsCoverImg"
              :preview-src-list="[scope.row.goodsCoverImg]"
              preview-teleported
              class="rounded"
              mode="cover"
              style="width: 100px; height: 100px"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="stockNum" label="商品库存"> </el-table-column>
        <el-table-column prop="sellingPrice" label="商品售价">
          <template #default="scope">
            {{ scope.row.sellingPrice / 100 }}
          </template>
        </el-table-column>
        <el-table-column label="审核状态">
          <template #default="scope">
            <span :class="statusList[scope.row.verifyStatus].class"
              >{{ statusList[scope.row.verifyStatus].label }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="上架状态">
          <template #default="scope">
            <span style="color: green" v-if="scope.row.goodsSellStatus == 0"
              >销售中</span
            >
            <span style="color: red" v-else>已下架</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="240">
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="handleEdit(scope.row.goodsId)"
              >修改</el-button
            >
            <el-button
              v-if="scope.row.goodsSellStatus == 0"
              type="primary"
              link
              @click="handleStatus(scope.row.goodsId, 1)"
              >下架</el-button
            >
            <el-button
              v-else
              type="primary"
              link
              @click="handleStatus(scope.row.goodsId, 0)"
              >上架</el-button
            >
            <!-- <el-button
              type="primary"
              link
              @click="handleExamine(scope.row.goodsId, 0)"
              >审核</el-button
            > -->
            <el-button
              type="primary"
              link
              @click="
                getEvaluationList(scope.row.goodsId);
                evaluationManageVisible = true;
              "
              >评价管理</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!--总数超过一页，再展示分页器-->
      <el-pagination
        class="mt-4 justify-end"
        background
        layout="prev, pager, next"
        :total="state.total"
        :page-size="state.pageSize"
        :current-page="state.currentPage"
        @current-change="changePage"
      />
    </el-card>
    <DialogExamineGoods
      v-model:show="state.visibleExamine"
      :id="state.id"
      @success="getGoodList"
    ></DialogExamineGoods>

    <el-dialog v-model="evaluationManageVisible" title="评价管理">
      <div
        class="shadow border-solid border border-gray-100 mb-2 bg-white rounded p-4"
        v-for="(item, index) in evaluationList"
        :key="index"
      >
        <div class="flex items-center mb-2">
          <el-image
            :src="item.userAvatar || man"
            alt=""
            class="w-12 h-12 rounded-full shadow bg-white mr-4"
          />
          <div class="flex-1">
            <div>{{ item.userNickname }}</div>
            <el-rate :model-value="item.level" disabled />
          </div>
          <!-- <el-button type="danger" plain @click="removeEvaluation(item)"
            >删除评论</el-button
          > -->
        </div>
        <div class="mb-2">
          <span>评价时间</span>
          <span class="ml-2 text-sm text-gray-800">{{ item.updateTime }}</span>
        </div>
        <div class="text-gray-500 text-sm break-all whitespace-pre-wrap">
          {{ item.appraise }}
        </div>
      </div>
      <el-empty v-if="!evaluationList.length"></el-empty>

      <el-pagination
        class="mt-4 justify-end"
        background
        layout="total, prev, pager, next"
        :total="evaluationTotal"
        :page-size="evaluationFilter.pageSize"
        :current-page="evaluationFilter.page"
        @current-change="
          p => {
            evaluationFilter.page = p;
            getEvaluationList(evaluationFilter.goodsId);
          }
        "
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, reactive, getCurrentInstance, ref } from "vue";
import { request } from "@/utils/http";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Delete } from "@element-plus/icons-vue";
import { useRouter, useRoute } from "vue-router";
import { relative } from "path";
import DialogExamineGoods from "./components/DialogExamineGoods.vue";
import man from "@/assets/icon-man.png";
const app = getCurrentInstance();
const route = useRoute();
const router = useRouter();
const state = reactive({
  id: undefined,
  loading: false,
  tableData: [], // 数据列表
  total: 0, // 总条数
  currentPage: 1, // 当前页
  pageSize: 10, // 分页大小
  visibleExamine: false
});
const categoryList = ref([]);

const statusList = [
  {
    label: "待审核",
    value: 0
  },
  {
    label: "审核通过",
    value: 1,
    class: "text-green-700"
  },

  {
    label: "审核不通过",
    value: 2,
    class: "text-red-700"
  }
];
const query = reactive({
  key: "",
  goodsSellStatus: -1,
  shopId: -1
});
onMounted(() => {
  onSearch();
  initCategory();
});
const onSearch = () => {
  state.currentPage = 1;
  getGoodList();
};
// 获取商品列表
const getGoodList = () => {
  state.loading = true;
  request
    .get("/mallService/mechanism/staff/goods/list", {
      params: {
        page: state.currentPage,
        pageSize: state.pageSize,
        ...query,
        goodsName: query.key
      }
    })
    .then(res => {
      state.tableData = res.data.list;
      state.total = res.data.total;
      state.loading = false;
    });
};
const handleAdd = () => {
  router.push({
    path: "/myShop/goods/add"
  });
};
const handleEdit = id => {
  router.push({ path: "/myShop/goods/add", query: { id } });
};
const changePage = val => {
  state.currentPage = val;
  getGoodList();
};

const initCategory = () => {
  return new Promise(resolve => {
    request
      .get("/mallService/mechanism/category", {
        params: {
          page: 1,
          pageSize: 1000
        }
      })
      .then(res => {
        const list = res.data.list;
        categoryList.value = list;
        resolve();
      });
  });
};
const handleStatus = (id, status) => {
  if (status == 1) {
    ElMessageBox.confirm("确认下架该商品吗", "提示").then(() => {
      request
        .put(`/mallService/mechanism/goods/status/${status}`, {
          ids: id ? [id] : []
        })
        .then(() => {
          ElMessage.success("修改成功");
          getGoodList();
        });
    });
  } else {
    request
      .put(`/mallService/mechanism/goods/status/${status}`, {
        ids: id ? [id] : []
      })
      .then(() => {
        ElMessage.success("修改成功");
        getGoodList();
      });
  }
};

const handleExamine = id => {
  state.id = id;
  state.visibleExamine = true;
};

const evaluationManageVisible = ref(false);
const evaluationList = ref([]);
const evaluationTotal = ref(0);

const evaluationFilter = ref({
  page: 1,
  pageSize: 20,
  goodsId: ""
});
const getEvaluationList = async id => {
  evaluationFilter.value.goodsId = id;
  const { data } = await request.get(
    `/mallService/api/goods/appraise/paginate`,
    {
      params: evaluationFilter.value
    }
  );
  evaluationList.value = data.list;

  evaluationTotal.value = data.total;
};
const removeEvaluation = async item => {
  await ElMessageBox.confirm("是否确认删除该评论?");

  await request.post(`/mallService/mechanism/appraise/delete`, {
    id: item.id
  });
  ElMessage.success("操作成功");
  getEvaluationList(evaluationFilter.value.goodsId);
};
</script>

<style scoped>
.good-container {
  min-height: 100%;
}
.el-card.is-always-shadow {
  min-height: 100% !important;
}
</style>
