<template>
  <div class="testdiv">
    <div class="divborder newSearchDiv">
      <!-- 文档状态 -->
      <div class="filter">
        <label>{{ $t("1221") }}：</label>
        <Select v-model="status" clearable class="searchSelect">
          <Option value="0">{{ $t("1013") }}</Option>
          <Option value="1">{{ $t("700096") }}</Option>
          <Option value="2">{{ $t("950440") }}</Option>
          <Option value="3">{{ $t("950320") }}</Option>
          <Option value="4">{{ $t("950472") }}</Option>
          <Option value="5">{{ $t("950443") }}</Option>
        </Select>
      </div>
      <!-- 文档类型 -->
      <div class="filter">
        <label>{{ $t("900754") }}：</label>
        <Select v-model="docuType" clearable class="searchSelect">
          <Option
            v-for="item in docuTypeList"
            :value="item.id"
            :key="item.id"
            >{{ item.name }}</Option
          >
        </Select>
      </div>
      <!-- 检索 -->
      <div class="filter">
        <label>{{ $t("100405") }}：</label>
        <Input clearable class="searchInput" type="text" v-model="keyword" />
      </div>
      <!-- 创建时间 -->
      <div class="filter">
        <label>{{ $t("1020") }}：</label>
        <DatePicker
          type="daterange"
          :value="dateTime"
          class="searchInput middleWidth"
          @on-change="selectDate"
        ></DatePicker>
      </div>
      <div class="searchBtn">
        <Button
          type="primary"
          class="twoWord"
          icon="ios-search"
          @click="Search()"
          >{{ $t("1001") }}</Button
        >
        <Button
          type="success"
          class="twoWord"
          icon="md-add-circle"
          @click="add()"
          >{{ $t("1002") }}</Button
        >
        <Button
          type="warning"
          class="twoWord"
          icon="ios-create-outline"
          @click="edit()"
          >{{ $t("1003") }}</Button
        >
        <Button
          type="error"
          class="twoWord"
          icon="md-close-circle"
          @click="del()"
          >{{ $t("1222") }}</Button
        >
        <Button
          type="primary"
          class="twoWord intervalRight"
          icon="md-eye"
          @click="preview()"
          >{{ $t("90000066") }}</Button
        >
        <Button
          type="primary"
          class="fourWord"
          icon="ios-cloud-upload"
          @click="Update()"
          >{{ $t("930130") }}</Button
        >
        <Button
          type="primary"
          class="fourWord"
          icon="ios-settings"
          @click="Manage()"
          >{{ $t("200238") }}</Button
        >
        <Button
          type="primary"
          class="fourWord"
          icon="md-download"
          @click="Download()"
          >{{ $t("200239") }}</Button
        >
      </div>
    </div>
    <div class="divborder newTableDiv">
      <Table
        class="tableClass"
        highlight-row
        :data="tableData"
        :columns="tableColumns2"
        @on-current-change="handleRowChange"
      ></Table>
      <!-- 底部分页区域 -->
      <div class="pageDiv">
        <div class="pageDirection">
          <Page
            :total="total"
            :current="page"
            @on-change="changePage"
            show-elevator
            show-sizer
            show-total
            @on-page-size-change="handlePageSize"
            :page-size-opts="[10, 20, 30, 40, 100]"
          ></Page>
        </div>
      </div>
    </div>

    <!-- -->
    <Modal
      class="newModalClass"
      v-model="showModal"
      :styles="{ width: '620px' }"
    >
      <p slot="header">
        <span v-if="type == 1">{{ $t("1002") }}</span>
        <span v-if="type == 2">{{ $t("1003") }}</span>
      </p>
      <div class="Main">
        <!-- 文档名称 -->
        <div>
          <label>
            <i>*</i>
            {{ $t(900752) }}：
          </label>
          <Input v-model="addobj.documentName" class="searchInput" />
        </div>
        <!-- 文档类型 -->
        <div>
          <label>
            <i>*</i>
            {{ $t("900754") }}：
          </label>
          <Select
            filterable
            clearable
            v-model="addobj.documentType"
            :disabled="type == 1 ? false : true"
            class="searchSelect"
            @on-change="documentTypeChange"
          >
            <Option
              v-for="item in docuTypeList"
              :value="item.id"
              :key="item.id"
              >{{ item.name }}</Option
            >
          </Select>
        </div>
        <!-- 选择文件 -->
        <div>
          <label>
            <i>*</i>
            {{ $t(700013) }}：
          </label>
          <Upload
            style="
              display: inline-block;
              white-space: nowrap;
              text-overflow: ellipsis;
              overflow: hidden;
              vertical-align: middle;
            "
            ref="upload"
            name="excel-file"
            :action="action"
            :headers="headers"
            :show-upload-list="false"
            :on-format-error="handleFormatError"
            :on-success="handleSuccess"
            :on-error="handleError"
          >
            <Button icon="md-folder" class="selectBtn">{{
              uploadtitle
            }}</Button>
          </Upload>
        </div>
        <!-- 关联产品 -->
        <div>
          <label>{{ $t("900560") }}：</label>
          <Select
            clearable
            filterable
            label-in-value
            class="searchSelect"
            v-model="addobj.relatedProduct"
          >
            <Option
              v-for="item in relatedProductList"
              :value="item.id"
              :key="item.id"
              >{{ item.code }}{{ item.name }}({{ item.drawingcode }})</Option
            >
          </Select>
        </div>
        <!-- 关联设备 -->
        <div>
          <label>{{ $t("900774") }}：</label>
          <Select
            clearable
            filterable
            label-in-value
            class="searchSelect"
            v-model="addobj.relatedEquipment"
          >
            <Option
              v-for="item in ListNCMachinesList"
              :value="item.id"
              :key="item.id"
              >{{ item.name }}({{ item.code }})</Option
            >
          </Select>
        </div>
        <!-- 使用部门 -->
        <div>
          <label>{{ $t("600325") }}：</label>
          <Select
            clearable
            filterable
            label-in-value
            class="searchSelect"
            v-model="addobj.useDepartment"
          >
            <Option
              v-for="item in UserDepartmentList"
              :value="item.id"
              :key="item.id"
              >{{ item.title }}</Option
            >
          </Select>
        </div>
        <!-- 备注 -->
        <div>
          <label>{{ $t(1030) }}：</label>
          <Input v-model="addobj.note" class="searchInput textarea" />
        </div>
        <!-- 是否默认展示 -->
        <div>
          <label><i>*</i>{{ "是否默认展示" }}：</label>
          <RadioGroup class="radiobox" v-model="addobj.showStatus">
            <Radio :label="0"
              ><span>{{ this.$t("1237") }}</span>
            </Radio>
            <Radio :label="1"
              ><span>{{ this.$t("1238") }}</span>
            </Radio>
          </RadioGroup>
        </div>
        <!-- 审核流程(添加) -->
        <div class="addAudit" v-if="type == 1">
          <label class="auditLable">{{ $t(960580) }}：</label>
          <Timeline>
            <TimelineItem v-if="addflag">
              <p class="time">
                <span>{{ $t("1231") }}</span>
              </p>
            </TimelineItem>
            <TimelineItem
              v-else
              v-for="(item, index) in auditList"
              :key="index"
            >
              <p class="time">
                <span>{{ $t("1077") }}{{ index + 1 }}{{ $t("1232") }}</span>
              </p>
            </TimelineItem>
          </Timeline>
        </div>
        <!-- 审核流程(修改) -->
        <div class="addAudit" v-if="type == 2">
          <label class="auditLable">{{ $t(960580) }}：</label>
          <Timeline>
            <TimelineItem v-if="auditeditflag">
              <p class="time">
                <span>{{ $t("1231") }}</span>
              </p>
            </TimelineItem>
            <TimelineItem
              v-else
              v-for="(item, index) in auditeditList"
              :key="index"
            >
              <p class="time">
                <span>{{ $t("1077") }}{{ index + 1 }}{{ $t("1232") }}</span>
              </p>
            </TimelineItem>
          </Timeline>
        </div>
      </div>
      <div slot="footer">
        <Button type="text" size="large" @click="showModal = false">{{
          $t(1033)
        }}</Button>
        <Button
          type="primary"
          v-if="type == 1"
          size="large"
          @click="saveData(1)"
          >{{ $t("1002") }}</Button
        >
        <Button
          type="primary"
          v-if="type == 2"
          size="large"
          @click="saveData(2)"
          >{{ $t("1003") }}</Button
        >
      </div>
    </Modal>

    <!-- 版本更新弹框 -->
    <Modal
      class="newModalClass"
      v-model="updateModal"
      :styles="{ width: '620px' }"
    >
      <p slot="header">
        <span>{{ $t("930130") }}</span>
      </p>
      <div class="Main">
        <!-- 文件名称 -->
        <div>
          <label>
            <i>*</i>
            {{ $t(900752) }}：
          </label>
          <Input
            disabled
            class="searchInput"
            v-model="updateobj.documentName"
          />
        </div>
        <!-- 文件类型 -->
        <div>
          <label>
            <i>*</i>
            {{ $t("900754") }}：
          </label>
          <Select
            disabled
            clearable
            label-in-value
            v-model="updateobj.documentType"
            class="searchSelect"
          >
            <Option
              v-for="item in docuTypeList"
              :value="item.id"
              :key="item.id"
              >{{ item.name }}</Option
            >
          </Select>
        </div>
        <!-- 选择文件 -->
        <div>
          <label>
            <i>*</i>
            {{ $t(700013) }}：
          </label>
          <Upload
            style="
              display: inline-block;
              white-space: nowrap;
              text-overflow: ellipsis;
              overflow: hidden;
              vertical-align: middle;
            "
            ref="upload"
            name="excel-file"
            :action="action"
            :headers="headers"
            :show-upload-list="false"
            :on-format-error="handleFormatError"
            :on-success="handleUpdateSuccess"
            :on-error="handleUpdateError"
            v-model="updateobj.selectFile"
          >
            <Button icon="md-folder" class="selectBtn">{{
              uploadtitle
            }}</Button>
          </Upload>
        </div>
        <!-- 关联产品 -->
        <div>
          <label>{{ $t("900560") }}：</label>
          <Select
            disabled
            clearable
            filterable
            label-in-value
            class="searchSelect"
            v-model="updateobj.relatedProduct"
          >
            <Option
              v-for="item in relatedProductList"
              :value="item.id"
              :key="item.id"
              >{{ item.name }}</Option
            >
          </Select>
        </div>
        <!-- 关联设备 -->
        <div>
          <label>{{ $t("900774") }}：</label>
          <Select
            disabled
            clearable
            filterable
            label-in-value
            class="searchSelect"
            v-model="updateobj.relatedEquipment"
          >
            <Option
              v-for="item in ListNCMachinesList"
              :value="item.id"
              :key="item.id"
              >{{ item.name }}</Option
            >
          </Select>
        </div>
        <!-- 使用部门 -->
        <div>
          <label>{{ $t("600325") }}：</label>
          <Select
            disabled
            clearable
            label-in-value
            class="searchSelect"
            v-model="updateobj.useDepartment"
          >
            <Option
              v-for="item in UserDepartmentList"
              :value="item.id"
              :key="item.id"
              >{{ item.title }}</Option
            >
          </Select>
        </div>
        <!-- 备注 -->
        <div>
          <label>{{ $t(1030) }}：</label>
          <Input
            v-model="updateobj.note"
            class="searchInput textarea"
            disabled
          />
        </div>
        <!-- 审核流程 -->
        <div class="updateAudit">
          <label class="auditLable">{{ $t(960580) }}：</label>
          <Timeline>
            <TimelineItem v-show="updateflag">
              <p class="time">
                <span>{{ $t("1231") }}</span>
              </p>
            </TimelineItem>
            <TimelineItem v-for="(item, index) in updateList" :key="index">
              <p class="time">
                <span>{{ $t("1077") }}{{ index + 1 }}{{ $t("1232") }}</span>
              </p>
            </TimelineItem>
          </Timeline>
        </div>
      </div>
      <div slot="footer">
        <Button type="text" size="large" @click="updateModal = false">{{
          $t("1033")
        }}</Button>
        <Button type="primary" size="large" @click="confirmBtn()">{{
          $t("900552")
        }}</Button>
      </div>
    </Modal>

    <!-- 版本管理弹框 -->
    <Modal
      class="newModalClass"
      v-model="manageModal"
      :styles="{ width: '950px' }"
    >
      <p slot="header">
        <span>{{ $t("200238") }}</span>
      </p>
      <div class="divborder newTableDiv manageTable">
        <Table
          class="tableClass"
          highlight-row
          :max-height="260"
          :data="tableData1"
          :columns="tableColumns1"
          @on-current-change="handleManageRowChange"
        ></Table>
      </div>
      <div slot="footer">
        <Button type="text" size="large" @click="manageModal = false">{{
          $t("1033")
        }}</Button>
        <Button type="primary" size="large" @click="confirmBtn3()">{{
          $t("900552")
        }}</Button>
      </div>
    </Modal>

    <!-- 预览对话框 -->
    <Modal
      class="newModalClass"
      title="预览"
      v-model="showmodal"
      :styles="{ width: '760px' }"
    >
      <div style="width: 700px; height: 600px; overflow: auto">
        <div v-show="showcontent" ref="preview_content"></div>
        <div v-show="showpdf">
          <embed
            :src="pdfurl"
            type="application/pdf"
            width="100%"
            height="500px"
          />
        </div>
      </div>
      <div slot="footer">
        <Button type="text" size="large" @click="showmodal = false">{{
          $t("1033")
        }}</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import axios from "@/libs/api.request";
