<template>
  <div id="orderInfoIndex">
    <div v-if="isList">
      <el-card v-loading="loading" style="position: relative;">
        <p>采购订单信息列表</p>
        <div class="btn_grooup">
          <el-button type="primary" size="mini" @click="downLoadMb">下载模板</el-button>
          <el-button type="primary" size="mini" @click="importMb">导入</el-button>
          <el-button type="primary" size="mini" @click="exportMb">导出</el-button>
          <el-button type="primary" size="mini" @click="addDivision">新增</el-button>
          <el-button type="primary" size="mini" @click="delItems">删除</el-button>
        </div>

        <el-super-ux-table
            id="data-table"
            v-model="tableData"
            index
            checkbox
            :size="size"
            :dict="dict"
            :page="pageInfo"
            :height=500
            :columns="TableColumns"
            pagination
            convenitentOperation
            storage-key="orderTable"
            @row-dblclick="useSee"
            @row-select="useSelect"
            @selection-change="handleSelectionChange"
            @row-click="rowSelect"
            @pagination="useQuery(params, pageInfo)"
            ref="tables"
          >
            <ux-table-column
              fixed="right"
              title="操作"
              align="center"
              width="100"
              >
              <template slot-scope="scope">
                <!-- <el-button type="text" size="mini" v-if="scope.row.status == '1' && scope.row.flowId" @click="reback(scope.row)">收回</el-button> -->
                <!-- <el-button type="text" size="mini" @click="check(scope.row)">查看</el-button> -->
                <el-button type="text" size="mini" @click="delItem(scope.row)">删除</el-button>
              </template>
            </ux-table-column>
        </el-super-ux-table>
      </el-card>
    </div>

    <!-- 用户导入对话框 -->
    <el-dialog title="数据导入" :visible.sync="upload.open" width="400px">
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :on-error="errorFile"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
      </el-upload>
      <div slot="footer">
        <el-button :size="size" type="primary" @click="submitFileForm"
          >确 定</el-button
        >
        <el-button :size="size" @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <Add v-model="isList" v-if="!isList" :pageStu="page" :disable="disable" :row="rowDetail" @refresh="searchList"/>
  </div>
</template>

