<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      v-model:page="page"
      v-model="form"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @row-del="rowDel"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template #menu-left>
        <el-button type="primary" @click="handleAdd">新增</el-button>
        <el-button type="danger" @click="handleDeletes">删除</el-button>
        <el-button type="warning" @click="handleExport" >导出</el-button>
      </template>
      <template #menu-right>
        <el-button type="primary" @click="handleImport">导入</el-button>
      </template>
      <template #menu="scope">
        <el-button type="text" @click="handleView(scope.row)">详情</el-button>
        <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
        <el-button type="text" @click="handleDel(scope.row)">删除</el-button>
      </template>
      <template #originalName="{ row }">
        <span style="color:#284c89;cursor:pointer;" @click="downloadA(row.link,row.originalName)">{{row.originalName}}</span>
        <!-- <a  :href="row.link" :download="row.originalName">{{row.originalName}}</a> -->
      </template>
    </avue-crud>

    <!-- 新增 、编辑、删除 -->
    <addTestProjectDialog
      v-if="addOpen"
      :showDialog="addOpen"
      @closeDialog="closeDialog"
      :title="title"
      :projectId="projectId"
    ></addTestProjectDialog>

    <!-- 导入 -->
    <basic-import v-if="isShowImport" title="导入" :isShow="isShowImport"
      templateUrl="/blade-desk/QA/CycleTestItem/download-excel-template"
      templateName="试验项目模板.xls"
      importUrl="/blade-desk/QA/CycleTestItem/import-excel"
     @closeDialog="closeDialog"></basic-import>
  </basic-container>
</template>

<script>
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { downloadXls } from '@/utils/util';
import addTestProjectDialog from './components/addTestProjectDialog.vue';

import { getList, remove,exportExcel} from '@/api/qualityManagement/periodicTesting/testProject.js';

import basicImport from '@/components/basic-import/main.vue'
export default {
  components: {
    addTestProjectDialog,
    basicImport
  },
  data() {
    return {
      loading: false,
      data: [],
      projectForm: {},
      projectRules: {
        tpProject: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
        testPieceTitle: [{ required: true, message: '请选择试验件', trigger: 'blur' }],
        tpStandard: [{ required: true, message: '请输入执行标准', trigger: 'blur' }],
        craftMan: [{ required: true, message: '请选择主管工艺', trigger: 'blur' }],
        mecMan: [{ required: true, message: '请选择试验员', trigger: 'blur' }],
        remDays: [{ required: true, message: '请选择超期提醒', trigger: 'blur' }],
        textCycle: [{ required: true, message: '请选择试验周期', trigger: 'blur' }],
      },
      form: {},
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      isShowImport:false,
      monthTags: [],
      yearTags: [],
      option: {
        tip: false,
        height: 'auto',
        calcHeight: 32,
        columnSort: true,
        searchShow: true,
        searchMenuSpan: 18,
        searchIcon: true,
        searchIndex: 3,
        tree: false,
        border: true,
        index: false,
        selection: true,
        viewBtn: false,
        delBtn: false,
        addBtn: false,
        editBtn: false,
        editBtnText: '修改',
        viewBtnText: '详情',
        addBtnIcon: ' ',
        viewBtnIcon: ' ',
        delBtnIcon: ' ',
        editBtnIcon: ' ',
        labelWidth: 120,
        dialogWidth: 600,
        dialogClickModal: false,
        searchEnter: true,
        filterBtn: false,
        searchShowBtn: false,
        excelBtn: false,
        showOverflowTooltip: true,
        align: 'center',
        searchLabelPosition: 'left',
        searchGutter: 24,
        searchSpan: 6,
        menuAlign: 'left',
        menuWidth:150,
        gridBtn: false,
        searchMenuPosition: 'right',
        column: [
          {
            label: '试验项目',
            prop: 'name',
            search: true,
            sortable: true,
          },
          {
            label: '试验条件',
            prop: 'condition',
            search: false,
            sortable: true,
          },
          {
            label: '执行标准',
            prop: 'cycleTestStandardName',
            search: false,
            sortable: true,
          },
          {
            label: '试验文件',
            prop: 'originalName',
            search: false,
            sortable: true,
          },
        ],
      },
      addOpen: false,
      title: '新增',
    };
  },
  mounted() {},
  methods: {
    closeDialog() {
      this.addOpen = false;
      this.isShowImport = false
      this.refreshChange()
    },
    // 点击详情按钮
    handleView(row) {
      this.projectId = row.id;
      this.title = '详情';
      this.addOpen = true;
    },
    // 点击编辑按钮
    handleEdit(row) {
      this.projectId = row.id;
      this.title = '编辑';
      this.addOpen = true;
    },
    handleDel(row){
        this.$confirm('确定删除所选数据?', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
    },

    downloadA(fileUrl, fileName){
            const xhr = new XMLHttpRequest();
            xhr.open('GET', fileUrl, true);
            xhr.responseType = 'blob';
            
            xhr.onload = function () {
                if (xhr.status === 200) {
                const res = xhr.response;
                const link = document.createElement('a');
                link.style.display = 'none';
                const url = window.URL.createObjectURL(res);
                link.href = url;
                link.setAttribute('download', fileName);
                document.body.appendChild(link);
                link.click();
                window.URL.revokeObjectURL(link.href);
                document.body.removeChild(link);
                } else {
                console.error('下载失败:', xhr.status);
                ElMessage.error('下载失败，请稍后重试');
                }
            };
            
            xhr.onerror = function() {
                console.error('下载请求出错');
                ElMessage.error('下载请求出错，请检查网络连接');
            };
            
            xhr.send();
        },

    // 点击上方删除按钮，多条删除
    handleDeletes() {
      if (this.selectionList.length == 0) {
        this.$message.error('请至少选择一条数据!');
      } else {
        this.$confirm('确定删除所选数据?', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          let ids = this.selectionList.map(item => item.id)
          return remove(ids.join(','));
        }).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
      }
    },
    // 导出
    handleExport(){
      this.$confirm('是否导出周期性试验项目数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        NProgress.start();
        exportExcel({...this.query}).then(res =>{
          downloadXls(res.data, `试验项目表${this.$dayjs().format('YYYY-MM-DD')}.xlsx`);
          NProgress.done();
        })
      })
    },
    // 点击导入按钮
    handleImport() {
      this.isShowImport = true
    },

    // 点击删除按钮
    rowDel(row) {
      this.$confirm('确定删除此条数据?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {});
    },
    // 点击新增按钮
    handleAdd() {
      this.title = '新增';
      this.addOpen = true;
    },
    // 多选
    selectionChange(list) {
      this.selectionList = list;
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;

      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        this.data = res.data.data.records;

        this.loading = false;
        this.page.total = res.data.data.total
        // this.selectionClear();
      });
    },
  },
};
</script>

<style></style>
