<template>
  <div>
    <ele-modal
      width="80vw"
      :visible="visibleDialog"
      :append-to-body="true"
      :close-on-click-modal="false"
      custom-class="ele-dialog-form"
      :title="`${title}信息`"
      :before-close="closeWindows"
      :maxable="true"
    >
      <div class="search_box">
        <el-row :gutter="15">
          <el-col :span="6">
            <el-form label-width="80px" class="ele-form-search">
              <el-form-item label="所属工厂" prop="factoryId">
                <el-select
                  @keyup.enter.native="handleSearch"
                  filterable
                  placeholder="请选择"
                  v-model="factoryId"
                  clearable
                  class="w100"
                >
                  <el-option
                    v-for="item in factoryList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="8">
            <el-input
              v-model="value"
              placeholder="搜索物品编码、名称、规格等"
              @keyup.enter.native="handleSearch"
            >
              <el-button
                slot="append"
                type="primary"
                icon="el-icon-search"
                size="small"
                @click="handleSearch"
                >搜索</el-button
              >
            </el-input>
          </el-col>
        </el-row>
      </div>
      <div class="flex_info">
        <div class="flex_left">
          <AssetTree
            ref="treeList"
            :treeIds="treeIds"
            @handleNodeClick="handleNodeClick"
          />
        </div>
        <div class="flex_right">
          <ele-pro-table
            ref="multipleTable"
            :columns="columns"
            :datasource="_getInformation"
            height="calc(100vh - 365px)"
            style="margin-bottom: 15px"
            full-height="calc(100vh - 116px)"
            tool-class="ele-toolbar-form"
            :selection.sync="selection"
            @columns-change="handleColumnChange"
            :cache-key="cacheKeyUrl"
            :page-size="20"
            row-key="id"
            :initLoad="false"
          ></ele-pro-table>
          <!-- <el-table ref="multipleTable" :data="tableData" border tooltip-effect="dark" height="455px"
            style="width: 100%" :header-cell-style="{ background: '#F0F3F3', border: 'none' }"
            @selection-change="handleSelectionChange">



            <el-table-column v-for="(item, index) in newColumns" :label="item.label" :align="item.align"
              :prop="item.prop" :show-overflow-tooltip="item.showOverflowTooltip"></el-table-column>
          </el-table>
          <div class="right mt10">
            <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="total"
              :page-sizes="[20, 30, 50, 100, 500]" :page-size.sync="pages.size" :current-page.sync="pages.pageNum"
              @current-change="handleCurrentChange" @size-change="handleSizeChange">
            </el-pagination>
          </div> -->
        </div>
      </div>
      <div class="select-btn">
        <el-button type="primary" @click="onConfirm">确定</el-button>
        <el-button @click="closeWindows">关闭</el-button>
      </div>
    </ele-modal>
  </div>
</template>

