<template>
  <div class="app-container">
    <el-form
        :model="queryParams"
        ref="queryFormRef"
        v-show="showSearch"
        :inline="true"
        @submit.native.prevent
    >
      <el-form-item label="案例标题" prop="title">
        <el-input
            v-model="queryParams.title"
            placeholder="请输入关键字"
            clearable
            size="default"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="所属站点" prop="tenantId">
        <SiteOptions v-model="queryParams.tenantId" :siteList="siteList"/>
      </el-form-item>
      <el-form-item>
        <el-button
            type="primary"
            icon="search"
            size="default"
            @click="handleQuery"
        >搜索
        </el-button
        >
        <el-button icon="refresh" size="default" @click="resetQuery"
        >重置
        </el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="plus"
            size="default"
            @click="handleAdd"
        >新增
        </el-button
        >
      </el-col>
      <right-toolbar
          v-model:showSearch="showSearch"
          @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataList">
      <el-table-column label="数据编码" prop="id" align="center"/>
      <el-table-column label="案例标题" prop="title" align="center"/>
      <el-table-column label="图片" prop="image" align="center" width="120">
        <template #default="{ row }">
          <div>
            <el-image
                style="width: 100px; height: 100px"
                :src="resolveStaticUrl(row.image)"
                fit="cover"
            ></el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="所属站点" align="center">
        <template #default="{ row }">
          {{ siteList.find((el) => el.id === row.tenantId)?.name ?? "无" }}
        </template>
      </el-table-column>
      <el-table-column
          label="描述"
          prop="description"
          show-overflow-tooltip
          align="center"
      />
      <el-table-column label="创建时间" prop="created_at" align="center">
        <template #default="{ row }">
          <span>{{ row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
      >
        <template #default="{ row }">
          <el-button
              size="small"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(row)"
          >编辑
          </el-button
          >
          <el-button
              size="small"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(row)"
          >删除
          </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-dialog :title="title" v-model="showEditDialog" width="40%">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="案例标题:" prop="title">
          <el-input v-model="form.title" placeholder="请输入案例标题"/>
        </el-form-item>
        <el-form-item label="描述:" prop="description">
          <el-input
              v-model="form.description"
              placeholder="请输入描述"
              maxlength="30"
          />
        </el-form-item>
        <el-form-item label="图片:" prop="image">
          <ImageUpload v-model="form.image" :isShowTip="false" :limit="1"/>
        </el-form-item>
        <el-form-item label="所属站点:" prop="tenantId">
          <SiteOptions v-model="form.tenantId" :siteList="siteList"/>
        </el-form-item>
        <el-form-item label="所属服务:" prop="kindId">
          <el-cascader
              v-model="form.kindId"
              clearable
              separator="-"
              placeholder="请选择，支持搜索"
              :options="caseOptions"
              filterable
              :props="{ emitPath: false, value: 'id', label: 'title' }"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="案例描述:" prop="content">
          <!--          <WangEditor-->
          <!--            v-model="form.content"-->
          <!--            destroy-on-close-->
          <!--            minHeight="150px"-->
          <!--          ></WangEditor>-->
          <el-input
              type="textarea"
              v-model="form.content"
              placeholder="请输入案例描述"
              :autosize="{ minRows: 6, maxRows: 8}"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script setup name="serviceCase">
import {ElMessage, ElMessageBox} from "element-plus";
import {reactive, ref, toRefs} from "vue";
import {tenantSelect} from "@/api/subPlatform/tenant";
import {
  serviceCaseList,
  serviceCaseAdd,
  serviceCaseDetail,
  serviceCaseEdit,
  serviceCaseDelete,
  serviceCaseKindSelect,
} from "@/api/website/solution";
import WangEditor from "@/components/WangEditor/index.vue";
import SiteOptions from "@/views/components/SiteOptions";
import {planCategoryList} from "../../../../api/website/solution";
import {resolveStaticUrl} from "@/utils/uri";

const dataList = ref([]);
const loading = ref(true);
const total = ref(0);
const showEditDialog = ref(false);
const siteList = ref([]);
const formRef = ref(null);
const queryFormRef = ref(null);
const caseOptions = ref([]); // 案例分类列表
const showSearch = ref(true);
const title = ref("");
//TODO:isSuper v-if
const data = reactive({
  queryParams: {
    title: undefined,
    tenantId: undefined,
    pageNum: 1,
    pageSize: 10,
  },
  form: {},
  rules: {
    title: [{required: true, message: "案例标题不能为空", trigger: "blur"}],
    description: [{required: true, message: "描述不能为空", trigger: "blur"}],
    image: [
      {
        required: true,
        message: "图片不能为空",
        trigger: ["blur", "change"],
      },
    ],
    tenantId: [
      {
        required: true,
        message: "所属站点不能为空",
        trigger: ["blur", "change"],
      },
    ],
    kindId: [
      {
        required: true,
        message: "所属服务不能为空",
        trigger: ["blur", "change"],
      },
    ],
    content: [
      {
        required: true,
        message: "案例描述不能为空",
        trigger: "blur",
      },
    ],
  },
});
const {queryParams, form, rules} = toRefs(data);
const resetQuery = () => {
  if (queryFormRef.value) {
    queryFormRef.value.resetFields();
  }
  handleQuery();
};
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const getList = async () => {
  loading.value = true;
  const resp = await serviceCaseList(queryParams.value);
  dataList.value = resp.rows;
  total.value = resp.total;
  loading.value = false;
};

const getSiteList = async () => {
  const {rows} = await tenantSelect();
  siteList.value = rows;
};

const getCaseKindList = async () => {
  const resp = await serviceCaseKindSelect();
  // const resp = await planCategoryList();
  // const serviceResp= await ser
  for (const key in resp.data) {
    if (Object.hasOwnProperty.call(resp.data, key)) {
      const item = {...resp.data[key], id: parseInt(key)};
      caseOptions.value.push(item);
    }
  }
};
// 取消按钮
const cancel = () => {
  showEditDialog.value = false;
  //   memberOpen.value = false;
  reset();
};
// 表单重置
const reset = () => {
  form.value = {
    id: undefined,
    tenantId: undefined,
    kindId: undefined,
    title: undefined,
    image: undefined,
    description: undefined,
    content: "",
  };
  if (formRef.value) {
    formRef.value.resetFields();
  }
};
// const getSiteName = (tenantId) => {
//   const item = siteList.value.find((el) => {
//     return el.id === tenantId;
//   });
//   return item ? item.name : "无";
// };
const handleAdd = () => {
  reset();
  showEditDialog.value = true;
  title.value = "新增";
};
const handleUpdate = async (row) => {
  reset();
  const resp = await serviceCaseDetail(row.id);
  form.value = resp.data;
  showEditDialog.value = true;
  title.value = "修改";
};

const submitForm = async () => {
  await formRef.value.validate();
  if (form.value.id != undefined) {
    await serviceCaseEdit(form.value);
    ElMessage.success("修改成功");
    showEditDialog.value = false;
    getList();
  } else {
    await serviceCaseAdd(form.value);
    ElMessage.success("新增成功");
    showEditDialog.value = false;
    getList();
  }
};
/** 删除按钮操作 */
const handleDelete = (row) => {
  ElMessageBox.confirm(`是否确认删除名为${row.title}的数据项？`)
      .then(async () => {
        await serviceCaseDelete(row.id);
        getList();
        ElMessage.success("删除成功");
      })
      .catch(() => {
      });
};

getList();
getSiteList();
getCaseKindList();
</script>
