<!-- 资产管理 -- 小程序 -->
<template>
  <el-row
    :gutter="20"
    style="height: 100%; background-color: #f2f4f6; display: flex"
  >
    <!--部门数据-->
    <el-col
      :span="3"
      :xs="24"
      style="
        margin-right: 10px;
        height: 100%;
        background-color: #fff;
        padding-top: 20px;
      "
    >
      <div class="head-container">
        <el-tree
          :data="deptOptions"
          :props="defaultProps"
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
          ref="tree"
          node-key="id"
          default-expand-all
          highlight-current
          @node-click="handleNodeClick"
        />
      </div>
    </el-col>
    <el-col
      :span="20"
      :xs="24"
      style="height: 100%; flex: 1"
    >
      <div
        class="L-main"
        id="L-size-main"
      >
        <div
          class="content-search"
          id="L-header"
        >
          <div class="search-title">查询条件</div>
          <el-form
            :inline="true"
            ref="queryForm"
            :model="formInline"
            :size="size"
            class="demo-form-inline"
            label-width="100px"
          >
            <el-row>
              <el-col :span="6">
                <el-form-item
                  label="所属单位："
                  prop="dwmc"
                >
                  <el-input
                    v-model="formInline.dwmc"
                    placeholder="请输入所属单位"
                    style="width: 95%;"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="小程序名称："
                  prop="xcxmc"
                >
                  <el-input
                    v-model="formInline.xcxmc"
                    placeholder="请输入小程序名称"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="新增时间："
                  prop="time"
                >
                  <el-date-picker
                    v-model="time"
                    type="datetimerange"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    placeholder="请选择"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                  />
                </el-form-item>
              </el-col>
              <el-col
                :span="4"
                style="text-align: right"
              >
                <el-form-item class="unit-form">
                  <el-button
                    size="mini"
                    @click="resetQuery('queryFrom')"
                    >重置</el-button
                  >
                  <el-button
                    size="mini"
                    type="primary"
                    @click="handleQuery('queryFrom')"
                    >查询</el-button
                  >
                </el-form-item>
              </el-col>
            </el-row>
            <!-- <el-row>
              <el-col :span="8">
                <el-form-item label="小程序状态：" prop="xtzt">
                  <el-select v-model="formInline.xtzt" placeholder="请选择系统状态">
                    <el-option
                      v-for="dict in dict.type.gzh_state"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="16" style="text-align: right;padding-right: 30px;">
                <el-form-item>
                  <el-button size="mini" @click="resetQuery('queryFrom')">重置</el-button>
                  <el-button size="mini" type="primary" @click="handleQuery('queryFrom')">查询</el-button>
                </el-form-item>
              </el-col>
            </el-row> -->
          </el-form>
        </div>
        <main>
          <div class="search-title">
            <span class="search-title-span">资产列表（蓝色为单位新增资产）</span>
            <el-row
              :gutter="10"
              class="mb8"
            >
              <el-col :span="1.5">
                <el-button
                  type="info"
                  plain
                  :icon="Upload"
                  size="mini"
                  @click="handleImport"
                  >导入</el-button
                >
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="warning"
                  plain
                  :icon="Download"
                  size="mini"
                  @click="handleExport"
                  >导出</el-button
                >
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  plain
                  :icon="Plus"
                  size="mini"
                  @click="handleAdd"
                  >新增资产</el-button
                >
              </el-col>
            </el-row>
          </div>
          <section>
            <el-table
              v-loading="loading"
              :data="tableData"
              :height="tabHeader"
              :row-class-name="tableRowClassName"
              :max-height="tabHeader"
            >
              <el-table-column
                type="index"
                width="60" 
                label="序号"
                align="center"
              />
              <el-table-column
                label="小程序名称"
                key="xcxmc"
                prop="xcxmc"
                align="center"
              >
                <template #default="scope">
                  <span
                    :style="{ color: scope.row.xzType == 1 ? 'blue' : '' }"
                    >{{ scope.row.xcxmc }}</span
                  >
                </template>
                <!-- <template #default="scope">
                  <dict-tag :options="dict.type.zc_xtlx" :value="scope.row.xtlx"/>
                </template> -->
              </el-table-column>
              <el-table-column
                label="所属单位"
                key="ssdw"
                prop="ssdw"
                align="center"
              />
              <!-- <el-table-column label="单位名称" key="dwmc" prop="dwmc" align="center">
              </el-table-column> -->
              <!-- <el-table-column label="新增时间" key="createTime" prop="createTime" align="center" /> -->
              <el-table-column
                label="小程序状态"
                key="state"
                prop="state"
                class-name="table-status"
                align="center"
              >
                <template #default="scope">
                  <span
                    v-if="scope.row.state == 1"
                    style="color: #16b771"
                  >
                    正常
                  </span>
                  <span
                    v-if="scope.row.state == 2"
                    style="color: #f58a0c"
                  >
                    注销
                  </span>
                  <span
                    v-if="scope.row.state == 3"
                    style="color: #1485ef"
                  >
                    迁移
                  </span>
                  <span
                    v-if="scope.row.state == 4"
                    style="color: #29a07a"
                  >
                    受限
                  </span>
                  <span
                    v-if="scope.row.state == 5"
                    style="color: #f50c0c"
                  >
                    违规
                  </span>
                  <span
                    v-if="scope.row.state == 6"
                    style="color: #f58a0c"
                  >
                    未知
                  </span>
                  <span
                    v-if="scope.row.state == 7"
                    style="color: #f50c0c"
                  >
                    关停
                  </span>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                prop="userId"
                class-name="table-operation"
                align="center"
              >
                <template #default="scope">
                  <div
                    style="
                      display: flex;
                      align-items: center;
                      justify-content: center;
                    "
                  >
                    <div
                      style="
                        display: flex;
                        align-items: center;
                        cursor: pointer;
                      "
                      @click="goInfo(scope.row, 1)"
                    >
                      <img
                        src="@/assets/images/icon-ck@2x.png"
                        alt=""
                        style="width: 20px; margin-right: 5px"
                      />
                      <span
                        class="look-info"
                        style="color: #1485ef; margin-right: 15px"
                        >查看</span
                      >
                    </div>
                    <div
                      style="
                        display: flex;
                        align-items: center;
                        cursor: pointer;
                      "
                      @click="goInfo(scope.row, 2)"
                    >
                      <img
                        src="@/assets/images/edit.png"
                        alt=""
                        style="width: 15px; margin-right: 5px"
                      />
                      <span
                        class="look-info"
                        style="color: #1485ef; margin-right: 15px"
                        >编辑</span
                      >
                    </div>
                    <div
                      style="
                        display: flex;
                        align-items: center;
                        cursor: pointer;
                      "
                      @click="goInfo(scope.row, 3)"
                    >
                      <img
                        src="@/assets/images/del.png"
                        alt=""
                        style="width: 20px; margin-right: 5px"
                      />
                      <span
                        class="look-info"
                        style="color: #f50c0c; margin-right: 15px"
                        >删除</span
                      >
                    </div>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </section>
          <my-pagination
            id="L-pagination"
            :total="total"
            :page="formInline.current"
            :limit="formInline.size"
            @pagination="getPagination"
            :current-page.sync="formInline.current"
          ></my-pagination>
        </main>
        <!-- 资产导入对话框 -->
        <el-dialog
          :title="upload.title"
          :visible.sync="upload.open"
          width="400px"
          append-to-body
        >
          <el-upload
            ref="upload"
            :limit="1"
            accept=".xlsx, .xls"
            :headers="upload.headers"
            :action="upload.url + '?updateSupport=' + upload.updateSupport"
            :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="false"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <div
              class="el-upload__tip text-center"
              slot="tip"
            >
              <!-- <div class="el-upload__tip" slot="tip">
                <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
              </div> -->
              <span>仅允许导入xls、xlsx格式文件。</span>
              <el-link
                type="primary"
                :underline="false"
                style="font-size: 12px; vertical-align: baseline"
                @click="importTemplate"
                >下载模板</el-link
              >
            </div>
          </el-upload>
          <div
            slot="footer"
            class="dialog-footer"
          >
            <el-button
              type="primary"
              @click="submitFileForm"
              >确 定</el-button
            >
            <el-button @click="upload.open = false">取 消</el-button>
          </div>
        </el-dialog>
      </div>
    </el-col>
  </el-row>
