<template>
  <div>
    <!-- <TitleCommon
      v-model="cardaddDrawer"
      :type="props.type"
      :pagesize="currentPageSize"
      :pagenumber="currentPage"
      :drawer="cardaddDrawer"
      @submit-drawer="addData"
      @add-form="clickAddData"
      @handle-close="closeDrawer"
      @clear-data="clearData"
    >
    </TitleCommon> -->
    <el-image-viewer
      v-if="showViewer"
      :url-list="urlList"
      @close="
        () => {
          showViewer = false;
        }
      "
      :z-index="99"
    />

    <div class="body">
      <el-button type="primary" :icon="Plus" @click="addForm" style="margin-bottom: 16px">
        添加模板</el-button
      >
      <el-table style="width: 100%" :data="tableData" highlight-current-row>
        <el-table-column label="模板名称" prop="name" min-width="14%" />
        <!-- <el-table-column :label="props.type + `代码`" prop="code" /> -->
        <el-table-column label="模板编码" prop="code" min-width="14%" />
        <el-table-column label="看板组件" min-width="14%" />
        <el-table-column prop="isDisabled" label="状态" min-width="14%">
          <template #default="scope">
            <el-tag v-if="scope.row.isDisabled === 0" type="success">启用</el-tag>
            <el-tag v-else type="danger">禁用</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="创建时间" prop="createdAt" min-width="14%" />
        <el-table-column label="备注" prop="remark" min-width="16%" />
        <el-table-column label="操作" min-width="14%">
          <!-- <template #default="scoped">
            <el-popconfirm title="确认要删除吗？" @confirm="deleteTableData(scoped.row)">
              <template #reference>
                <img
                  :src="del"
                  alt="delete"
                  class="actionIcon"
                  style="height: 30px; width: 30px; padding: 5px"
                />
              </template>
            </el-popconfirm>
            <img
              :src="edit"
              alt="edit"
              class="actionIcon"
              @click="showEditDrawer(scoped.row)"
              style="height: 30px; width: 30px; padding: 5px"
            />
          </template> -->
          <template #default="scope">
            <el-button link type="primary" size="small" @click="showPreview(scope.row)"
              ><el-tooltip class="box-item" effect="dark" content="预览" placement="top">
                <el-icon :size="16">
                  <View />
                </el-icon>
              </el-tooltip>
            </el-button>
            <el-button link type="primary" size="small" @click="showEditDrawer(scope.row)"
              ><el-tooltip class="box-item" effect="dark" content="编辑" placement="top">
                <el-icon :size="16">
                  <EditPen />
                </el-icon>
              </el-tooltip>
            </el-button>

            <el-button link type="primary" size="small" @click="showDeleteDialog(scope.row)"
              ><el-tooltip class="box-item" effect="dark" content="删除" placement="top">
                <el-icon :size="16">
                  <Delete />
                </el-icon>
              </el-tooltip>
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div style="margin-top: 15px">
        <el-pagination
          v-model:currentPage="currentPage"
          v-model:currentPageSize="currentPageSize"
          :page-sizes="[10, 20, 50, 100, 200]"
          layout="->,total,sizes,prev,pager,next,jumper"
          :total="total"
          @size-change="handleSizeChangeFun"
          @current-change="handlePageChangeFun"
        />
      </div>
    </div>

    <DrawerCommonVue
      ref="childRef"
      :type="props.type"
      :drawer-type="drawerType"
      :add-item="addData"
      :edit-item="submitDrawer"
    />
    <el-dialog v-model="dialogVisible" title="删除该条模板" width="30%" align-center>
      <p>删除后，其他功能若关联该结构，也将同步更新。</p>
      <p>是否确认删除？</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="deleteTableData(currentRow)">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, ref } from 'vue';
  import { ElImageViewer } from 'element-plus';
  import { Plus, EditPen, View, Delete } from '@element-plus/icons-vue';
  import DrawerCommonVue, { FormModelCommon } from './DrawerCommon.vue';
  import { Records, SceneModule } from '@/api/template/template';
  // import { LabelType } from './constant';

  // const currentFormType = ref('场景');

  const props = defineProps<{
    type: string;

    addData: (d: SceneModule) => Promise<unknown>;
    // searchDataByName: (d: DataCommon) => Promise<unknown>;
    deleteTableData: (d: TableModel) => Promise<unknown>;
    submitDrawer: (d: SceneModule) => Promise<unknown>;
    getData: (d: Page) => Promise<unknown>;
  }>();

  const addForm = () => {
    drawerType.value = 'add';
    openDrawer(true);
    setDrawerForm({
      id: null,
      code: '',
      name: '',
      component: '',
      remark: '',
      thumbnail: null,
      isDisabled: 0,
    });
  };

  export type CreateType = '添加模板' | '编辑模板' | '添加标签' | '编辑标签';
  export interface TableModel {
    id: number;
    name: string;
    code: string;
    isDisabled: number;
    remark: string;
    createAt: string;
    previewImage: string;
  }

  export interface ModelCommon {
    drawerFormData: FormModelCommon | null;
  }

  export interface Page {
    pageNumber: number;
    pageSize: number;
  }

  // const currentType = ref<CreateType>('编辑模板');
  // const currentdrawerFormData = ref<FormModelCommon>({} as FormModelCommon);
  // const cardeditDrawer = ref(false);
  // const cardaddDrawer = ref(false);
  const currentPage = ref(1);
  const currentPageSize = ref(10);
  const total = ref(100);
  const tableData = ref<Records[]>([]);

  const drawerType = ref('add'); //抽屉的功能是新建还是编辑

  const childRef = ref<typeof DrawerCommonVue | null>(null);

  const setDrawerForm = (detailsData: FormModelCommon) => {
    if (childRef.value) {
      // console.log('调用了子组件函数');
      childRef.value.setForm(detailsData);
    }
  };

  const openDrawer = (index: boolean) => {
    if (childRef.value) {
      // console.log('调用了子组件函数');
      childRef.value.drawerSwitch(index);
    }
  };

  const fillFileList = (name: string, url: string) => {
    if (childRef.value) {
      // console.log('调用了子组件函数');
      childRef.value.setFileList(name, url);
    }
  };

  const dialogVisible = ref(false);
  const currentRow = ref<TableModel>({} as TableModel);

  const showDeleteDialog = (row: TableModel) => {
    dialogVisible.value = true;
    currentRow.value = row;
  };

  // 删除数据-finish
  function deleteTableData(row: TableModel) {
    // emit('deleteTableData', row);
    props.deleteTableData(row).then(() => {
      dialogVisible.value = false;
      getData({ pageNumber: currentPage.value, pageSize: currentPageSize.value });
    });
  }

  const showViewer = ref(false);

  const urlList = ref<string[]>();

  const showPreview = (row: TableModel) => {
    urlList.value = [];
    // console.log('preViewImg=', row.previewImage);
    urlList.value.push(row.previewImage);
    showViewer.value = true;
  };

  // 编辑数据弹框-finish
  function showEditDrawer(row: TableModel) {
    drawerType.value = 'edit';
    openDrawer(true);

    setDrawerForm({
      id: row.id,
      code: row.code,
      name: row.name,
      component: '',
      remark: row.remark,
      thumbnail: row.previewImage,
      isDisabled: row.isDisabled,
    });
    fillFileList(row.name, row.previewImage);
  }

  // 弹框关闭事件-finish
  // const handleClose = (done: () => void) => {
  //   done();
  //   closeDrawer();
  // };

  // 编辑提交数据
  function submitDrawer(data: SceneModule) {
    // console.log('编辑提交数据：', data);
    props.submitDrawer(data).then(() => {
      // console.log('submitDrawer', res);
      openDrawer(false);
      getData({ pageNumber: currentPage.value, pageSize: currentPageSize.value });
    });
  }

  // 查询数据列表-finish
  function getData(data: Page) {
    props.getData(data).then((res) => {
      // console.log('getData', res);
      tableData.value = res.records;
      total.value = res.totalRow;
    });
  }

  // 根据名称找到数据-finish
  // function searchDataByName(data: DataCommon) {
  //   props.searchDataByName(data).then((res) => {
  //     console.log('searchDataByName', res);
  //     tableData.value = res.records;
  //   });
  // }

  // 单机添加按钮，控制弹框显示-finish
  // function clickAddData() {
  //   cardaddDrawer.value = true;
  // }

  // 添加数据-finish
  function addData(data: SceneModule) {
    props.addData(data).then(() => {
      // console.log('addData', res);
      openDrawer(false);
      //如果是创建了新的，则列表回到第一页；如果只是编辑则列表位置不变
      currentPage.value = 1;
      currentPageSize.value = 10;
      getData({ pageNumber: currentPage.value, pageSize: currentPageSize.value });
    });
  }

  // function closeDrawer() {
  //   cardaddDrawer.value = false;
  //   cardeditDrawer.value = false;
  //   // getData({ pageNumber: currentPage.value, pageSize: currentPageSize.value });更新数据另外干，不用每次关闭抽屉就拉后端
  // }

  // 清空输入框数据-finish
  // function clearData() {
  //   // getSceneLabelList(currentPage.value, currentPageSize.value);
  //   getData({ pageNumber: currentPage.value, pageSize: currentPageSize.value });
  // }

  // 页数-finish
  function handleSizeChangeFun(val: number) {
    currentPageSize.value = val;
    getData({ pageNumber: currentPage.value, pageSize: currentPageSize.value });
  }

  // 翻页-finish
  function handlePageChangeFun(val: number) {
    currentPage.value = val;
    console.log('currentPage:' + currentPage.value);
    getData({ pageNumber: currentPage.value, pageSize: currentPageSize.value });
  }

  onMounted(() => {
    // getData(props.currentPage, props.currentPageSize);
    getData({ pageNumber: currentPage.value, pageSize: currentPageSize.value });
  });
</script>

<style scoped>
  .body {
    width: 100%;
    position: relative;
    /* display: flex;
    flex-direction: column; */
    height: calc(100vh - 140px);
    background-color: #fff;
    padding: 16px;
    border-radius: 4px;
  }

  .actionIcon {
    display: inline-block;
    cursor: pointer;
  }
</style>
