<script>
import materialApi from "@/api/material/basic";
import { SearchColumnsExtend, OtherDictColumns } from "./columns";
import { initDicts } from "@/utils/init.js";
export default {
  name: "material-basic",
  dicts: [...initDicts([...SearchColumnsExtend, ...OtherDictColumns])],
  components: {
    ElSuperSearch: () => import("@/components/super-search/index.vue"),
    ElDictTag: () => import("@/components/DictTag/index.vue"),
    IsUsing: () => import("./isUsing/index.vue"),
    detailDrawer: () => import("./details.vue"),
    whlbButton: () => import("./wei-hu-lei-bie/index.vue"),
    BatchImport: () => import("@/components/BatchImport/index.vue"),
  },
  props: {
    parentData: String
  },
  watch: {
    parentData(newValue, oldValue) {
      // 当parentData变化时，这个函数会被调用
      if(newValue != ''){
        this.$set(this.params,'classifys',[newValue])
        this.useList()
      }
    }
  },
  data() {
    const params = this.$init.params(SearchColumnsExtend);
    const page = this.$init.page();
    return {
      loading: false,
      params: params,
      SearchColumnsExtend: SearchColumnsExtend,
      rowKey: "id",
      size: "mini",
      page: page,
      taskList: [],
      checkedList: [],
      resizeHeight: 0,
      tableHeader: [],
    };
  },
  computed: {
    tableHeight: {
      get() {
        return this.resizeHeight;
      },
      set() {},
    },
  },
  directives: {
    // 使用局部注册指令的方式
    resize: {
      // 指令的名称
      bind(el, binding) {
        // el为绑定的元素，binding为绑定给指令的对象
        let width = "",
          height = "";
        function isReize() {
          const style = document.defaultView.getComputedStyle(el);
          if (width !== style.width || height !== style.height) {
            binding.value(); // 关键
          }
          width = style.width;
          height = style.height;
        }
        el.__vueSetInterval__ = setInterval(isReize, 300);
      },
      unbind(el) {
        clearInterval(el.__vueSetInterval__);
      },
    },
  },
  methods: {
    resize() {
      this.resizeHeight =
        document.getElementsByClassName("el-super-ux-table")[0].offsetHeight -
        55;
    },
    // 列表
    async useList() {
      try {
        this.loading = true;

        this.checkedList = [];

        let param = {
          templateCode: "material",
          ...this.params,
          createTimeBegin:
            (this.params.createTimeQueue && this.params.createTimeQueue[0]) ||
            "",
          createTimeEnd:
            (this.params.createTimeQueue && this.params.createTimeQueue[1]) ||
            "",
          updateTimeBegin:
            (this.params.updateTimeQueue && this.params.updateTimeQueue[0]) ||
            "",
          updateTimeEnd:
            (this.params.updateTimeQueue && this.params.updateTimeQueue[1]) ||
            "",
        };

        let {
          code,
          data: {
            tableBody: { rows, total },
          },
        } = await materialApi.materialList(param, this.page);

        if (code == 200) {
          this.taskList = rows;
          this.page.total = total;
        }
      } catch (error) {
      } finally {
        this.loading = false;
      }
    },
    // 获取物料列表表头
    async getTagList(templateCode) {
      try {
        let { code, data } = await materialApi.tagList({ templateCode });
        if (code == 200) {
          this.tableHeader = data;
        }
      } catch (error) {}
    },
    // 重置
    useReset() {
      this.params = this.$init.params(SearchColumnsExtend);
      this.page = this.$init.page();
      this.useList();
    },
    handleEdit() {
      let { setVisible } = this.$refs.detailDrawer;
      setVisible(true);
      // this.$router.push({
      //   path: `/material/basicFile/detail/${this.checkedList[0].id}`,
      //   query: {
      //     isEdit: true,
      //   },
      // });
    },
    // 确认导入
    handelImport(fileList) {
      let formData = new FormData();

      formData.append("file", fileList[0].raw);
      materialApi.fileImport(formData).then((res) => {
        if (res.code == 200) {
          if (res.data.flag) {
            this.$modal.loading("加载中...");
            console.log(res.data.datas);
            let param = { failDatas: res.data.datas };
            if (null != param) {
              materialApi.exportMartial(param).then((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 = "导入失败的物料基础档案数据.xlsx"; // 下载后文件名
                document.body.appendChild(downloadElement);
                downloadElement.click(); // 点击下载
                document.body.removeChild(downloadElement); // 下载完成移除元素
                window.URL.revokeObjectURL(href); // 释放blob对象
                this.$modal.closeLoading();
                let { setVisible } = this.$refs.batchImport;
                setVisible(false);
              });
            }
          }
          this.$notify({
            message: res.data.msg,
            type: res.data.flag ? "warning" : "success",
          });
        } else {
          this.$notify({
            message: res.msg,
            type: res.code == 200 ? "success" : "warning",
          });
        }
      });
    },
    // 模板下载
    handleTemDownload() {
      this.download("/system/material/download", {}, `物料基本信息模板.xlsx`);
    },
    // 批量导出
    useExport() {
      let ids = this.checkedList.length
        ? this.checkedList.map((i) => i.id)
        : [];

      if (ids.length) {
        let params = {
          // orgId: '1',
          ids,
        };
        this.download(
          "/system/material/export",
          params,
          `物料基本信息${new Date().getTime()}.xlsx`
        );
      } else {
        let params = {
          templateCode: "material",
          ...this.params,
          createTimeBegin:
            (this.params.createTimeQueue && this.params.createTimeQueue[0]) ||
            "",
          createTimeEnd:
            (this.params.createTimeQueue && this.params.createTimeQueue[1]) ||
            "",
          updateTimeBegin:
            (this.params.updateTimeQueue && this.params.updateTimeQueue[0]) ||
            "",
          updateTimeEnd:
            (this.params.updateTimeQueue && this.params.updateTimeQueue[1]) ||
            "",
        };
        this.download(
          "/system/material/export",
          params,
          `物料基本信息${new Date().getTime()}.xlsx`
        );
      }
    },
    useDbClick(e) {
      // console.log("A:::" + JSON.stringify(e))
      // this.checkedList = [{ ...e }];
      // let { setVisible } = this.$refs.detailDrawer;
      // setVisible(true);
      this.$router.push({
        path: `/material/extend/detailMain?materialId=${e.id}`,
      });
    },
    // 行数据勾选操作
    handleSelect(selection, row) {
      this.checkedList = selection;
    },
    //手动勾选全选
    handleSelectAll(selection) {
      this.checkedList = selection;
    },
  },
  created() {
    this.getTagList("material_list");
    this.useList();
  },
};
</script>