<script>
import { orderList, delOrder, mbDownload, mbExport, errDownload } from '@/api/innerData/order.js'
// 导入的token
import { getToken } from "@/utils/auth";
export default {
  dicts: [],
  components: {
    Add: () => import("./addOrderInfo.vue"),
    ElSuperUxTable: () => import("@/components/super-ux-table/index.vue"),
  },
  data () {
    return {
      // 页面配置
      isList: true,
      // 页面状态
      page: '',
      disable: false,
      rowDetail: {},
      size: "mini",
      loading: false,
      params: {},
      pageInfo: {
        pageNum: 1,
        pageSize: 20,
        total: 0
      },
      tableData: [],
      selectData: [],
      // SearchColumns: SearchColumns,
      TableColumns: [
        { item: { key: "puOrgName", title: "采购组织" }, attr: {} },
        { item: { key: "billTypeName", title: "订单类型" }, attr: {} },
        { item: { key: "supplierName", title: "供应商" }, attr: {} },
        { item: { key: "orderCode", title: "订单编号" }, attr: {} },
        { item: { key: "taxPrice", title: "价税合计" }, attr: {} },
        { item: { key: "buyerName", title: "采购员" }, attr: {} },
        { item: { key: "materialName", title: "物料名称" }, attr: {} },
        { item: { key: "materialCode", title: "物料编码" }, attr: {} },
        { item: { key: "specification", title: "规格" }, attr: {} },
        { item: { key: "model", title: "型号" }, attr: {} },
        { item: { key: "manufacturerName", title: "生产厂家/代理人" }, attr: {} },
        { item: { key: "unitName", title: "单位" }, attr: {} },
        { item: { key: "qty", title: "数量" }, attr: {} },
        { item: { key: "money", title: "含税单价" }, attr: {} },
        { item: { key: "sipPrice", title: "内部价格" }, attr: {} },
        { item: { key: "sipSupplierName", title: "内部供应商" }, attr: {} },
      ].map(({ item, attr }) => ({
      attr,
      item: {
        ...item,
        sortabled: true,
        fixedabled: true,
        filterabled: true,
        hiddenabled: true,
      },
      })),
      ids: [],
      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "数据导入",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 1,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/sip/order/import",
      },
    }
  },
  created() {
    this.useQuery(this.params, this.pageInfo)
  },
  methods: {
    // 新增
    addDivision() {
      this.isList = false
      this.page = 'add'
      this.disable = false
    },
    delItems() {
      if (this.ids.length <= 0) {
        this.$modal.notifyWarning("至少勾选一条数据");
      } else {
        delOrder(this.ids).then(res => {
          if(res.code === 200) {
            this.$modal.notifySuccess("删除成功");
            this.useQuery(this.params, this.pageInfo)
          }
       })
      }
    },
    searchList() {
      this.useQuery(this.params, this.pageInfo)
    },
    useSee() {},
    useSelect() {},
    handleSelectionChange(selection) {
      console.log('选中', selection)
      this.ids = selection.map(item => item.id)
      console.log('选中数组', this.ids)
    },
    rowSelect(row) {
      this.$refs.tables.toggleRowSelection([{row: row}]);
    },
    // 加载列表
    async useQuery(prop, page) {
      let params = {...prop, ...page}
      await orderList(params).then(res => {
        if( res.code === 200 ) {
          this.tableData = res.rows
          this.pageInfo.total = res.total
        }
      })
    },
    delItem(row) {
      const param = [row.id]
      delOrder(param).then(res => {
        if(res.code === 200) {
          this.$modal.notifySuccess("删除成功");
          this.useQuery(this.params, this.pageInfo)
        }
      })
    },
    downLoadMb() {
      this.$modal.loading("正在下载模板，请稍后...");
      mbDownload().then((res) => {
          this.$modal.closeLoading();
          const blob = new Blob([res], {
            type: "application/vnd.ms-excel;charset=UTF-8",
          }); // 创建一个类文件对象：Blob对象表示一个不可变的、原始数据的类文件对象
          console.log('blob1', blob)
          const downloadElement = document.createElement("a"); //创建a标签
          const href = window.URL.createObjectURL(blob); // 创建下载的链接
          // var temp = res.headers["content-disposition"];
          // var fileName = decodeURIComponent(temp.split("filename=")[1]); // 中文需要转码 (前端乱码）
          // var name = fileName.split(";")[0]; //切割成文件名
          downloadElement.href = href; //下载地址
          downloadElement.download =
            "内部订单价格模板" + this.parseTime(new Date().getTime()) + ".xlsx"; // 下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); // 点击下载
          document.body.removeChild(downloadElement); // 下载完成移除元素
          window.URL.revokeObjectURL(href); // 释放blob对象
          this.download.open = false;
        })
        .catch((err) => {
          this.$modal.closeLoading();
        });
    },
    importMb() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
      this.$modal.loading("正在导入数据，请稍后...");
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.$modal.closeLoading();
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      // this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      if (response.data && response.data.length !== 0) {
        this.$modal.notifyError("导入失败，请检查格式是否正确");
        console.log(response.data)
        errDownload(response.data).then((res) => {
          this.$modal.closeLoading();
          const blob = new Blob([res], {
            type: "application/vnd.ms-excel;charset=UTF-8",
          }); // 创建一个类文件对象：Blob对象表示一个不可变的、原始数据的类文件对象
          const downloadElement = document.createElement("a"); //创建a标签
          const href = window.URL.createObjectURL(blob); // 创建下载的链接
          downloadElement.href = href; //下载地址
          downloadElement.download ="内部订单价格导入失败" + this.parseTime(new Date().getTime()) +".xlsx"; // 下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); // 点击下载
          document.body.removeChild(downloadElement); // 下载完成移除元素
          window.URL.revokeObjectURL(href); // 释放blob对象
        })
        .catch((err) => {
          this.$modal.closeLoading();
        });
      } else {
        this.$modal.notifySuccess("导入成功");
        this.useQuery(this.params, this.pageInfo);
      }
      console.log('结果',response)
    },
    errorFile(err) {
      this.$modal.closeLoading();
      this.$modal.notifyError("文件已变动，请重新上传");
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    exportMb() {
      mbExport().then((res) => {
          this.$modal.closeLoading();
          console.log(res)
          const blob = new Blob([res], {
            type: "application/vnd.ms-excel;charset=UTF-8",
          }); // 创建一个类文件对象：Blob对象表示一个不可变的、原始数据的类文件对象
          const downloadElement = document.createElement("a"); //创建a标签
          const href = window.URL.createObjectURL(blob); // 创建下载的链接
          downloadElement.href = href; //下载地址
          downloadElement.download ="内部订单价格导出" + this.parseTime(new Date().getTime()) +".xlsx"; // 下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); // 点击下载
          document.body.removeChild(downloadElement); // 下载完成移除元素
          window.URL.revokeObjectURL(href); // 释放blob对象
        })
        .catch((err) => {
          this.$modal.closeLoading();
        });
    },
  }
}
</script>

<style lang="scss" scoped>
#orderInfoIndex {
  padding: 12px;
  box-sizing: border-box;
  overflow-y: scroll;
}
.btn_grooup {
  margin-bottom: 10px;
  display: flex;
  justify-content: flex-end;
}
</style>