<template>
  <div>
    <el-dialog
      :title="`${title}信息`"
      append-to-body
      :visible="visibleDialog"
      :before-close="closeWindows"
      width="80vw"
    >
      <div class="search_box">
        <el-col :span="8">
          <el-input v-model="value" placeholder="搜索物品编码、名称">
            <el-button
              slot="append"
              type="primary"
              icon="el-icon-search"
              size="small"
              @click="handleSearch"
              >搜索</el-button
            >
          </el-input>
        </el-col>
      </div>
      <div class="flex_info">
        <div class="flex_left">
          <AssetTree
            @handleNodeClick="handleNodeClick"
            :type="type[0]"
            :init="true"
            ref="treeList"
            paramsType="type"
          />
        </div>
        <div class="flex_right">
          <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 type="selection" width="55" align="center">
            </el-table-column>
            <el-table-column width="55px" label="序号" type="index">
              <!-- <template slot-scope="{ $index }">
                {{ $tableIndex($index, pages.pageNum, pages.size) }}
              </template> -->
            </el-table-column>
            <el-table-column
              prop="assetCode"
              label="物品编码"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              prop="assetName"
              label="物品名称"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <!-- <el-table-column
              prop="brandNum"
              label="牌号"
              :show-overflow-tooltip="true"
            ></el-table-column> -->
            <el-table-column
              :prop="item.prop"
              :show-overflow-tooltip="true"
              :label="item.label"
              v-for="(item, index) in tableHeader"
              :key="index"
            >
              <template slot-scope="{ row }">
                <template v-if="item.formatter">{{
                  item.formatter(row)
                }}</template>
                <template v-else>{{ row[item.prop] }}</template>
              </template></el-table-column
            >
            <el-table-column
              prop="measuringUnit"
              label="计量单位"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              prop="weightUnit"
              label="重量单位"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              prop="roughWeight"
              label="毛重"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              prop="netWeight"
              label="净重"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              prop="packingUnit"
              label="包装单位"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              prop="categoryLevelPath"
              label="分类"
              :show-overflow-tooltip="true"
            ></el-table-column>
          </el-table>
          <div class="right mt10" v-if="bizScene != 5">
            <el-pagination
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              :page-sizes="[15, 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>
    </el-dialog>
  </div>
</template>

<script>
  import AssetTree from './AssetTree/wms.vue';
  import { getList } from '@/api/classifyManage/itemInformation';

  export default {
    props: {
      visibleDialog: {
        type: Boolean,
        default: false
      },
      title: {
        type: String,
        default: ''
      },
      bizScene: {
        type: String,
        default: ''
      },
      type: {
        type: Array,
        default: () => []
      },
      tableHeader: {
        type: Array,
        default: () => []
      },
      loadTree: {
        type: Boolean,
        default: true
      }
    },
    watch: {
      visibleDialog: {
        handler(v) {
          if (v) {
            this.getTreeList();
          }
        },
        deep: true
      }
    },
    components: { AssetTree },
    data() {
      return {
        value: '',
        treeType: '',
        treeList: [],
        tableData: [],
        multipleSelection: [],
        pages1: { classificationIdList: [] },
        pages: {
          pageNum: 1,
          size: 10
        },
        total: 0,
        curType: '',
        classificationId: '',
        memoSelection: []
      };
    },
    created() {},
    methods: {
      handleSearch() {
        this.pages.pageNum = 1;
        this.initData();
      },
      onConfirm() {
        this.$emit('selectTableData', [
          ...this.memoSelection,
          ...this.multipleSelection
        ]);
        this.closeWindows();
      },
      getTreeList() {
        this.$nextTick(() => {
          if (!this.loadTree) this.$refs.treeList.getTreeData();
        });
      },
      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) {
        this.classificationId = data.id;
        this.curType = data.type;
        this.initData();
      },
      closeWindows() {
        this.memoSelection = [];
        this.multipleSelection = [];
        this.$emit('update:loadTree', false);
        this.$emit('update:visibleDialog', false);
        this.pages.pageNum = 1;
      },
      handleCurrentChange(e) {
        this.initData();
      },
      handleSizeChange(e) {
        this.pages.pageNum = 1;
        this.initData();
      },
      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));
        if (this.bizScene == 5) {
          this._getAssetLedger();
        } else {
          this._getInformation();
        }
      },
      async _getInformation() {
        const params = {
          ...this.pages,
          // type: this.curType,
          // code: this.value,
          searchKey: this.value,
          categoryLevelId: this.classificationId
        };
        console.log(params);
        const 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' //最小包装单位
          };
          this.tableData = res.list.map((item) => {
            for (const key in curMap) {
              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;
        }
      },
      async _getAssetLedger() {
        const params = {
          // // type: this.curType,
          assetCode: this.value,
          materialId: this.classificationId,
          assetType: this.type[0]
        };
        const curMap = {
          materialName: 'assetName', //类型
          batchNo: 'batchNo', //批次号
          outInNum: '' //数量
        };
        const res = await getAssetLedger(params);
        if (res?.success && this.classificationId == params.materialId) {
          this.tableData = res.data.map((item) => {
            for (const key in curMap) {
              item[key] = curMap[key] ? item[curMap[key]] : '';
            }

            item.curId =
              item.assetCode +
              item.measurementUnit +
              item.minPackUnit +
              item.unit;
            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);
              }
            });
          });
        }
      }
    }
  };
</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;
    }
  }
  .search_box {
    overflow: hidden;
    ::v-deep .el-input-group__append {
    }
  }
  .select-btn {
    text-align: right;
  }
  .right {
    text-align: right;
  }
  .mt10 {
    margin-top: 10px;
  }
</style>
