<template>
  <el-dialog v-model="visible" :width="width" append-to-body show-close :close-on-click-modal="false" style="min-height: 600px;">
    <template #header>
      <div class="dialog-title-container">
        <span class="title-label" style="color: #fff; display: flex; flex-direction: row; justify-content: flex-start; align-items: center; line-height: 26px;"> <el-icon> <Document /> </el-icon>文件列表</span>
      </div>
    </template>
    <div class="page-container list-container">
      <!-- 功能按钮区 -->
      <div class="list-btns-container">
        <el-row style="font-size: 13px; padding: 2px 10px;">客户名称：{{ companyName }}</el-row>
      </div>
      <!-- 搜索区 -->
      <el-form class="list-search-container" :model="queryParams" ref="queryRef" :inline="true" label-width="68px" size="small">
        <el-form-item label="文件名称：">
          <el-input v-model.trim="queryParams.fileName" size="small" type="text" placeholder="文件名称" :clearable="true"
            style="width: 130px" />
        </el-form-item>
        <!-- <el-form-item label="客户名称：">
          <el-input v-model.trim="queryParams.companyName" size="small" type="text" placeholder="客户名称" :clearable="true"
            style="width: 130px" />
        </el-form-item> -->
        <el-form-item label="文件类型：">
          <el-select v-model="queryParams.type" clearable>
                    <el-option v-for="item in fileTypes" :key="item.value" :label="item.label"
                      :value="item.value" />
                  </el-select>
        </el-form-item>
        <el-form-item label="文件状态：">
          <el-select v-model="queryParams.deleted" clearable>
            <el-option label="正常" :value="0" />
            <el-option label="作废" :value="1" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="来源：" v-if="tenant.versionId === '4'">
          <el-select v-model="queryParams.fromTenantId" clearable>
            <el-option v-for="tenant in tenantList" :label="tenant.contactCompany" :value="tenant.fromTenantId" :key="tenant.id"/>
          </el-select>
        </el-form-item> -->
        <el-form-item label="上传人：" prop="userName">
          <el-input size="small" v-model="queryParams.userName" placeholder="请输入上传人" clearable style="width: 130px"
            @keyup.enter="handleQuery" />
        </el-form-item>

        <el-form-item prop="dateFilter" label="上传时间：">
          <el-date-picker size="small" v-model="queryParams.dateFilterFinish" type="daterange" clearable
            format="YYYY - MM - DD " value-format="YYYY-MM-DD" range-separator="至" start-placeholder="业务日期"
            end-placeholder="业务日期" style="width: 70%;"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery" size="small">搜索</el-button>
          <el-button type="primary" icon="Upload" @click="uploadHandle" size="small" v-hasPermi="['business:upload:add']">上传</el-button>
          <el-button type="danger" :disabled="!ids.length" icon="Delete" @click="handleDelete" size="small" v-hasPermi="['business:upload:remove']">作废</el-button>
        </el-form-item>
      </el-form>
      <!-- <div v-if="flag && flag2 && tenant.versionId !== '4'">
        <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
          <el-tab-pane label="全部" name="first">

          </el-tab-pane>
          <el-tab-pane label="我的" name="second">

          </el-tab-pane>
        </el-tabs>
      </div> -->

      <!-- 列表区 -->
      <el-table v-loading="loading" :data="list" size="small" border height="100%"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" :selectable="selectable" width="55" align="center" />
        <el-table-column label="文件名称" prop="fileName" min-width="110" align="left" />
        <!-- <el-table-column label="客户名称" align="center" prop="companyName">
          <template #default="scope">
            <div style="display: flex; align-items: center; ">
              <template v-if="scope.row.customerLabelName ">
                <el-tooltip :content="scope.row.customerLabelName" placement="top">
                  <el-icon :size="15">
                    <CollectionTag />
                  </el-icon>
                </el-tooltip>
                <span style="padding-left:5px;">{{ scope.row.companyName }}</span>
              </template>
              <template v-else>
                <div style="width: 20px; height: 15px;"></div>
                <span>{{ scope.row.companyName }}</span>
              </template>
            </div>
          </template>
        </el-table-column> -->
        <el-table-column label="受委托方" align="center" prop="accountName" min-width="100"
          v-if="tenant.versionId === '4'" />
        <el-table-column label="文件类型" align="center" prop="type" width="120">
          <template #default="scope">
              {{ fileTypes.find(f => f.value == scope.row.type).label }}
          </template>
        </el-table-column>
        <el-table-column label="上传人" align="center" prop="userName" width="120" />
        <el-table-column label="上传时间" align="center" prop="createTime" width="180" />
        <el-table-column label="文件状态" align="center" prop="deleted" width="80">
          <template #default="scope">
            <template v-if="scope.row.deleted">
              <el-tag type="danger">作废</el-tag>
            </template>
            <template v-else>
              <el-tag type="success">正常</el-tag>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="130" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link size="small" type="primary" circle
              @click="viewHandle(scope.row)">查看</el-button>
            <el-button size="small" link type="primary" circle
              @click="downloadHandle(scope.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-image-viewer v-if="showViewer" :url-list="currentFileList" @close="closeImages" :initial-index="showIndex" />
      <form-dialog ref="formDialogRef" :getList="getList" :fileTypes="fileTypes" />
      <view-dialog ref="viewDialogRef" :getList="getList" />
    </div>
  </el-dialog>
