<template>
  <div style="display: flex">
    <div class="left-tree">
      <el-tree
        :data="treeData"
        :props="defaultProps"
        @node-click="handleNodeClick"
        class="customer-tree"
        default-expand-all
        highlight-current
        v-loading="treeLoading"
      ></el-tree>
    </div>
    <div class="plate">
      <div class="breadcrumb">首页 / <span>文献资料</span></div>
      <div class="iptBox">
        <el-input
          class="ipt"
          prefix-icon="el-icon-search"
          v-model="literatureName"
          placeholder="请输入文献名称"
          clearable
        ></el-input>
      </div>
      <div class="cont" v-for="(item, i) in list" :key="i">
        <div class="contFlex">
          <div class="contTitle">{{ item.literatureName }}</div>
          <div class="" style="display: flex">
            <!-- <div class="contNumb">
              <i class="el-icon-view"></i>{{ item.viewCount || 0 }}
            </div> -->
            <div class="contNumb">
              <i class="el-icon-download"></i>{{ item.downloadCount || 0 }}
            </div>
          </div>
        </div>
        <div class="contFlex on">
          <div>
            <div
              class=""
              style="display: flex; margin-bottom: 10px"
              v-if="item.theme"
            >
              <div class="contText">主题</div>
              <div class="contTxt">
                {{ getDictLabel("sys_theme", item.theme) || "" }}
              </div>
            </div>
            <div
              class=""
              style="display: flex; margin-bottom: 10px"
              v-if="item.publishOrganization"
            >
              <div class="contText">发布机构</div>
              <div class="contTxt">
                {{
                  getDictLabel(
                    "sys_provide_organization",
                    item.publishOrganization
                  ) || ""
                }}
              </div>
            </div>
            <div
              class=""
              style="display: flex; margin-bottom: 10px"
              v-if="item.publishType"
            >
              <div class="contText">开放类型</div>
              <div
                class="contTxt"
                :class="item.publishType === 'open' ? 'on' : ''"
              >
                {{ getDictLabel("sys_publish_type", item.publishType) || "" }}
              </div>
            </div>
            <div class="" style="display: flex">
              <div class="contText">发布时间</div>
              <div class="contTxt">
                <span v-if="item.publicYear"
                  >【{{
                    getDictLabel("sys_public_year", item.publicYear) || ""
                  }}】</span
                >
                {{ parseTime(item.createTime, "{y}-{m}-{d} {h}:{i}") }}
              </div>
            </div>
          </div>
          <div class="" style="display: flex">
            <el-button @click="preview(item)">预览</el-button>
            <el-button type="primary" @click="download(item)">下载</el-button>
          </div>
        </div>
      </div>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
        class="customer-pagination"
      />
    </div>

    <!-- 文献下载弹窗 -->
    <el-dialog
      title="文献下载"
      :visible.sync="open"
      width="600px"
      append-to-body
    >
      <div v-for="(file, i) in downList" :key="i" class="file-item">
        <a target="_blank" :href="file">
          {{ file.substr(file.lastIndexOf("/") + 1, file.length - 1) }}
        </a>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="open = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 文件预览（选择文件） -->
    <el-dialog
      title="预览"
      :visible.sync="showMutilPreview"
      width="600px"
      append-to-body
    >
      <div v-for="(file, i) in previewList" :key="i" class="file-item">
        <a @click="setPreview(file)">
          {{ file.substr(file.lastIndexOf("/") + 1, file.length - 1) }}
        </a>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showMutilPreview = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 文件预览 -->
    <el-dialog
      :title="
        '预览' +
        ' — ' +
        previewUrl.substr(
          previewUrl.lastIndexOf('/') + 1,
          previewUrl.length - 1
        )
      "
      v-if="showPreview"
      :visible="true"
      width="943px"
      append-to-body
    >
      <Preview :url="previewUrl" v-if="previewUrl" />
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="download(previewData)"
          v-if="previewData"
          >下 载</el-button
        >
        <el-button @click="showPreview = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 文件申请 -->
    <el-dialog
      title="申请文献附件权限"
      v-if="showApply"
      :visible="true"
      append-to-body
      width="600px"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="申请说明"
          >{{ applyRejectReason ? applyRejectReason : "当前文献附件受权限控制，需要提交管理员申请权限" }}</el-form-item
        >
        <el-form-item label="申请理由" prop="remark">
          <el-input
            v-model="form.remark"
            placeholder="请输入申请理由"
            type="textarea"
          ></el-input>
        </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>