export default {
  data() {
    return {
      addflag: false,
      auditeditflag: false,
      updateflag: false,
      htmlContent: "",
      updateModal: false, // 版本更新对话框
      showmodal: false, // 预览对话框隐藏
      manageModal: false, // 版本管理对话框
      showpdf: false,
      pdfurl: "",
      managePreviewModal: false, // 版本管理预览弹框
      showcontent: false,
      uploadtitle: "请选择上传文件",
      total: 0, // 总条数
      status: "", // 搜索条件-文档状态
      docuType: "", // 搜索条件-文档类型
      keyword: "", // 搜索条件-检索关键字
      page: 1, // 页码
      pagesize: 10, // 一页展示多少条数据
      type: 0, // type 为 1 是添加操作 type 为 2 是修改操作
      dateTime: [], // 搜索时间范围
      docuTypeList: [], // 文档类型数据
      image_name: "", //  文件名称
      pdf_name: "", //  上传文件路径
      file_image_name: "",
      file_pdf_name: "",
      relatedProduct: 0,
      useDepartment: 0,
      relatedProductList: [], // 关联产品下拉数据
      ListNCMachinesList: [], // 关联设备下拉数据
      UserDepartmentList: [], // 使用部门下拉数据
      tableData: [], // table 数据
      tableData1: [], // 弹框table表格数据
      auditList: [], // 判断数组长度
      updateList: [],
      auditeditList: [],
      showModal: false, // 是否展示弹出框
      addobj: {}, // 添加弹框表单对象
      updateobj: {}, // 更新弹框表单对象
      manageobj: {},
      detailobj: {},
      action: this.axios.publicPath + "esop/upload/UploadImage", // 上传的地址
      headers: {
        // 设置上传的请求头部
        token: localStorage.getItem("token"),
        timestamp: localStorage.getItem("timestamp"),
        nonce: localStorage.getItem("nonce"),
        sign: localStorage.getItem("sign"),
      },
      tableColumns2: [
        {
          type: "sort",
          title: this.$t("1008"),
          render: (h, params) => {
            return h(
              "span",
              params.index + (this.page - 1) * this.pagesize + 1
            );
          },
          width: "50px",
        },
        {
          title: this.$t("900752"),
          key: "name",
        },
        {
          title: this.$t("900754"),
          key: "type_name",
        },
        {
          title: this.$t("930131"),
          key: "version_name",
        },
        {
          title: this.$t("100088"),
          key: "product_name",
        },
        {
          title: this.$t("100040"),
          key: "creator_name",
        },
        {
          title: this.$t("1020"),
          key: "create_time",
        },
        {
          title: this.$t("960580"),
          key: "process_name",
        },
        {
          title: this.$t("930132"),
          key: "file_name",
        },
        {
          title: this.$t("930133"),
          key: "version",
        },
        {
          title: this.$t("200054"),
          key: "approval_status",
          width: "120px",
          align: "center",
          render: (h, params) => {
            var statusText = "",
              statusBg = "#00FFFF";
            if (params.row.approval_status == 1) {
              statusText = this.$t(700096);
              statusBg = "#f0ad4e";
            } else if (params.row.approval_status == 2) {
              statusText = this.$t(950440);
              statusBg = "#f0ad4e";
            } else if (params.row.approval_status == 3) {
              statusText = this.$t(950320);
              statusBg = "green";
            } else if (params.row.approval_status == 4) {
              statusText = this.$t(950472);
              statusBg = "#d7d7d7";
            } else if (params.row.approval_status == 5) {
              statusText = this.$t(950443);
              statusBg = "red";
            }
            return h(
              "div",
              {
                class: "",
                style: {
                  backgroundColor: statusBg,
                  color: "#fff",
                  width: "100%",
                  height: "36px",
                  lineHeight: "36px",
                  textAlign: "center",
                },
              },
              statusText
            );
          },
        },
      ],
      page1: 1,
      pagesize1: 10,
      nowversion: 0,
      tableColumns1: [
        {
          type: "sort",
          title: this.$t("1008"),
          render: (h, params) => {
            return h(
              "span",
              params.index + (this.page1 - 1) * this.pagesize1 + 1
            );
          },
          width: "80px",
        },
        {
          title: this.$t(920193),
          width: 100,
          key: "version",
        },
        {
          title: this.$t(920194),
          width: 150,
          key: "datetime",
        },
        {
          title: this.$t(700135),
          key: "creator_name",
        },
        {
          title: this.$t(950473),
          key: "is_valid",
          render: (h, params) => {
            return h("div", [
              h(
                "RadioGroup",
                {
                  props: {
                    value: params.row.is_valid,
                  },
                  nativeOn: {
                    click: (e) => {
                      this.tableData1.forEach((item, index) => {
                        item.is_valid = 0;
                      });
                      params.row.is_valid = 1;
                      this.tableData1[params.index].is_valid = 1;
                      this.nowversion = params.index;
                    },
                  },
                },
                [
                  h(
                    "Radio",
                    {
                      props: {
                        label: 1,
                      },
                    },
                    "Radio1"
                  ),
                ]
              ),
            ]);
          },
        },
        {
          title: this.$t(1038),
          width: 100,
          render: (h, params) => {
            let statusText;
            statusText = this.$t(90000066);
            return h("Button", {
              class: ["ivu-btn-primary"],
              domProps: {
                innerHTML: statusText,
                back: "button",
              },
              style: {
                cursor: "pointer",
              },
              on: {
                click: () => {
                  this.showView(
                    this.detailobj.id,
                    params.row.id,
                    params.row.file_url
                  );
                },
              },
            });
          },
        },
        {
          title: this.$t(930131), // 版本名称
          key: "version_name",
          width: 200,
          render: (h, params) => {
            let vm = this;
            return h("input", {
              style: {
                width: "150px",
              },
              domProps: {
                value: params.row.version_name,
                disabled: params.row.is_valid === 1 ? false : true,
              },
              on: {
                input: function (event) {
                  params.row.version_name = event.target.value;
                  vm.tableData1[params.index] = params.row;
                },
              },
            });
          },
        },
      ],
    };
  },
  mounted() {
    this.Search(); // 获取表格数据
    this.GetAllDocumentSets(); // 获取文档类型数据
    this.GetProducts(); // 获取关联产品列表数据
    this.ListNCMachines(); // 获取关联设备列表数据
    this.getUserDepartment(); // 获取使用部门列表数据
    this.tableColumns1 = this.$time.initTableTitle(this.tableColumns1);
    this.tableColumns2 = this.$time.initTableTitle(this.tableColumns2);
  },
  methods: {
    // 初始化搜索时间
    initTime() {
      const _this = this;
      let date = new Date();
      let start = _this.$time.timestampToTime(
        date.getTime() - 7 * 24 * 60 * 60 * 1000
      );
      let end = _this.$time.timestampToTime(
        date.getTime() + 1 * 24 * 60 * 60 * 1000
      );
      _this.dateTime = [start, end];
    },
    // 监听搜索时间变化
    selectDate(v) {
      this.dateTime = [v[0], v[1]];
    },
    Search() {
      this.page = 1;
      this.pagesize = 10;
      this.tableSearch();
    },
    // 监听搜索事件
    tableSearch() {
      this.detailobj = {};
      // 组装请求参数
      var params = {
        page: this.page,
        pagesize: this.pagesize,
        status: this.status,
        type: this.docuType,
        keyword: this.keyword,
        starttime: this.dateTime[0],
        endtime: this.dateTime[1],
      };
      this.axios
        .request({
          url: "/esop/EsopDocumentCreate/GetDocumentPagedList",
          params,
          methods: "get",
        })
        .then((res) => {
          this.total = 0; //  设定一个初始值
          this.tableData = []; //  设定一个初始值
          if (res.data.ret == 1) {
            this.total = res.data.total;
            this.tableData = res.data.data;
          } else {
            this.$Message.error(this.$t("" + res.data.msg));
          }
        });
    },
    // 初始化搜索时间
    initTime() {
      let date = new Date();
      let start = this.$time.timestampToTime(
        date.getTime() - 7 * 24 * 60 * 60 * 1000
      );
      let end = this.$time.timestampToTime(date.getTime());
      this.dateTime = [start, end];
    },
    // 监听搜索时间变化
    selectDate(v) {
      this.dateTime = [v[0], v[1]];
    },
    // 监听添加按钮
    add() {
      this.type = 1; // 设置 type 为 1 表示是添加操作
      this.showModal = true;
      this.uploadtitle = "请选择上传文件";
      this.addflag = true;
      this.pdf_name = ""; // 清空文档路径
      this.addobj = {
        documentName: "", // 文档名称
        documentType: "", // 文档类型
        relatedProduct: "", // 关联产品
        relatedEquipment: "", // 关联设备
        useDepartment: "", // 使用部门
        note: "", // 备注
        showStatus: 0, // 展示状态
      };
    },
    // 修改事件
    edit() {
      if (
        this.detailobj.id == "" ||
        this.detailobj.id == null ||
        this.detailobj.id == undefined
      ) {
        this.$Message.error(this.$t(1043));
        return false;
      }
      this.showModal = true; // 弹出框显示
      this.type = 2; // type 为 2 表示修改
      this.addobj.documentName = this.detailobj.name; // 文档名称
      this.addobj.documentType = this.detailobj.type_id; // 文档类型
      this.file_url = this.detailobj.file_url;
      this.image_name = this.detailobj.file_name;
      this.pdf_name = this.detailobj.file_url;
      this.uploadtitle = this.detailobj.file_name; // 选择文件
      this.addobj.relatedProduct = this.detailobj.product_id; // 关联产品
      this.addobj.relatedEquipment = this.detailobj.machine_id; // 关联设备
      this.addobj.useDepartment = this.detailobj.section_id; // 使用部门
      this.addobj.note = this.detailobj.remark; // 备注
      this.addobj.showStatus = this.detailobj.default_display; // 展示与否
      //  组装请求参数
      let params = {
        document_id: this.detailobj.id,
        type_id: this.detailobj.type_id,
      };
      this.axios
        .request({
          url: "/esop/EsopProcess/GetProcessFlow",
          params,
          method: "get",
        })
        .then((res) => {
          this.auditeditflag = false;
          this.auditeditList = [];
          if (res.data.ret === 1 && res.data.data.length !== 0) {
            // 如果返回的数据不为空, 就需要隐藏. 如果返回值为空， 就需要显示
            this.auditeditflag = false;
            this.auditeditList = res.data.data;
          } else {
            this.auditeditflag = true; // 显示
          }
        });
    },
    // 弹框确定事件
    saveData(type) {
      let obj = this.addobj;
      // 必填项表单验证
      if (!obj.documentName) {
        this.$Message.error(this.$t(100407));
        return false;
      } else if (!obj.documentType) {
        this.$Message.error(this.$t(100408));
        return false;
      } else if (this.pdf_name === "") {
        this.$Message.error(this.$t(100409));
        return false;
      }
      // type 为 1 添加 type 为 2 修改
      if (type == 1) {
        // 组装请求参数
        let data = {
          id: this.detailobj.id,
          file_name: this.image_name, // 文件名称
          file_url: this.pdf_name, // 文件路径  this.axios.publicPath +
          name: obj.documentName, // 文件名称
          type_id: obj.documentType, // 文件类型
          product_id: obj.relatedProduct !== "" ? obj.relatedProduct : 0, // 关联产品
          machine_id: obj.relatedEquipment !== "" ? obj.relatedEquipment : 0, // 关联设备
          section_id: obj.useDepartment !== "" ? obj.useDepartment : 0, // 使用部门
          remark: obj.note, // 备注
          default_display: obj.showStatus == 0 ? 0 : obj.showStatus,
        };
        this.axios
          .request({
            url: "/esop/EsopDocumentCreate/AddDocument",
            data,
            method: "post",
          })
          .then((res) => {
            let result = res.data;
            if (result.ret == 1) {
              this.showModal = false; // 隐藏
              this.$Message.success(this.$t("1055")); // 提示
              this.Search();
            } else {
              this.$Message.error(this.$t("" + result.msg)); // 提示
            }
          });
      } else if (type == 2) {
        // 组装请求参数
        let data = {
          id: this.detailobj.id,
          file_name: this.image_name, // 文件名称
          file_url: this.pdf_name, // 文件路径  this.axios.publicPath +
          name: obj.documentName, // 文件名称
          type_id: obj.documentType, // 文件类型
          product_id: obj.relatedProduct !== "" ? obj.relatedProduct : 0, // 关联产品
          machine_id: obj.relatedEquipment !== "" ? obj.relatedEquipment : 0, // 关联设备
          section_id: obj.useDepartment !== "" ? obj.useDepartment : 0, // 使用部门
          remark: obj.note, // 备注
          default_display:
            obj.showStatus == obj.showStatus ? obj.showStatus : 0,
        };
        this.axios
          .request({
            url: "/esop/EsopDocumentCreate/UpdateDocument",
            data,
            method: "post",
          })
          .then((res) => {
            let result = res.data;
            if (result.ret == 1) {
              this.showModal = false; // 隐藏
              this.$Message.success(this.$t("1060")); // 提示
              this.tableSearch();
            } else {
              this.$Message.error(this.$t("" + result.msg)); // 提示
            }
          });
      }
    },
    // 监听撤回事件
    del() {
      if (
        this.detailobj === undefined ||
        this.detailobj.id === undefined ||
        this.detailobj.id === 0
      ) {
        this.$Message.error(this.$t("1043"));
        return false;
      } else {
        this.$Modal.confirm({
          title: this.$t("1223"),
          content: "",
          width: "290px",
          closable: true,
          okText: this.$t("1222"),
          onOk: () => {
            let params = { id: this.detailobj.id };
            axios
              .request({
                url: "/esop/EsopDocumentCreate/RecallDocument",
                params,
                method: "post",
              })
              .then((res) => {
                if (res.data.ret === 1) {
                  this.$Message.success(this.$t("1224"));
                  this.tableSearch();
                } else {
                  this.$Message.error(this.$t(res.data.msg));
                  this.tableSearch();
                }
              });
          },
        });
      }
    },
    // 监听预览事件
    preview() {
      if (!this.detailobj.id) {
        this.$Message.error(this.$t("1043"));
        return false;
      }
      this.showView(this.detailobj.id, 0, this.detailobj.file_url);
    },
    // 预览事件
    showView(id, versionid, file_url) {
      this.showpdf = false;
      this.showcontent = false;
      let url = axios.publicPath + file_url;
      // 判断url的值
      if (url != undefined && url != "undefined" && url != "") {
        //判断文档过类型
        let arr = url.split(".");
        if (arr.length > 1) {
          let type = arr[arr.length - 1];
          if (
            type == "txt" ||
            type == "pdf" ||
            type == "jpg" ||
            type == "png"
          ) {
            if (type == "jpg" || type == "png") {
              let html =
                '<img style="width:100%;height:100%;" src="' + url + '">';
              this.$refs.preview_content.innerHTML = html;
              this.showcontent = true;
              this.showmodal = true;
            } else if (type == "txt") {
              var params = {
                id: id,
                history_id: versionid,
              };
              axios
                .request({
                  url: "/esop/Download/PreviewFile",
                  params,
                  method: "get",
                })
                .then((res) => {
                  if (res.data.ret === 1) {
                    // var str = 'asfdasdfasdfasfd\nadfasdfasdfasdfad\nasdfasdfasdfasdf\n'
                    var str = res.data.data;
                    var str_o = str.replace(/<br>/g, "\n");
                    var str_t = str_o.replace(/</g, "&lt;");
                    var str_f = str_t.replace(/>/g, "&gt;");
                    var str_s = str_f.replace(/\n/g, "<br/>");
                    this.$refs.preview_content.innerHTML = str_s;
                    this.showcontent = true;
                    this.showmodal = true;
                  } else {
                    this.$Message.error(this.$t(res.data.msg));
                  }
                });
            } else if (type == "pdf") {
              this.showpdf = true;
              this.pdfurl = url;
              this.showmodal = true;
            }
          } else {
            this.$Message.error(this.$t("400073"));
            return false;
          }
        } else {
          this.$Message.error(this.$t("400072"));
          return false;
        }
      } else {
        this.$Message.error(this.$t("400071"));
        return false;
      }
    },
    // 监听版本更新事件
    Update() {
      if (
        this.detailobj === undefined ||
        this.detailobj.id === undefined ||
        this.detailobj.id === 0
      ) {
        this.$Message.warning(this.$t("1043"));
        return false;
      }
      this.updateModal = true; // 弹框显示
      this.updateobj.documentName = this.detailobj.name; // 文档名称
      this.updateobj.documentType = this.detailobj.type_id; // 文档类型
      this.uploadtitle = this.detailobj.file_name; // 选择文件
      this.file_image_name = this.detailobj.file_name;
      this.file_pdf_name = this.detailobj.file_url;
      this.updateobj.relatedProduct = this.detailobj.product_id; // 关联产品
      this.updateobj.relatedEquipment = this.detailobj.machine_id; //  关联设备
      this.updateobj.useDepartment = this.detailobj.section_id; //  使用部门
      this.updateobj.note = this.detailobj.remark; //  备注
      // 组装请求参数
      let params = {
        document_id: this.detailobj.id,
        type_id: this.detailobj.type_id,
      };
      axios
        .request({
          url: "/esop/EsopProcess/GetProcessFlow",
          params,
          method: "get",
        })
        .then((res) => {
          this.updateflag = false;
          this.updateList = [];
          if (res.data.ret === 1 && res.data.data.length !== 0) {
            // 如果返回的有数据, 则隐藏。如果返回没有数据,  则显示出来
            this.updateflag = false; //  隐藏
            this.updateList = res.data.data; // 赋值
          } else {
            this.updateflag = true; // 显示
          }
        });
    },
    // 版本更新弹框确认事件
    confirmBtn() {
      if (
        this.file_url === "" &&
        this.file_url === undefined &&
        this.file_url === 0
      ) {
        this.$Message.warning("请上传新文档"); // 提示
        return false;
      }
      let data = {
        file_name: this.file_image_name,
        file_url: this.file_pdf_name,
        id: this.detailobj.id,
      };
      axios
        .request({
          url: "/esop/EsopDocumentCreate/UpdateVersion",
          data,
          method: "post",
        })
        .then((res) => {
          if (res.data.ret == 1) {
            this.updateModal = false; // 隐藏
            this.$Message.success("版本更新成功！"); // 提示
            this.tableSearch(); // 刷新
            this.file_url = ""; // 清空
          } else {
            this.updateModal = false; // 隐藏
            this.$Message.error(res.data.msg); // 提示
          }
        });
    },
    // 监听版本管理事件
    Manage() {
      if (
        this.detailobj === undefined ||
        this.detailobj.id === undefined ||
        this.detailobj.id === 0
      ) {
        this.$Message.warning(this.$t("1043"));
        return false;
      }
      this.manageModal = true; // 显示
      let params = { document_id: this.detailobj.id };
      axios
        .request({
          url: "/esop/EsopDocumentCreate/GetAllVersion",
          params,
          method: "get",
        })
        .then((res) => {
          this.tableData1 = [];
          if (res.data.ret === 1 && res.data.data.length !== 0) {
            this.tableData1 = res.data.data;
          } else {
            this.$Message.error(this.$t("" + result.msg));
          }
        });
    },
    // 监听下载附件事件
    Download() {
      if (!this.detailobj.id) {
        this.$Message.warning(this.$t("1043"));
        return false;
      }
      var url =
        axios.publicPath + "esop/Download/DownloadFile?id=" + this.detailobj.id;
      var file_name = this.detailobj.file_name;
      var xhr = new XMLHttpRequest();
      xhr.open("GET", url, true);
      xhr.setRequestHeader("token", localStorage.getItem("token"));
      xhr.setRequestHeader("timestamp", localStorage.getItem("timestamp"));
      xhr.setRequestHeader("sign", localStorage.getItem("sign"));
      xhr.setRequestHeader("nonce", localStorage.getItem("nonce"));
      xhr.responseType = "blob";
      xhr.onload = function () {
        if (this.status === 200) {
          var blob = this.response;
          var a = document.createElement("a");
          a.download = file_name;
          a.href = window.URL.createObjectURL(blob);
          a.click();
        } else {
          this.$Message.error("下载失败");
        }
      };
      xhr.send();
    },
    // 弹框关联设备数据列表
    GetProducts() {
      axios
        .request({
          url: "/config/projectproduct/GetProducts",
          method: "get",
        })
        .then((res) => {
          if (res.data.ret == 1 && res.data.data.length !== 0) {
            this.relatedProductList = res.data.data;
          } else {
            this.relatedProductList = [];
          }
        });
    },
    // 弹框关联设备数据列表
    ListNCMachines() {
      axios
        .request({
          url: "/config/Machine/ListNCMachines",
          method: "get",
        })
        .then((res) => {
          if (res.data.ret == 1 && res.data.data.length !== 0) {
            this.ListNCMachinesList = res.data.data;
          } else {
            this.ListNCMachinesList = [];
          }
        });
    },
    // 弹框使用部门数据列表
    getUserDepartment() {
      axios
        .request({
          url: "/config/ProjectUser/getUserDepartment",
          method: "get",
        })
        .then((res) => {
          let result = res.data.data;
          if (
            res.data.ret == 1 &&
            result &&
            Array.isArray(result) &&
            result.length
          ) {
            this.UserDepartmentList = result;
          } else {
            this.UserDepartmentList = [];
          }
        });
    },
    // 审核弹框-文档类型
    GetAllDocumentSets() {
      axios
        .request({
          url: "/esop/EsopDocumentSet/GetAllDocumentSets",
          method: "get",
        })
        .then((res) => {
          let result = res.data.data;
          if (
            res.data.ret === 1 &&
            result &&
            Array.isArray(result) &&
            result.length
          ) {
            this.docuTypeList = result;
          } else {
            this.docuTypeList = [];
          }
        });
    },
    //  文件格式验证失败时的钩子，返回字段为 file, fileList
    handleFormatError(file) {
      this.$Message.error(this.$t("950396") + file.name + this.$t("950397"));
    },
    //  文件上传成功时钩子函数
    handleSuccess(res, file) {
      if (res.ret == 1) {
        this.$Message.success(this.$t("100378"));
        this.image_name = file.name;
        this.pdf_name = file.response.data; // 有值
        this.uploadtitle = file.name;
      } else {
        this.$Message.error(this.$t(res.msg));
      }
    },
    // 文件上传失败时的钩子
    handleError() {
      this.$Message.error(this.$t("2010006") + "!");
    },
    // 版本更新弹框(文件上传成功时钩子函数)
    handleUpdateSuccess(res, file) {
      if (res.ret == 1) {
        this.$Message.success(this.$t("100378"));
        this.file_image_name = file.name;
        this.file_pdf_name = file.response.data;
        this.uploadtitle = file.name;
      } else {
        this.$Message.error(this.$t(res.msg));
      }
    },
    // 版本更新弹框(文件上传失败时的钩子)
    handleUpdateError() {
      this.$Message.error(this.$t("9000123") + "!");
    },
    confirmBtn3() {
      //组装请求参数
      let data = {
        document_id: this.detailobj.id,
        history_id: parseInt(this.tableData1[this.nowversion].id),
        version_name: this.tableData1[this.nowversion].version_name,
      };
      axios
        .request({
          url: "/esop/EsopDocumentCreate/UpdateValidVersion",
          data,
          method: "post",
        })
        .then((res) => {
          if (res.data.ret === 1) {
            this.Search();
            this.manageModal = false;
            this.$Message.success(this.$t("400074"));
          } else {
            this.$Message.error(this.$t(res.data.msg));
          }
        });
    },
    // 在文档类型下拉列表中选定一个类型
    documentTypeChange(v) {
      if (!v) {
        //  非空就暂停
        return false;
      }
      // 调用接口事件
      var params = {
        type_id: v,
      };
      axios
        .request({
          url: "/esop/EsopProcess/GetProcessFlow",
          params,
          method: "get",
        })
        .then((res) => {
          if (res.data.ret === 1) {
            this.auditList = [];
            this.addflag = true;
            if (Array.isArray(res.data.data) && res.data.data.length) {
              this.auditList = res.data.data;
              this.addflag = false;
            }
          } else {
            this.$Message.error(this.$t(res.data.msg));
          }
        });
    },
    // 首页表格的当前行发生变化的时候会触发
    handleRowChange(currentRow, oldCurrentRow) {
      this.detailobj = currentRow;
    },
    // 版本管理弹框表格发生变化触发
    handleManageRowChange(currentRow, oldCurrentRow) {
      this.manageobj = currentRow;
    },
    changePage(value) {
      this.page = value;
      this.tableSearch();
    },
    handlePageSize(value) {
      this.pagesize = value;
      this.tableSearch();
    },
  },
};
</script>

<style lang="less" scoped>
.selectBtn {
  width: 140px;
}
.Main > div {
  margin-bottom: 20px;
}
.updateAudit {
  float: right;
  margin-right: 130px;
  margin-top: -350px;
  .auditLable {
    font-weight: bold;
    font-size: 14px;
    padding-bottom: 15px;
    padding-right: 28px;
  }
}
.addAudit {
  float: right;
  margin-right: 120px;
  margin-top: -350px;
  .auditLable {
    font-weight: bold;
    font-size: 14px;
    padding-bottom: 15px;
    padding-right: 28px;
  }
}
.time {
  font-size: 14px;
}
.content {
  padding-right: -15px;
}
.manageTable {
  margin-right: 40px;
}
.preview_content {
  overflow-y: scroll;
  overflow-x: hidden;
  min-height: 300px;
  max-height: 500px;
}
</style>