</template>

<script setup name="ResouceUpload">
  import { listLableNoPage } from "@/api/business/lable"
  import { listFile, delFile } from "@/api/business/fileUpload";
  import { uploadFile, downloadFile } from "@/api/tool/file";
  import useUserStore from "@/store/modules/user";
  import { ref } from "vue";
  import formDialog from "./form.vue";
  import viewDialog from "./view.vue";
  import {
    listEntrustOrder,
  } from "@/api/business/entrust/entrustOrder";
  import {
    listProductionCompany,
  } from "@/api/business/production/productionCompany";

  const { proxy } = getCurrentInstance();
  /** 字典数组区 */
  /** 查询 对象 */
  const tenant = useUserStore().tenant
  const list = ref([]);
  const loading = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const oneself = ref(false);
  const total = ref(0);
  const baseUrl = ref(import.meta.env.VITE_APP_BASE_API);
  const showViewer = ref(false);
  const currentFileList = ref([]);
  const showIndex = ref(0);
  const tenantList = ref([]);
  const visible = ref(false);
  const width = ref(1400)

  const permissions = useUserStore().permissions;

  const fileTypes = ref([
    {value: 1, label: '票据'},
    {value: 2, label: '银行'},
    {value: 3, label: '社保及公积金'},
    {value: 4, label: '库存表'},
  ])
  const formOpen = ref(false);
  const formDialogRef = ref(null);
  const viewDialogRef = ref(null);
  const flag = ref(checkPermission(['business:upload:person']))
  const flag2 = ref(checkPermission(['business:upload:myself']))
  const activeName = flag.value ? ref('first') : ref('second');
  const options = ref([]);
  const form = ref({
    id: null,
    companyName: "",
    companyId: null,
    remark: "",
    type: 1,
    files: [],
  });

  const emptyForm = {
    id: null,
    companyName: "",
    companyId: null,
    type: 1,
    remark: "",
    files: [],
  };

  /** 查询对象 */
  const queryParams = ref({
    pageNum: 1,
    pageSize: 20,
    orderByColumn: "create_time",
    // year: proxy.moment().subtract(1, "month").format("yyyy"),
    // month: proxy.moment().subtract(1, "month").format("MM"),
    principal: tenant.versionId !== '4' && !flag.value ? useUserStore().user.userId : null,
    tenantVersionId: tenant.versionId,
    // companyId: proxy.$route.query.companyId
  });

  const companyName = ref('')

  /***********************  方法区  ****************************/
    /** 查询company列表 */
  // function getList() {
  //   loading.value = true;
  //   listProductionCompany(queryParams.value).then((response) => {
  //     list.value = response.rows;
  //     total.value = response.total;
  //     loading.value = false;
  //   });
  // }

  function open(arg) {
    visible.value = true;
    queryParams.value.companyId = arg.companyId
    companyName.value = arg.companyName
    getList()
    // form.value = arg;
    // loading.value = true
    // fileExtension.value = arg.fileName.match(/\.([^.]+)$/)[1];
  }
  /**
   * 对话框关闭 事件
   */
  function close() {
    visible.value = false;
  }

  function selectable(row) {
    return !row.deleted
  }

  function getEntrustOrderList() {
    if(tenant.versionId != '4') {
      return
    }
    listEntrustOrder({
    pageNum: 1,
    pageSize: 20,
    orderByColumn: "create_time", status: 1}).then(res => {
      tenantList.value = res.rows
    })
  }

  onActivated(() => {
    // 你的逻辑
    // getList();
    getEntrustOrderList()
  });
  /** 查询文件列表 */
  function getList() {
    loading.value = true;
    listFile(queryParams.value).then((response) => {
      list.value = response.rows.map((l) => ({ ...l }));
      // prev.value = proxy.deepClone(response.rows);
      total.value = response.total;
      loading.value = false;
    });
  }

  /** 是否为自己负责 */
  function handleOneself() {
    if (oneself.value) {
      queryParams.value.principal = useUserStore().user.userId;
    } else {
      queryParams.value.principal = null;
    }
    getList();
  }

  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }
  function checkPermission(templatePermission) {
    const all_permission = "*:*:*";
    const permissions = useUserStore().permissions;
    const hasPermissions = permissions.some((permission) => {
      return (
        all_permission === permission || templatePermission.includes(permission)
      );
    });
    return hasPermissions;
  }
  /** 重置按钮操作 */
  function resetQuery() {
    queryParams.value = {
      pageNum: 1,
      pageSize: 20,
      year: proxy.moment().format("YYYY"),
      month: proxy.moment().format("MM"),
      orderByColumn: "create_time",
      tenantVersionId: tenant.versionId
    };
    if (activeName.value != null && activeName.value === 'second') {
      queryParams.value.principal = useUserStore().user.userId;
    }
    handleQuery();
  }

  // 多选框选中数据
  function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }
  function getOption() {
    listLableNoPage().then(res => {
      options.value = res.data
    })
  }

  function formCancel() {
    formOpen.value = false;
    reset();
  }

  function reset() {
    form.value = proxy.deepClone(emptyForm);
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const _ids = row.id || ids.value;
    proxy.$modal
      .confirm("是否确认作废选中的数据项？")
      .then(function () {
        return delFile(_ids);
      })
      .then(() => {
        getList();
        proxy.$modal.msgSuccess("作废成功！");
      })
      .catch(() => { });
  }

  function upload(param) {
    const formData = new FormData();
    formData.append("file", param.file);
    uploadFile(formData).then((res) => {
      if (res.code === 200) {
        const file = {};
        file.fileName = res.newFileName;
        file.url = res.url;
        file.originalFileName = res.originalFilename;
        file.fileUrl = res.fileName;
        file.masterId = form.value.id;
        file.masterTableName = "biz_deduction";
        form.value.files.push(file);
      }
    });
  }

  function showFileList(row) {
    currentFileList.value = row.files.map((l) => `${baseUrl.value}${l.fileUrl}`);
    showViewer.value = true;
  }

  function closeImages() {
    showViewer.value = false;
  }

  function uploadHandle(row) {
    formDialogRef.value.open({companyId: queryParams.value.companyId});
  }
  function viewHandle(row) {
    const fileExtension = row.fileName.match(/\.([^.]+)$/)[1];
    if(!['xlsx', 'xls', 'doc', 'docx', 'txt', 'pdf', 'jpg', 'png'].includes(fileExtension)) {
      proxy.$modal.msgError(`该文件格式不支持预览!`);
      return false
    }
    viewDialogRef.value.open(row);
  }
  function downloadHandle(row) {
    downloadFile({fileName: row.fileUrl, delete: false})
      .then((blob) => {
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        // 下载文件的名称及文件类型后缀
        link.download = row.fileName;
        document.body.appendChild(link);
        link.click();
        //在资源下载完成后 清除 占用的缓存资源
        window.URL.revokeObjectURL(link.href);
        document.body.removeChild(link);
      });
  }

  defineExpose({
    open,
  });
</script>