import { parseQueryParam } from "@/utils/dxp";
import {
  listLiterature,
  addDownloadCount,
  getFileUrl,
} from "@/api/customer/literature";
import { applyResource } from "@/api/customer/resource";
import Preview from "@/components/Preview";
import { getDynamicsApiUrl } from "@/utils/dxp";
export default {
  name: "Literature",
  dicts: [
    "sys_provide_organization",
    "sys_theme",
    "sys_public_year",
    "sys_publish_type",
  ],
  watch: {
    literatureName: {
      handler(val) {
        this.queryParams.literatureName = val;
        this.getList();
      },
    },
  },
  components: { Preview },
  data() {
    return {
      literatureName: "",
      baseUrl: getDynamicsApiUrl(process.env.VUE_APP_BASE_API),
      queryParams: {
        literatureName: null,
        publishOrganization: null,
        theme: null,
        publicYear: null,
        status: "1",
        pageNum: 1,
        pageSize: 10,
      },
      treeLoading: false,
      loading: false,
      list: [],
      total: 0,
      treeData: [],
      open: false, // 下载弹窗
      downList: [], // 下载文件列表
      defaultProps: {
        children: "children",
        label: "label",
      },
      showPreview: false,
      showMutilPreview: false,
      previewList: [],
      previewData: null,
      previewUrl: null,
      showApply: false,
      applyRejectReason: null,
      form: {},
      rules: {
        remark: {
          required: true,
          message: "请填写申请理由",
          trigger: "blur",
        },
      },
    };
  },
  created() {
    this.treeLoading = true;

    // 获取参数
    const params = parseQueryParam(window.location.search);
    if (params.name) {
      this.literatureName = decodeURIComponent(params.name);
      this.queryParams.literatureName = this.literatureName;
    } else {
      this.literatureName = null;
      this.queryParams.literatureName = null;
    }

    const self = this;
    setTimeout(function () {
      self.getTree();
    }, 500);
    // this.getList();
  },
  methods: {
    cancel() {
      this.showApply = false;
      this.applyRejectReason = null;
      this.form = {};
    },
    getUrl(data, callback) {
      getFileUrl({ id: data.id }).then((res) => {
        if (res.data) {
          callback(res.data.fileUrl);
        } else {
          if (res.msg === "wait") {
            this.$modal.msg("您已申请当前文献附件权限，请耐心等待管理员审核");
          } else {
            if (res.msg !== '操作成功') {
              this.applyRejectReason = res.msg;
            }
            
            this.showApply = true;
            this.form = data;
          }
        }
      });
    },
    preview(data) {
      this.previewList = [];
      this.previewData = data;
      const callback = (fileUrl) => {
        if (fileUrl.indexOf(",") >= 0) {
          const previewList = [];
          fileUrl.split(",").forEach((p) => {
            previewList.push(this.baseUrl + p);
          });

          this.showMutilPreview = true;
          this.previewList = previewList;
        } else {
          this.setPreview(this.baseUrl + fileUrl);
        }
      };

      this.getUrl(data, callback);
    },
    setPreview(url) {
      this.showPreview = true;
      this.previewUrl = url;
    },
    download(data) {
      const id = data.id;
      const callback = (fileUrl) => {
        this.downList = [];
        addDownloadCount(id);
        if (fileUrl.indexOf(",") >= 0) {
          // 弹窗下载
          const downList = [];
          fileUrl.split(",").forEach((p) => {
            downList.push(this.baseUrl + p);
          });
          this.open = true;
          this.downList = downList;
          // console.log(this.downList);
        } else {
          window.open(this.baseUrl + fileUrl);
        }
      };

      this.getUrl(data, callback);
    },
    getDictLabel(dicts, val) {
      if (this.dict.type[dicts]) {
        const dict = this.dict.type[dicts].find((p) => p.value === val);
        if (dict) {
          return dict.raw.dictLabel;
        }
      }

      return null;
    },
    getTree() {
      const provideOrganizations = this.dict.type["sys_provide_organization"];
      const themes = this.dict.type["sys_theme"];
      const publicYears = this.dict.type["sys_public_year"];

      const treeData = [];

      // 发布机构
      const provideTreeData = [];
      provideOrganizations.forEach((p) => {
        provideTreeData.push({
          label: p.label,
          value: p.value,
          type: "publishOrganization",
        });
      });

      const provideTree = {
        label: "按发布机构分类",
        children: provideTreeData,
      };
      treeData.push(provideTree);

      // 主题
      const themeData = [];
      themes.forEach((p) => {
        themeData.push({
          label: p.label,
          value: p.value,
          type: "theme",
        });
      });

      const themeTree = {
        label: "按主题分类",
        children: themeData,
      };
      treeData.push(themeTree);

      // 发布年份
      const yearData = [];
      publicYears.forEach((p) => {
        yearData.push({
          label: p.label,
          value: p.value,
          type: "publicYear",
        });
      });

      const yearTree = {
        label: "按发布年份分类",
        children: yearData,
      };
      treeData.push(yearTree);
      this.treeData = treeData;
      this.treeLoading = false;
    },
    handleNodeClick(data) {
      console.log(data);
      if (data.type) {
        (this.queryParams.publishOrganization = null),
          (this.queryParams.theme = null),
          (this.queryParams.publicYear = null),
          (this.queryParams[data.type] = data.value);
        this.getList();
      }
    },
    getList() {
      listLiterature(this.queryParams).then((response) => {
        this.list = response.rows;
        this.total = response.total;
      });
    },
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const submitData = {
            resourceType: "literature",
            resourceId: this.form.id,
            remark: this.form.remark,
          };
          applyResource(submitData).then((response) => {
            this.$modal.msgSuccess("申请文献成功，请等待管理员审核");
            this.cancel();
          });
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
.left-tree {
  width: 270px;
  padding: 20px;
  box-shadow: 1px 0px 25px 0px rgba(0, 0, 0, 0.04);
  overflow: hidden;
}
.plate {
  padding: 20px 30px;
  box-sizing: border-box;
  width: 100%;
  background: #fafafa;
  min-height: 900px;

  .iptBox {
    width: 100%;
    background: #ffffff;
    box-shadow: 0px 2px 12px 0px rgba(159, 192, 255, 0.14);
    border-radius: 4px;
    padding: 30px;
    box-sizing: border-box;
    margin: 30px 0;

    .ipt {
      width: 340px;
      height: 42px;
    }
  }

  .cont {
    width: 100%;
    padding: 20px 30px;
    box-sizing: border-box;
    background: #ffffff;
    box-shadow: 0px 2px 12px 0px rgba(159, 192, 255, 0.14);
    border-radius: 4px;
    margin-bottom: 20px;

    .contFlex {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 20px;

      .contTitle {
        font-size: 20px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #333333;
      }

      .contNumb {
        font-size: 14px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #333333;
        margin-left: 30px;
      }

      .el-icon-view {
        color: #2866ff;
        margin-right: 10px;
      }

      .el-icon-download {
        color: #2866ff;
        margin-right: 10px;
      }

      .contText {
        width: 94px;
        font-size: 16px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #999999;
      }

      .contTxt {
        font-size: 16px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #666666;

        &.on {
          color: #00b42a;
        }
      }
    }

    .contFlex.on {
      margin-bottom: 0;
    }
  }
}

.customer-pagination {
  background: none;
}

.file-item {
  margin-bottom: 20px;
  text-decoration: underline;
  color: #46a6ff;
}
</style>