<script>
  import warehouseDefinition from '@/api/warehouseManagement/warehouseDefinition';
  import AssetTree from './assetTree.vue';
  import { getList } from '@/api/classifyManage/itemInformation';
  import storageApi from '@/api/warehouseManagement/index.js';
  import tabMixins from '@/mixins/tableColumnsMixin';

  export default {
    mixins: [tabMixins],

    props: {
      visibleDialog: {
        type: Boolean,
        default: false
      },
      title: {
        type: String,
        default: ''
      },
      bizScene: {
        type: String,
        default: ''
      },
      treeIds: {
        type: Array,
        default: () => []
      },
      loadTree: {
        type: Boolean,
        default: true
      },
      cacheKeyUrl: ''
    },
    watch: {
      // tableData(val) {
      //   this.doLayout();
      // },
      visibleDialog: {
        handler(v) {
          if (v) {
            this.getTreeList();
          }
        },
        deep: true
      }
    },
    components: { AssetTree },
    data() {
      return {
        factoryList: [],
        factoryId: '',
        value: '',
        treeType: '',
        treeList: [],
        tableData: [],
        selection: [],
        pages1: { classificationIdList: [] },
        pages: {
          pageNum: 1,
          size: 20
        },
        total: 0,
        curType: '',
        classificationId: '',
        // memoSelection: [],
        newColumns: [] // 动态表头
      };
    },
    created() {
      this.getFieldModel();
      this.getFactoryList();
    },
    computed: {
      columns() {
        return [
          {
            width: 45,
            type: 'selection',
            columnKey: 'selection',
            align: 'center',
            reserveSelection: true
          },
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center',
            showOverflowTooltip: true,
            fixed: 'left'
          },
          {
            prop: 'assetCode',
            label: '物品编码',
            align: 'center',
            showOverflowTooltip: true,
            fixed: 'left'
          },
          {
            prop: 'assetName',
            label: '物品名称',
            align: 'center',
            showOverflowTooltip: true,
            fixed: 'left'
          },
          {
            label: '牌号',
            align: 'brandNum',
            showOverflowTooltip: true
          },
          {
            prop: 'modelType',
            label: '型号',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'specification',
            label: '规格',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'measuringUnit',
            label: '计量单位',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'weightUnit',
            label: '重量单位',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'roughWeight',
            label: '毛重',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'netWeight',
            label: '净重',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 120
          },
          {
            prop: 'packingUnit',
            label: '包装单位',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'categoryLevelPath',
            label: '分类',
            align: 'center',
            showOverflowTooltip: true
          },

          {
            prop: 'isUnpack',
            label: '允许拆包',
            align: 'center',
            showOverflowTooltip: true,
            formatter: (_row, _column, cellValue) => {
              return _row.isUnpack ? '是' : '否';
            }
          },
          ...this.newColumns
        ];
      }
    },
    methods: {
      //获取工厂列表
      async getFactoryList() {
        const res = await warehouseDefinition.getFactoryarea({
          pageNum: 1,
          size: 9999,
          type: 1
        });
        this.factoryList = res.list;
      },
      // doLayout() {
      //   let that = this;
      //   this.$nextTick(() => {
      //     that.$refs.multipleTable.doLayout();
      //   });
      // },
      // 获取动态表头
      getFieldModel() {
        storageApi.fieldModel({ fieldModel: 't_main_category' }).then((res) => {
          let newRes = res.map((m) => {
            return {
              prop: 'extField.' + m.prop,
              label: m.label,
              align: 'center',
              showOverflowTooltip: true
            };
          });
          this.newColumns = [...newRes];
        });
      },
      handleSearch() {
        this.reload();
      },
      /* 刷新表格 */
      reload(where) {
        this.$nextTick(() => {
          this.$refs.multipleTable.reload({ page: 1, where });
        });
      },
      onConfirm() {
        // console.log([...this.memoSelection, ...this.multipleSelection]);
        this.$emit('selectTableData', this.selection);
        this.closeWindows();
      },
      getTreeList() {
        this.$nextTick(() => {
          this.$refs.treeList.getTreeData().then((data) => {
            this.handleNodeClick(data);
          });
        });
      },
      setclassIds(data, list) {
        if (data && data.length !== 0) {
          data.forEach((item) => {
            if (item.children && item.children.length !== 0) {
              this.setclassIds(item.children, list);
            }
            list.push(item.id);
          });
        }
        return list;
      },
      // handleSelectionChange(val) {
      //   this.multipleSelection = val;
      // },
      handleNodeClick(data) {
        console.log('-----------------');
        console.log(data);
        this.classificationId = data.id;
        this.curType = data.type;
        this.reload();
      },
      closeWindows() {
        this.selection = [];
        // this.multipleSelection = [];
        this.$refs.multipleTable.setSelectedRows([]);
        this.$emit('update:loadTree', false);
        this.$emit('update:visibleDialog', false);
        this.pages.pageNum = 1;
      },

      handleCurrentChange(e) {
        this.reload();
      },
      handleSizeChange(e) {
        this.pages.pageNum = 1;
        this.reload();
      },
      initData() {
        // this.memoSelection = this.multipleSelection.reduce((cur, pre) => {
        //   if (!this.memoSelection.some((i) => i.curId === pre.curId)) {
        //     cur.push(pre);
        //   }
        //   return cur;
        // }, this.memoSelection.slice(0));
        this._getInformation();
      },
      async _getInformation({ page, limit, where, order }) {
        const params = {
          pageNum: page,
          size: limit,
          ...where,
          factoryId: this.factoryId,
          searchKey: encodeURIComponent(this.value),
          categoryLevelId: this.classificationId
        };
        let res = await getList(params);

        if (res && this.classificationId == params.categoryLevelId) {
          const curMap = {
            assetId: 'id',
            assetCode: 'code', //编码
            assetName: 'name', //名称
            materialId: 'id',
            materialName: 'informationName',
            batchNo: '', //批次号
            unit: 'measuringUnit', //单位
            minPackUnit: 'packingUnit' //最小包装单位
          };
          res.list.forEach((item) => {
            for (const key in curMap) {
              // console.log(curMap[key],'curMap[key]')
              item[key] = curMap[key] ? item[curMap[key]] : '';
            }
            item.curId = item.id;
            return item;
          });

          // this.$nextTick(() => {
          //   this.tableData.forEach((item) => {
          //     const index = this.memoSelection.findIndex(
          //       (i) => item.curId === i.curId
          //     );
          //     if (index > -1) {
          //       // 删除还给 multipleSelection
          //       this.$refs.multipleTable.toggleRowSelection(item, true);
          //       this.memoSelection.splice(index, 1);
          //     }
          //   });
          // });
          // this.total = res.count;
        }
        return res;
      }
    }
  };
</script>

<style lang="scss" scoped>
  .flex_info {
    display: flex;
    margin-top: 20px;
    margin-bottom: 20px;

    .flex_left {
      width: 202px;
      height: 434px;
      padding: 10px;
      border: 1px solid #d7d7d7;
      overflow-y: auto;
    }

    .flex_right {
      flex: 1;
      margin-left: 10px;
      overflow: hidden;
    }
  }

  .search_box {
    overflow: hidden;
  }

  .select-btn {
    text-align: right;
  }

  .right {
    text-align: right;
  }

  .mt10 {
    margin-top: 10px;
  }
</style>