</template>
<script setup>
import { Upload,Download,Plus } from '@element-plus/icons-vue'
import { ref, onMounted, onUnmounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import myPagination from "@/views/components/Pagination/index.vue";
import { getToken } from "@/utils/auth";
import {
  miniProgramsList,
  deleteMiniPrograms,
  schema,
} from "@/api/auditPagesApi/index";

const router = useRouter();
const route = useRoute();
const size = ref('default')

// 响应式数据定义
const deptOptions = ref(undefined);
const defaultProps = {
  children: "children",
  label: "label",
};
const formInline = ref({
  dwmc: "",
  xcxmc: "",
  startTime: "",
  endTime: "",
  current: 1,
  size: 10,
});
const time = ref([]);
const total = ref(0);
const tableData = ref([]);
const loading = ref(false);
const tabHeader = ref(undefined);

const upload = ref({
  open: false,
  title: "小程序资产导入",
  isUploading: false,
  updateSupport: 0,
  headers: { Authorization: "Bearer " + getToken() },
    url:
    import.meta.env.VITE_APP_HJ === "test"
      ? import.meta.env.VITE_APP_BASE_API +
        "/tc/assetOfficialAccount/importData"
      : location.origin + "/api/tc/assetOfficialAccount/importData",
});

function getDeptTree() {
  schema({ type: 1 }).then((response) => {
    deptOptions.value = response.data;
  });
}

function filterNode(value, data) {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
}

function handleNodeClick(data) {
  formInline.value.deptId = data.id;
  handleQuery();
}

function getList() {
  loading.value = true;
  miniProgramsList(formInline.value).then((res) => {
    loading.value = false;
    total.value = res.data.total;
    tableData.value = res.data.records;
  });
}

function resetQuery() {
  // resetForm('queryForm') // 暂未实现
  time.value = [];
  formInline.value.deptId = undefined;
  // this.$refs.tree.setCurrentKey(null)
  handleQuery();
}

function handleQuery() {
  formInline.value.current = 1;
  if (time.value && time.value.length === 2) {
    formInline.value.startTime = time.value[0];
    formInline.value.endTime = time.value[1];
  }
  getList();
}

function getPagination(pages) {
  formInline.value.current = pages.page;
  formInline.value.size = pages.limit;
  getList();
}

function handleImport() {
  upload.value.open = true;
}

function handleExport() {
  download(
    "/tc/miniPrograms/export",
    {
      ...formInline.value,
    },
    `小程序资产${new Date().getTime()}.xlsx`
  );
}

function importTemplate() {
  download(
    "/tc/miniPrograms/importTemplate",
    {},
    `小程序资产导入模板${new Date().getTime()}.xlsx`
  );
}

function handleFileUploadProgress(event, file, fileList) {
  upload.value.isUploading = true;
}

function handleFileSuccess(response, file, fileList) {
  upload.value.open = false;
  upload.value.isUploading = false;
  this.$refs.upload.clearFiles()
  this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getList();
}

function submitFileForm() {
  this.$refs.upload.submit();
}

function handleAdd() {
  router.push({
    path: "/assetsManage2/xcxZCinfo",
    query: {
      pageType: "add",
      type: 1,
      parentName: "/assetsManage2/xcxZC",
    },
  });
}

function goInfo(row, id) {
  console.log(formInline.value,'row')
  if (id === 1) {
    router.push({
      path: "/assetsManage2/xcxZCinfo",
      query: {
        pageType: "look",
        type: 1,
        id: row.id,
        queryData: formInline.value,
        parentName: "/assetsManage2/xcxZC",
      },
    });
  } else if (id === 2) {
    router.push({
      path: "/assetsManage2/xcxZCinfo",
      query: {
        pageType: "change",
        type: 1,
        id: row.id,
        queryData: formInline.value,
        parentName: "/assetsManage2/xcxZC",
      },
    });
  } else if (id === 3) {
    const userIds = row.id;
    this.$modal
      .confirm('是否确认删除用户编号为"' + userIds + '"的数据项？')
      .then(() => {
        return deleteMiniPrograms(userIds);
      })
      .then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      })
      .catch(() => {});
  }
}

function tableRowClassName({ row, rowIndex }) {
  if (rowIndex % 2 !== 0) {
    return "evenNumber-row";
  }
  return "";
}

function cancalDebounce() {
  const element = document.getElementById("L-size-main");
  const header = document.getElementById("L-header");
  const pagination = document.getElementById("L-pagination");
  const elementHeight = element?.offsetHeight || 0;
  const headerHeight = header?.offsetHeight || 0;
  const paginationtHeight = pagination?.offsetHeight || 0;
  tabHeader.value = elementHeight - headerHeight - paginationtHeight - 110;
}

// 生命周期
onMounted(() => {
  if (Object.keys(route.params).length !== 0) {
    formInline.value = route.params;
  } else {
    formInline.value.current = 1;
    formInline.value.size = 20;
  }
  getDeptTree();
  getList();
  cancalDebounce();
  window.addEventListener("resize", cancalDebounce);
});

onUnmounted(() => {
  window.removeEventListener("resize", cancalDebounce);
});
</script>
