<template>
  <el-dialog
    :visible.sync="visible"
    :append-to-body="true"
    :title="`${title}信息`"
    width="80vw"
  >
    <el-form :model="searchForm" label-width="100px">
      <el-row>
        <!-- <el-col :span="6">
          <el-form-item label="仓库：" prop="warehouseId">
            <el-select
              style="width: 100%"
              clearable
              v-model="searchForm.warehouseId"
              placeholder="请选择"
            >
              <el-option
                v-for="item in warehouseList"
                :label="item.name"
                :value="item.id"
                :key="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col> -->
        <!-- <el-col :span="6">
          <el-form-item label="货位：" prop="cargoSpaceCode">
            <el-input
              v-model.trim="searchForm.cargoSpaceCode"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="批次号：" prop="batchNum">
            <el-input
              v-model.trim="searchForm.batchNum"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col> -->
        <!-- <el-col :span="6">
          <el-form-item label="包装编码：" prop="num">
            <el-input
              v-model.trim="searchForm.num"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col> -->
        <el-col :span="6">
          <el-form-item label="列表维度：" prop="dimension">
            <template>
              <el-select
                style="width: 100%"
                @change="changeDimensionHandler"
                v-model="dimension"
                placeholder="请选择"
              >
                <el-option label="物料维度" value="4"> </el-option>
                <el-option label="包装维度" value="3"> </el-option>
                <el-option label="批次维度" value="2"> </el-option>
                <!-- <el-option label="物品维度" value="1"> </el-option> -->
              </el-select>
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="物品编码">
            <el-input
              type="text"
              placeholder="搜索物品编码"
              v-model="searchForm.code"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="物品名称">
            <el-input
              type="text"
              placeholder="搜索物品名称"
              v-model="searchForm.assetName"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="批次号">
            <el-input
              type="text"
              placeholder="搜索物品批次号"
              v-model="searchForm.batchNo"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="刻码">
            <el-input
              type="text"
              placeholder="搜索物品刻码"
              v-model="searchForm.engrave"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="发货码">
            <el-input
              type="text"
              placeholder="搜索发货码"
              v-model="searchForm.barcodes"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="批号">
            <el-input
              type="text"
              placeholder="搜索批号"
              v-model="searchForm.manualBatchNo"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="牌号">
            <el-input
              type="text"
              placeholder="搜索牌号"
              v-model="searchForm.brandNum"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col v-if="dimension != 2" :span="6">
          <el-form-item label="质检结果">
            <el-select
              clearable
              v-model="searchForm.qualityResult"
              placeholder="请选择质检结果"
              style="width: 100%"
            >
              <el-option
                v-for="item in qualityResultOption"
                :label="item.label"
                :value="item.value"
                :key="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col style="text-align: right">
          <el-button type="primary" @click="doSearch">搜索</el-button>
          <el-button icon="el-icon-refresh-left" @click="reset">重置</el-button>
        </el-col>
      </el-row>
    </el-form>
    <el-container>
      <el-aside width="200px" class="wrapper-assets">
        <AssetTree
          @handleNodeClick="handleNodeClick"
          :type="assetType"
          ref="treeList"
          :init="true"
          paramsType="type"
        />
      </el-aside>
      <el-main>
        <el-table
          ref="multipleTable"
          :data="tableData"
          tooltip-effect="dark"
          height="50vh"
          border
          row-key="oid"
          style="width: 100%"
          :header-cell-style="{ background: '#F0F3F3', border: 'none' }"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            :reserve-selection="true"
            width="55"
            align="center"
            fixed="left"
            :selectable="selectable"
          >
          </el-table-column>
          <el-table-column
            prop="assetCode"
            label="编码"
            min-width="120"
            v-if="dimension != 3 || dimension != 4"
          ></el-table-column>
          <el-table-column
            prop="name"
            width="200"
            label="名称"
          ></el-table-column>
          <el-table-column
            width="200"
            :prop="item.prop"
            :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="manualBatchNo"
            label="批号"
            min-width="100"
          ></el-table-column>
          <el-table-column
            v-if="dimension == 2 || dimension == 3 || dimension == 4"
            prop="batchNo"
            label="批次号"
            min-width="120"
          ></el-table-column>
          <el-table-column
            label="发货条码"
            prop="barcodes"
            width="80"
            :show-overflow-tooltip="true"
          ></el-table-column>
          <el-table-column
            v-if="dimension == 3 || dimension == 4"
            prop="onlyCode"
            label="包装编码"
            min-width="120"
          ></el-table-column>
          <el-table-column
            v-if="dimension == 3 || dimension == 4"
            prop="no"
            label="物料编码"
            min-width="120"
          ></el-table-column>
          <el-table-column
            v-if="dimension == 3 || dimension == 4"
            prop="materielCode"
            label="物料代号"
            min-width="120"
          ></el-table-column>
          <el-table-column
            v-if="dimension == 3 || dimension == 4"
            prop="clientCode"
            label="客户代号"
            min-width="120"
          ></el-table-column>
          <el-table-column
            v-if="dimension == 3 || dimension == 4"
            prop="engrave"
            label="刻码"
            min-width="120"
          ></el-table-column>
          <el-table-column
            prop="packingCountBase"
            label="包装库存数量"
            width="120"
            v-if="dimension != 4"
          ></el-table-column>
          <el-table-column
            prop="minUnit"
            label="单位"
            v-if="dimension != 4"
            width="90"
          ></el-table-column>
          <el-table-column
            prop="availableCountBase"
            label="计量库存数量"
            width="120"
          ></el-table-column>
          <el-table-column
            prop="measuringUnit"
            label="计量单位"
            width="90"
          ></el-table-column>
          <el-table-column
            v-if="dimension == 4 || dimension == 3"
            prop="weight"
            label="重量"
            min-width="120"
          ></el-table-column>
          <el-table-column
            v-if="dimension == 4 || dimension == 3"
            prop="weightUnit"
            label="重量单位"
            min-width="120"
          ></el-table-column>
          <el-table-column
            prop="expirationTime"
            label="周期倒计时"
            min-width="120"
          ></el-table-column>
          <el-table-column prop="weightUnit" label="质检状态" min-width="120">
            <template slot-scope="{ row }">
              <span v-if="row.qualityStatus == 0">未质检</span>
              <span v-else-if="row.qualityStatus == 1">已质检</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column prop="weightUnit" label="质检结果" min-width="120">
            <template slot-scope="{ row }">
              <span v-if="row.qualityResult == 0">合格</span>
              <span v-else-if="row.qualityResult == 1">不合格</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="pathName"
            label="仓库"
            min-width="120"
          ></el-table-column>

          <!-- <el-table-column prop="pathName" label="仓库"> </el-table-column> -->
        </el-table>
        <div style="text-align: right; padding: 10px">
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            :page-sizes="[5, 10, 20, 50]"
            :page-size.sync="pages.size"
            :current-page.sync="pages.pageNum"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          >
          </el-pagination>
        </div>
      </el-main>
    </el-container>

    <div slot="footer">
      <el-button type="primary" @click="confirm()">确定</el-button>
      <el-button @click="cancel">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import AssetTree from '@/components/AssetTree/wms.vue';
  // import { detailSelect } from '@/api/stockManagement/stockLedger';
  // import { deepClone } from '@/utils';

  import { tableHeader } from '../../handleTask/components/inoutBound/common';
  import outin from '@/api/warehouseManagement/outin';
  import { login } from '@/api/login';
  import { getWarehouseList } from '@/api/classifyManage/itemInformation';
  import {
    getBatchDetails,
    getDetailById,
    getDetailByCode
  } from '@/api/classifyManage';
  export default {
    components: { AssetTree },
    props: {
      title: String,
      assetType: {
        type: [String, Number],
        default: ''
      },
      warehousingMaterialList: {
        type: Array,
        default: () => []
      }
    },
    computed: {
      tableHeader() {
        return tableHeader(this.assetType);
      }
    },
    watch: {
      // 解决右侧悬浮操作栏不对称问题
      tableData: {
        handler() {
          this.$nextTick(() => {
            this.$refs.multipleTable.doLayout();
          });
        },
        deep: true
      }
    },
    data() {
      return {
        qualityResultOption: [
          {
            value: 0,
            label: '合格'
          },
          {
            value: 1,
            label: '不合格'
          }
        ],
        qualityStatusOption: [
          {
            value: 1,
            label: '已质检'
          },
          {
            value: 0,
            label: '未质检'
          }
        ],
        visible: false,
        tableData: [],
        total: 0,
        pages: {
          pageNum: 1,
          size: 10
        },
        searchForm: {
          code: '',
          assetName: '',
          batchNo: '',
          brandNum: '',
          engrave: '',
          barcodes: '',
          qualityResult: '',
          manualBatchNo: ''
        },
        selectionList: [],
        materialType: '',
        warehouseList: [],
        dimension: '4'
      };
    },
    created() {},
    methods: {
      changeDimensionHandler(e) {
        this.pages.pageNum = 1;
        this.changeDimension(e);
      },
      async changeDimension(e, is) {
        // await this.$refs.multipleTable.clearSelection();
        // this.selectionList = [];
        console.log('===1', this.warehousingMaterialList);
        console.log('===2', e);
        // if (is != 'page') {
        //   this.$refs.multipleTable.clearSelection();
        // }
        this.dimension = e;
        let res = {};
        const params = {
          ...this.pages,
          ...this.searchForm,
          dimension: e
        };
        if (this.materialType) {
          params.categoryLevelId = this.materialType;
        }
        if (e == 2) {
          res = await getBatchDetails(params);
          this.tableData = res.list.map((item) => {
            return {
              ...item,
              minUnit: item.packingUnit,
              oid: item.stockBatchId,
              assetCode: item.code
            };
          });
        } else if (e == 3) {
          res = await outin.getInventoryDetails(params);
          this.tableData = res.list.map((item) => {
            return {
              ...item,
              batchNo: item.batchNum,
              minUnit: item.packingUnit,
              // availableCountBase: 1,
              packingCountBase: 1,
              oid: item.id,
              assetCode: item.code
            };
          });
          this.total = res.count;
          return this.tableData;
        } else if (e == 4) {
          res = await outin.getMaterielDetails(params);
          this.tableData = res.list.map((item, index) => {
            return {
              ...item,
              availableCountBase: 1,
              packingCountBase: 1,
              minUnit: item.packingUnit,
              oid: item.id + this.pages.pageNum + (index + 1)
            };
          });
          console.log('===', this.tableData);
        } else {
          res = await outin.getRealTimeInventory(params);
          this.tableData = res.list.map((item) => {
            return { ...item, oid: item.id, assetCode: item.code };
          });
        }
        if (res) {
          this.total = res.count;
          // this.selectionList = deepClone(this.warehousingMaterialList);

          this.$nextTick(() => {
            this.tableData.forEach((item) => {
              const index = this.warehousingMaterialList.findIndex((i) =>
                this.dimension == 1 || this.dimension == 3
                  ? item.id == i.id
                  : this.dimension == 2
                  ? item.stockBatchId == i.stockBatchId
                  : item.oid == i.oid
              );
              if (index > -1) {
                // 删除还给 multipleSelection
                this.$refs.multipleTable.toggleRowSelection(item, true);
              }
            });
          });
        }
      },
      selectable(row, index) {
        if (row.canUsedCount != 0) {
          return true;
        } else {
          return false;
        }
      },
      open() {
        this.visible = true;
        this.$nextTick(() => {
          this.$refs.treeList.getTreeData();
          // this.doSearch()
        });
      },
      async handleExit(arr) {
        console.log('arr=====', arr);
        console.log('this.dimension', this.dimension);
        let ids = null;
        let batchIds = null;
        let materielIds = null;
        if (this.dimension == 3) {
          ids = arr.map((item) => {
            return item.id;
          });
        } else if (this.dimension == 2) {
          ids = arr.map((item) => {
            return item.recordId;
          });
          batchIds = arr.map((item) => {
            return item.stockBatchId;
          });
        } else if (this.dimension == 4) {
          materielIds = arr.map((item) => {
            return item.materielId;
          });
          ids = arr.map((item) => {
            return item.recordId;
          });
        } else {
          ids = arr.map((item) => {
            return item.recordId;
          });
        }
        let categoryIds = arr.map((item) => {
          return item.id;
        });
        let batchNos = arr.map((item) => {
          return item.batchNo;
        });
        let outInDetailIds = arr.map((item) => {
          return item.outInDetailId;
        });
        const parmas = {
          categoryLevelId: this.materialType,
          type: this.dimension,
          categoryIds,
          batchNos,
          batchIds,
          ids,
          outInDetailIds,
          materielIds
        };
        console.log(parmas);
        const data = await getDetailById(parmas);
        return data;
      },
      async getSelectionList(list) {
        let ajax = [];
        let arr = [];
        list.forEach((item) => {
          this.searchForm.code = item.productCode;
          ajax.push(this.changeDimension(this.dimension));
        });
        (await Promise.all(ajax)).forEach((item) => {
          arr.push(...item);
        });
        return arr;
      },
      async confirm(list, dimension) {
        if (dimension) {
          const data = await getDetailByCode(
            list.map((item) => {
              return {
                categoryLevelId: item.productCategoryId,
                code: item.productCode,
                count: item.totalCount
              };
            })
          );
          this.$emit('detailData', { ...data, wlList: [] }, dimension);
          this.visible = false;
          return;
        }
        if (!this.selectionList.length) {
          this.$message.error('请至少选择一条数据！');
          return;
        }
        const data = await this.handleExit(this.selectionList);
        let arr = [];
        if (this.dimension == 4) {
          arr = this.selectionList.map((item) => {
            return { ...item, assetName: item.name };
          });
        }
        this.$emit('detailData', { ...data, wlList: arr }, this.dimension);

        // this.$emit('selectTableData', this.selectionList);
        this.cancel();
      },
      cancel() {
        this.multipleSelection = [];
        this.$refs.multipleTable.clearSelection();
        this.visible = false;
      },
      handleSelectionChange(val) {
        for (const key in val) {
          val[key].categoryId = val[key].id;
        }
        this.selectionList = val;
      },
      handleNodeClick(data) {
        this.materialType = data.id === data.originId ? '' : data.id;
        this.doSearch();
      },
      handleCurrentChange() {
        // this.getList();
        this.changeDimension(this.dimension, 'page');
      },
      reset() {
        this.searchForm.code = '';
        this.searchForm.assetName = '';
        this.searchForm.batchNo = '';
        this.searchForm.engrave = '';
        this.searchForm.barcodes = '';
        this.searchForm.qualityResult = '';
        this.searchForm.manualBatchNo = '';
        this.searchForm.brandNum = '';
        this.doSearch();
      },
      doSearch() {
        this.pages.pageNum = 1;
        // this.getList();
        this.changeDimension(this.dimension);
      },
      handleSizeChange() {
        this.pages.pageNum = 1;
        // this.getList();
        this.changeDimension(this.dimension, 'page');
      }
      // async getList() {
      //   const params = {
      //     ...this.pages,
      //     ...this.searchForm,
      //     dimension: this.dimension
      //     // code: 5
      //   };

      //   if (this.materialType) {
      //     params.categoryLevelId = this.materialType;
      //   }

      //   const res = await outin.getMaterielDetails(params);

      //   if (res) {
      //     this.tableData = res.list.map((item, index) => {
      //       return {
      //         ...item,
      //         oid: index + 1 + (this.pages.pageNum - 1) * this.pages.size
      //       };
      //     });
      //     this.total = res.count;
      //     // this.selectionList = deepClone(this.warehousingMaterialList);
      //     console.log(' this.tableData==', this.tableData);
      //     this.$nextTick(() => {
      //       this.tableData.forEach((item) => {
      //         const index = this.warehousingMaterialList.findIndex((i) =>
      //           this.dimension == 1 || this.dimension == 3
      //             ? item.id == i.id
      //             : this.dimension == 2
      //             ? item.stockBatchId == i.stockBatchId
      //             : item.meterielId == i.meterielId
      //         );
      //         if (index > -1) {
      //           // 删除还给 multipleSelection
      //           this.$refs.multipleTable.toggleRowSelection(item, true);
      //         }
      //       });
      //     });
      //   }
      // }
    }
  };
</script>

<style lang="scss" scoped>
  .el-dialog__wrapper {
    ::v-deep .el-aside {
      background-color: #fff !important;
      border: 1px solid #ccc;
    }
  }

  .wrapper-assets {
    max-height: 53vh;
    overflow: auto;
  }
</style>