<template>
  <el-card
    v-loading="loading"
    :body-style="{
      height: '100%',
      padding: 0,
      display: 'flex',
      'flex-direction': 'column',
    }"
  >
    <!-- 查询条件 -->
    <el-super-search
      v-model="params"
      :size="size"
      :dict="dict"
      :columns="SearchColumnsExtend"
      @reset="useReset"
      @submit="useList"
    ></el-super-search>


    <div
      class="el-super-ux-table"
      v-resize="resize"
      style="
        position: relative;
        display: flex;
        flex: 1;
        flex-direction: column;
        overflow: auto;
      "
    >
      <ux-grid
        v-if="tableHeader.length"
        border
        use-virtual
        keep-source
        beautify-table
        :size="size"
        :data="taskList"
        :height="tableHeight"
        ref="materialTable"
        @cell-dblclick="useDbClick"
        @select="handleSelect"
        @select-all="handleSelectAll"
        :header-row-style="{
          color: '#515a6e',
        }"
        style="flex: 1"
      >
        <
        <!-- 多选 -->
        <ux-table-column
          fixed="left"
          width="60"
          align="center"
          type="checkbox"
          resizable
          reserve-selection
          :column-key="rowKey"
        ></ux-table-column>
        <!-- 序号 -->
        <ux-table-column
          fixed="left"
          width="50"
          title="序号"
          type="index"
          align="center"
          class="is-index"
          resizable
        ></ux-table-column>
        <ux-table-column
          width="150"
          v-for="h in tableHeader"
          v-if="h.show"
          :title="h.name"
          align="center"
          resizable
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span v-if="h.apiUrl">{{ scope.row[`${h.prop}Name`] }}</span>
            <el-checkbox
              v-else-if="h.attribute == 'checkbox'"
              v-model="scope.row[h.prop]"
              disabled
              :size="size"
              true-label="0"
              false-label="2"
            ></el-checkbox>
            <el-dict-tag
              v-else-if="h.dictId"
              :size="size"
              :value="scope.row[h.prop]"
              :options="dict.type[h.dictId]"
            ></el-dict-tag>

            <!-- <span v-else>{{ scope.row[h.prop] || "--" }}</span> -->
            <span v-else>{{ scope.row[h.prop] }}</span>
          </template>
        </ux-table-column>
      </ux-grid>
      <div
        style="
          height: 50px;
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
        :style="{
          height: '50px',
        }"
      >
        <pagination
          :total="page.total"
          :page.sync="page.pageNum"
          :limit.sync="page.pageSize"
          @pagination="useList"
          style="height: 32px; padding: 0 !important; flex: 1; overflow-x: auto"
        />
      </div>
    </div>

    <detailDrawer
      ref="detailDrawer"
      :select-data.sync="checkedList"
      @success="useList"
    ></detailDrawer>
  </el-card>
</template>
<style scoped lang="scss">
.el-card {
  width: calc(100% - 32px);
  height: calc(100vh - 32px);
  border-radius: 8px;
}
</style>
