<template>
  <div class="koi-flex">
    <KoiCard>
      <!-- 表格头部按钮 -->
      <el-row :gutter="10">
        <el-col :span="1.5" v-auth="['system:role:add']">
          <el-button type="primary" icon="plus" plain @click="handleAdd()">新增</el-button>
          <el-button type="success" icon="microphone" plain @click="Mp3Check()">生成语音文件</el-button>
        </el-col>
        <!--  @click="handleExpend()"  -->
      </el-row>

      <div class="h-20px"></div>
      <!-- 数据表格 -->
      <el-table
        v-if="refreshTreeTable"
        v-loading="loading"
        border
        :indent="30"
        :data="tableList"
        :default-expand-all="isExpandAll"
        row-key="uuid"
        @row-click="rowClick"
        :lazy="true"
        :load="load"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        empty-text="暂时没有数据哟🌻"
      >
        <el-table-column
          label="报纸期刊"
          prop="datetime"
          align="left"
          :show-overflow-tooltip="true"
          width="400px"
        >
          <template #default="scope">
            <el-input @blur="addSort(scope.row)" v-if="scope.row.level==2" :maxlength="2" class="center-input"
                      style="max-width: 50px;margin-right: 10px"
                      v-model="scope.row.weight"></el-input>
            <span class="cursor-pointer">{{ scope.row.datetime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" width="250px" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.status==0" type="danger">已隐藏</el-tag>
            <el-tag v-if="scope.row.status==1" type="success">显示中</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="数量" prop="bm_count" width="350px" align="center">
          <template #default="scope">
            <div v-if="scope.row.level==1">版面数量：{{ scope.row.bm_count }}</div>
            <div v-if="scope.row.level==2">新闻数量：{{ scope.row.new_count }}</div>
            <div v-if="scope.row.level==3">
              <audio v-if="scope.row.mp_url!=null&&scope.row.mp_url!=''" controls :src="'https://jinrigushi.gushitv.com/'+scope.row.mp_url"></audio>
              <span v-if="scope.row.mp_url==null||scope.row.mp_url==''">语音生成中...</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="450px" fixed="right">
          <template #default="{ row }">

            <el-button v-if="row.level==1"
                       type="info"
                       @click="openA(row)"
            >预览
            </el-button>

            <el-button v-if="row.level==1 && row.status==1"
                       type="primary"
                       @click="statusUpdate(row,0)"
            >隐藏
            </el-button>
            <el-button v-if="row.level==1 && row.status==0"
                       type="success"
                       @click="statusUpdate(row,1)"
            >显示
            </el-button>
            <el-button v-if="row.level==1"
                       type="warning"
                       @click="handleAddDate(row)"
            >添加版面
            </el-button>
            <!--            <el-button v-if="row.level==1"-->
            <!--                       type="warning"-->

            <!--                       @click="handleUpdateDate(row)"-->
            <!--            >修改-->
            <!--            </el-button>-->
            <el-button v-if="row.level==1"
                       type="danger"

                       @click="handleDeleteDate(row)"
            >删除
            </el-button>

            <el-button v-if="row.level==2"
                       type="info"
                       plain
                       @click="openUrl('/paper/article/index/'+row.id)"
            >添加新闻
            </el-button>
            <el-button v-if="row.level==2"
                       type="warning"
                       plain
                       @click="handleUpdateBm(row)"
            >修改
            </el-button>
            <el-button v-if="row.level==2"
                       type="danger"
                       plain
                       @click="handleDeleteBm(row)"
            >删除
            </el-button>
            <el-button v-if="row.level==3"
                       type="primary"
                       icon="Edit"
                       circle
                       plain
                       @click="openUrl('/paper/article/update/'+row.id)"
            ></el-button>
            <el-button v-if="row.level==3"
                       type="danger"
                       icon="Delete"
                       circle
                       plain
                       @click="handleDeleteNews(row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="h-20px"></div>
      <!-- {{ searchParams.pageNo }} --- {{ searchParams.pageSize }} -->
      <!-- 分页 -->
      <el-pagination
        background
        v-model:current-page="pageNumber.page"
        v-model:page-size="pageNumber.size"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleListPageSize"
        @current-change="handleListPage"
      />
    </KoiCard>
    <KoiDialog ref="koiDrawerDate" :width="500" :height="100" title="期刊编辑" @koiConfirm="handleConfirmDateDo"
               @koiCancel="handleCancel" :loading="confirmLoading">
      <template #content>
        <el-row>
          <el-col :span="18">
            <el-form :model="Dateform" label-width="auto">
              <el-form-item label="报刊日期">
                <el-date-picker
                  v-model="Dateform.datetime"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="选择报刊日期"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>
              <!--              <el-form-item label="报刊类型">-->
              <!--                <el-select v-model="Dateform.type_id" placeholder="选择报刊类型">-->
              <!--                  <el-option v-for="item in typeList" :label="item.type" :value="item.id"/>-->
              <!--                </el-select>-->
              <!--              </el-form-item>-->
            </el-form>
          </el-col>
        </el-row>
      </template>
    </KoiDialog>
    <KoiDialog ref="koiDrawerBm" :width="500" :height="400" :title="Bmform.id==0?'添加版面':'修改版面'"
               @koiConfirm="handleConfirmBmDo"
               @koiCancel="handleCancel" :loading="confirmLoading">
      <template #content>
        <el-row>
          <el-col :span="18">
            <el-form :model="Bmform" label-width="auto">
              <el-form-item label="版面名称">
                <el-input v-model="Bmform.bm_name" placeholder="输入版面名称"/>
              </el-form-item>
              <el-form-item label="版面排序">
                <el-input type="number" v-model="Bmform.weight" placeholder="输入版面排序"/>
              </el-form-item>
              <el-form-item label="版面PDF">
                <KoiUploadFiles :fileList="Bmform.pdf" acceptType=".pdf" @update:fileList="updateFileList"
                                @fileSuccess="getFileList">
                  <template #tip>PDF最大为 10M</template>
                </KoiUploadFiles>
              </el-form-item>
              <el-form-item label="版面图片" prop="avatar">
                <KoiUploadImage :imageUrl="Bmform.bm_img" @update:imageUrl="getImgList" width="150px" height="150px">
                  <template #content>
                    <el-icon>
                      <Picture/>
                    </el-icon>
                    <span>请上传版面图片</span>
                  </template>
                  <template #tip>图片最大为 3M</template>
                </KoiUploadImage>
              </el-form-item>

            </el-form>
          </el-col>
        </el-row>

      </template>
    </KoiDialog>
  </div>
</template>

<script setup lang="ts" name="menuPage">
import {nextTick, ref, reactive, onMounted} from "vue";
import {koiNoticeSuccess, koiNoticeError, koiMsgError, koiMsgWarning, koiMsgBox, koiMsgInfo} from "@/utils/koi.ts";
import {generateUUID} from "@/utils/index.ts";
import {useRoute, useRouter} from "vue-router";
import {
  bmDel,
  bmList,
  bmListNews,
  bmListNext,
  bmUpdate,
  dateDel,
  dateUpdate,
  getList,
  newsDel,
  bmOneAdd, getMp3
} from "@/api/system/post/index.ts";
import useTabsStore from "@/stores/modules/tabs.ts";

const tabsStore = useTabsStore();
const router = useRouter();
// 表格加载动画Loading
const loading = ref(false);
// 是否显示搜索表单[默认显示]
const showSearch = ref<boolean>(true); // 默认显示搜索条件

// 表格数据
const tableList = ref([]);
// 查询参数
const searchParams = ref({
  menuName: "",
  auth: "",
  menuStatus: ""
});
const typeList = ref();
const getTypelist = async () => {
  try {
    const res: any = await getList([]);
    typeList.value = res.data;
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试!");
  }
}
const Dateform = reactive({
  datetime: "",
  type_id: ""
});
const total = ref(0);
const pageNumber = reactive({page: 1, size: 10});
/** 重置搜索参数 */
const resetSearchParams = () => {
  searchParams.value = {
    menuName: "",
    auth: "",
    menuStatus: ""
  };
};
/*PDF删除*/
const updateFileList = (d) => {
  console.log(d);
  //console.log(index);
  //backArr.value[index].bm_pdf = d.fullurl?d.fullurl:'';
}
const Mp3Check = async (row) => {
  //console.log(row);
  try {
    const res: any = await getMp3('');
    koiNoticeSuccess("语音生成成功！");
    handleTreeList();
  } catch (error) {
    console.log(error);
    koiNoticeError("数据修改失败，请刷新重试🌻");
  }

}
const openA = (item) => {
  console.log(item);
  var url="https://jinrigushi.gushitv.com/#/?date="+item.datetime;
  if(item.status==0){
    url="https://jinrigushi.gushitv.com/#/?date="+item.datetime+"&status=1";
  }
  window.open(url);
}
/*PDF上传*/
const getFileList = (d) => {
  console.log(d);
  Bmform.bm_pdf = d.fullurl;
}
/*IMG上传*/
const getImgList = (d) => {
  console.log(d);
  Bmform.bm_img = d;
}
/*获取PDF文件名称*/
const getFileNameFromUrl = (url) => {
  // 使用最后一个斜杠的位置来分割路径
  const lastSlashIndex = url.lastIndexOf('/');
  if (lastSlashIndex === -1) {
    return 'pdf.pdf'; // 如果没有找到斜杠，则返回空字符串
  }
  // 提取文件名部分
  const fileName = url.substring(lastSlashIndex + 1);
  return fileName;
}
/** 搜索 */
const handleSearch = () => {
  console.log("搜索");
};
const load = async (row, treeNode, resolve) => {
  console.log(row)
  console.log(treeNode)

  try {
    if (row.level == 1) {
      var res: any = await bmListNext({date_id: row.id});
      res.data = res.data.map(item => {
        return {
          ...item,
          uuid: generateUUID(),
          datetime: item.bm_name,
          bm_name: undefined // 或者删除该项
        };
      });
    } else {
      var res: any = await bmListNews({bm_id: row.id});
      res.data = res.data.map(item => {
        return {
          ...item,
          uuid: generateUUID(),
          datetime: item.new_name,
          bm_name: undefined // 或者删除该项
        };
      });
    }
    console.log("菜单数据表格数据->", res.data);

    resolve(res.data)
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试🌻");
  }
}
const Bmform = reactive({
  bm_img: "",
  bm_name: "",
  bm_pdf: "",
  id: 0,
  pdf: [],
  weight: 0,
})
/*版面修改*/
const handleUpdateBm = (row) => {
  console.log(row);
  Bmform.bm_name = row.datetime;
  Bmform.bm_img = row.bm_img;
  Bmform.bm_pdf = row.bm_pdf;
  Bmform.id = row.id;
  Bmform.pdf = [{'url': row.bm_pdf, 'name': getFileNameFromUrl(row.bm_pdf)}];
  koiDrawerBm.value.koiOpen();
}
/*添加版面*/
const handleAddDate = (row) => {
  console.log(row);
  Bmform.bm_name = "";
  Bmform.bm_img = "";
  Bmform.bm_pdf = "";
  Bmform.weight = 0;
  Bmform.id = 0;
  Bmform.pdf = [];
  Bmform.date_id = row.id;
  koiDrawerBm.value.koiOpen();
}
/*版面排序修改*/
const addSort = async (row) => {
  //console.log(row);
  try {
    const res: any = await bmUpdate({id: row.id, weight: row.weight});
    koiNoticeSuccess("修改成功!");
    handleTreeList();
  } catch (error) {
    console.log(error);
    koiNoticeError("数据修改失败，请刷新重试🌻");
  }

}
const statusUpdate = async (row,type) => {
  try {
    const res: any = await dateUpdate({status:type,id: row.id});
    console.log("菜单数据表格数据->", res.data);
    koiNoticeSuccess("修改成功!");
    handleTreeList();
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试🌻");
  }
}
/*版面修改/添加*/
const handleConfirmBmDo = async () => {
  confirmLoading.value = true;
  try {
    if (Bmform.id == 0) {
      const res: any = await bmOneAdd(Bmform);
      console.log("菜单数据表格数据->", res.data);
      koiNoticeSuccess("添加成功!");
    } else {
      const res: any = await bmUpdate(Bmform);
      console.log("菜单数据表格数据->", res.data);
      koiNoticeSuccess("修改成功!");
    }
    confirmLoading.value = false;
    koiDrawerBm.value.koiQuickClose();
    handleTreeList();
  } catch (error) {
    console.log(error);
    koiNoticeError("数据修改失败，请刷新重试🌻");
  }
}
const handleListPageSize = (size) => {
  pageNumber.size = size;
  pageNumber.page = 1;
  handleTreeList();
}
const handleListPage = (page) => {
  console.log(page);
  pageNumber.page = page;
  handleTreeList();
};
/** 重置 */
const resetSearch = () => {
  console.log("重置搜索");
  resetSearchParams();
  handleTreeList();
};

/** 树形表格查询 */
const handleTreeList = async () => {
  try {
    loading.value = true;
    tableList.value = []; // 重置表格数据
    const res: any = await bmList(pageNumber);
    console.log("菜单数据表格数据->", res.data.data);

    res.data.data = res.data.data.map(item => {
      return {
        ...item,
        uuid: generateUUID(),
      };
    });

    tableList.value = res.data.data;
    loading.value = false;
    total.value = res.data.count;
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试🌻");
  }
};

onMounted(() => {
  // 获取表格数据
  handleTreeList();
  getTypelist();
  // let index = tabsStore.tabList.find(tab => tab.path.includes('/paper/article/update/'));
  // console.log(index)
  // while (typeof (index) !='undefined') {
  //   tabsStore.removeTab(index.path);
  //   index = tabsStore.tabList.find(tab => tab.path.includes('/paper/article/update/'));
  // }
});

const rowClick = (row, column, e) => {
  console.log(column);
  if (column?.property == "datetime") {
    if (e.currentTarget.querySelector(".el-table__expand-icon")) {
      const expandIcon = e.currentTarget.querySelector(".el-table__expand-icon");
      if (expandIcon) {
        expandIcon.style.cursor = "pointer";
        // 如果你需要点击展开图标，也可以在这里添加点击事件
        expandIcon.click();
      }
    }
  }
}

// 重新渲染表格状态
const refreshTreeTable = ref(true);
// 是否展开[默认折叠]
const isExpandAll = ref(true);

/** 添加 */
const handleAdd = () => {
  router.push("/paper/add");
};

/** 修改 */
const handleUpdateDate = (row) => {
  console.log(row);
  Dateform.datetime = row.datetime;
  Dateform.type_id = row.type_id;
  Dateform.id = row.id;
  koiDrawerDate.value.koiOpen();
};
/** 修改 */
const handleConfirmDateDo = async () => {
  confirmLoading.value = true;
  try {
    const res: any = await dateUpdate(Dateform);
    console.log("菜单数据表格数据->", res.data);
    koiNoticeSuccess("修改成功!");
    confirmLoading.value = false;
    koiDrawerDate.value.koiQuickClose();
    handleTreeList();
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试🌻");
  }
}
const handleCancel = () => {
  koiDrawerDate.value.koiClose();
  koiDrawerBm.value.koiClose();
};
// 添加 OR 修改对话框Ref
const koiDrawerDate = ref();
const koiDrawerBm = ref();
// 确定按钮是否显示Loading
const confirmLoading = ref(false);

const openUrl = (url) => {
  router.push(url);
}

/** 删除期刊*/
const handleDeleteDate = (row: any) => {
  const id = row.id;
  koiMsgBox("您确认需要删除期刊[ " + row.datetime + " ]么？")
    .then(async () => {
      try {
        await dateDel({'id': id});
        koiNoticeSuccess("删除成功!");
        handleTreeList();
      } catch (error) {
        console.log(error);
      }
    })
    .catch(() => {
    });
};
/** 删除版面*/
const handleDeleteBm = (row: any) => {
  const id = row.id;
  koiMsgBox("您确认需要删除版面[ " + row.datetime + " ]么？")
    .then(async () => {
      try {
        await bmDel({'id': id});
        koiNoticeSuccess("删除成功!");
        handleTreeList();
      } catch (error) {
        console.log(error);
      }
    })
    .catch(() => {
    });
};
/** 删除新闻*/
const handleDeleteNews = (row: any) => {
  const id = row.id;
  koiMsgBox("您确认需要删除新闻[ " + row.datetime + " ]么？")
    .then(async () => {
      try {
        await newsDel({'id': id});
        koiNoticeSuccess("删除成功!");
        handleTreeList();
      } catch (error) {
        console.log(error);
      }
    })
    .catch(() => {
    });
};

</script>

<style lang="scss" scoped>
::v-deep(.center-input .el-input__inner ) {
  text-align: center;
}
</style>
