<template>
  <el-dialog :visible.sync="visible" title="选择出库明细" width="90vw">
    <el-form :model="formData" label-width="120px">
      <el-row>
        <!-- <el-col :span="6">
          <el-form-item label="仓库：" prop="warehouseId">
            <el-select
              style="width: 100%"
              clearable
              v-model="formData.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="code">
            <el-input
              v-model.trim="formData.code"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="物品名称" prop="name">
            <el-input
              v-model.trim="formData.name"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="货位" prop="goodsAllocation">
            <el-input
              v-model.trim="formData.goodsAllocation"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item :label="`${title}编码`" prop="sourceBizNo">
            <el-input
              v-model.trim="formData.sourceBizNo"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="批次号" prop="batchNo">
            <el-input
              v-model.trim="formData.batchNo"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="包装编码" prop="packageNo">
            <el-input
              v-model.trim="formData.packageNo"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="时间类型">
            <el-select
              style="width: 100%"
              v-model="formData.dateType"
              placeholder=""
              @change="$forceUpdate()"
            >
              <el-option label="生产日期" :value="2"> </el-option>
              <el-option label="采购日期" :value="1"> </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="时间" prop="productTime">
            <el-date-picker
              v-model="formData.productTime"
              type="daterange"
              style="width: 100%"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              placeholder="选择日期"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col style="text-align: right">
          <el-button @click="reset" icon="el-icon-refresh-left" size="small"
            >重置</el-button
          >
          <el-button
            type="primary"
            @click="handleList"
            icon="el-icon-search"
            size="small"
            >搜索</el-button
          >
        </el-col>
      </el-row>
    </el-form>
    <div class="info-box">
      <ul>
        <li><span>物品编码</span>{{ infoData.code }}</li>
        <li><span>物品名称</span>{{ infoData.name }}</li>
        <li v-for="(item, index) in tableHeader" :key="index">
          <span>{{ item.label }}</span>
          <template v-if="item.formatter">{{
            item.formatter(infoData)
          }}</template>
          <template v-else>{{ infoData[item.prop] }}</template>
        </li>
        <li v-if="infoData.sparePartsNum">
          <span>申领数量</span>{{ infoData.sparePartsNum }}
        </li>
      </ul>
      <div class="result-box">
        <!-- takeStockPattern0,逐个出库,1,批量出库 -->

        <div class="select-box"><span>已选数量</span> {{ selectedNum }}条</div>
        <div v-if="infoData.takeStockPattern === 1" class="select-box">
          <!-- 选择数量<el-input-number
            size="mini"
            :controls="false"
            v-model="multipleNum"
            :max="tableData.length"
          >
          </el-input-number
          >条 -->
          <el-button type="text" @click="openBatch">批量出库</el-button>
        </div>
      </div>
    </div>
    <el-table
      height="60vh"
      ref="tableRef"
      :data="tableData"
      @selection-change="selecctedRow"
      style="width: 100%"
      :header-cell-style="{ background: '#EEEEEE', border: 'none' }"
    >
      <el-table-column label="序号" type="index"></el-table-column>
      <el-table-column
        label="货位"
        prop="pathName"
        show-overflow-tooltip
        width="270"
      >
      </el-table-column>
      <el-table-column
        :label="`${title}编码`"
        prop="sourceBizNo"
      ></el-table-column>
      <el-table-column label="物品编码" prop="code"> </el-table-column>
      <el-table-column label="物品名称" prop="name"> </el-table-column>
      <el-table-column label="批次号" prop="batchNum"> </el-table-column>
      <el-table-column
        label="生产日期"
        width="180"
        v-if="formData.dateType == 2"
      >
        <template slot-scope="{ row }">
          <span>
            {{ row.produceTime }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="采购日期"
        width="180"
        v-if="formData.dateType == 1"
      >
        <template slot-scope="{ row }">
          <span>
            {{ row.procureTime }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="最小包装单元"
        prop=""
        align="center"
        v-if="!infoData.isUnpack"
      >
        <template slot-scope="{ row }">
          {{ row.measurementUnit }}{{ row.unit }}/{{ row.minUnit }}
        </template>
      </el-table-column>
      <el-table-column label="包装编码" prop="packageNo"></el-table-column>
      <el-table-column label="入库时间" prop="createTime"></el-table-column>
      <el-table-column width="50" type="selection"></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="formData.size"
        :current-page.sync="formData.pageNum"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      >
      </el-pagination>
    </div>
    <div slot="footer" class="footer">
      <div class="info">
        <div><span>总库存量</span>{{ infoData.availableCountBase }}</div>
        <!-- <div><span>总包装数量</span>{{ infoData.realPacketNum }}</div> -->
      </div>
      <div>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </div>
    </div>
    <el-dialog
      :visible.sync="batchVisible"
      title="批量选择"
      width="300px"
      append-to-body
    >
      <div style="text-align: center">
        <el-input-number
          size="small"
          v-model="multipleNum"
          :max="tableData.length"
        >
        </el-input-number>
      </div>

      <div slot="footer">
        <el-button size="small" @click="batchVisible = false">取消</el-button>
        <el-button size="small" type="primary" @click="multiConfirm"
          >确认</el-button
        >
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
  // import { getWarehouseActualDetail } from '@/api/stockManagement/stockLedger.js'
  import outin from '@/api/warehouseManagement/outin';
  import { getWarehouseList } from '@/api/classifyManage/itemInformation';

  export default {
    props: {
      tableHeader: {
        type: Array,
        default: () => []
      },
      title: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        visible: false,
        batchVisible: false,
        multipleNum: '',
        confirmResolve: null,
        tableData: [],
        selectList: [],
        formData: {
          cargoSpaceCode: '',
          time: '',
          dateType: 2,
          batchNo: '',
          packageNo: '',
          onlyCode: '',
          pageNum: 1,
          size: 10
        },
        infoData: {},
        memo: [],
        memo1: [],
        total: 0,
        warehouseList: []
      };
    },
    computed: {
      selectedNum() {
        return this.memo.length;
      },
      checkedAll: {
        get() {
          return this.tableData.every((item) => item.checked);
        },
        set(val) {
          this.tableData.forEach((item) => (item.checked = val));
        }
      }
    },
    created() {
      // this.getArguInfo();
    },
    methods: {
      //搜索数据源
      async getArguInfo() {
        // console.log(111);
        // const { data } = await getWarehouseList();
        // this.warehouseList = data;
      },
      handleCurrentChange(val) {
        this.formData.pageNum = val;
        this.handleList();
      },
      handleSizeChange(val) {
        // this.formData.pageNum = 1;
        this.formData.size = val;
        this.handleList();
      },
      selecctedRow(val) {
        console.log(val);
        this.$emit('mxArgs', val);
        this.memo = val;
      },
      open(infoData, memo = []) {
        this.visible = true;
        this.batchVisible = false;
        this.infoData = infoData;
        this.tableData = [];
        // console.log('wqwq', this.infoData.assetCode);
        this.formData = { pageNum: 1, size: 10, type: infoData.type };
        if (this.infoData.bizTypes == 3) {
          // this.formData.code = this.infoData.assetCode;
          this.$set(this.formData, 'code', this.infoData.assetCode);
        }
        this.formData.dateType = 2;

        this.memo1 = memo || [];
        this.multipleNum = this.memo.length;

        this.handleList(true);

        return new Promise((res) => (this.confirmResolve = res));
      },
      cancel() {
        this.tableData = [];
        this.memo = [];
        this.memo1 = [];
        this.visible = false;
      },
      confirm() {
        if (!this.selectedNum) {
          return this.$message.error('请勾选数据');
        }
        this.confirmResolve && this.confirmResolve(this.memo);
        this.cancel();
      },
      openBatch() {
        this.multipleNum = 0;
        this.batchVisible = true;
      },
      multiConfirm() {
        if (!this.multipleNum) {
          return this.$message.error('请输入大于0的数量');
        }
        this.batchVisible = false;

        const selectedList = this.tableData.filter((i) => i.checked);

        if (selectedList.length === this.multipleNum) return;

        if (selectedList.length >= this.multipleNum) {
          for (
            let index = this.multipleNum;
            index < selectedList.length;
            index++
          ) {
            selectedList[index].checked = false;

            this.singleSelect(false, selectedList[index]);
          }
        } else {
          let rest = this.multipleNum - selectedList.length;

          for (const p of this.tableData) {
            if (!p.checked) {
              p.checked = true;
              this.memo.push(p);
              rest--;
            }

            if (!rest) break;
          }
        }

        // this.tableData.forEach((item, index) => {
        //   item.checked = index < this.multipleNum

        //   if (item.checked) {
        //     this.memo.push(item)
        //   }
        // })
      },
      reset() {
        this.formData = {};
        this.handleList();
      },
      singleSelect(checked, row) {
        // 取消选中
        if (!checked) {
          let index = this.memo.findIndex(
            (item) => item.onlyCode === row.onlyCode
          );
          if (index > -1) {
            this.memo.splice(index, 1);
          }
        } else {
          this.memo.push(row);
        }
      },
      // 表格数据
      async handleList(val) {
        console.log(this.infoData);
        console.log('sasa', this.formData);
        if (this.formData.dateType == 1) {
          this.formData.manufactureTime = this.formData.productTime;
        } else {
          this.formData.procurementTime = this.formData.productTime;
        }
        // if (!this.infoData.id) {
        //   this.$message.warning('数据异常，当前物品id为空！');
        //   return;
        // }
        const res = await outin.getoutDetail({
          ...this.formData,
          categoryId: this.infoData.id
        });
        console.log('11', res);
        this.tableData = res.data.list;
        this.total = res.data.count;
        if (res.data.list.length > 0 && res.data.list[0].brandNum) {
          this.infoData.brandNum = res.data.list[0].brandNum;
        }

        if (val) {
          this.changeSelect();
        }
      },
      changeSelect() {
        this.$nextTick(() => {
          this.tableData.forEach((item) => {
            const index = this.memo1.findIndex(
              (i) => item.sourceBizNo == i.sourceBizNo
            );
            if (index > -1) {
              this.$refs.tableRef.toggleRowSelection(item, true);
            }
          });
        });
      }
    }
  };
</script>

<style lang="scss" scoped>
  .info-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 14px;
    padding: 20px 0 5px;

    ul {
      list-style: none;
      display: flex;
      justify-content: space-between;
      align-items: center;
      li {
        margin-right: 40px;
      }
      span {
        font-weight: bold;
        margin-right: 10px;
      }
    }

    .result-box {
      margin: 0 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      white-space: nowrap;
      .el-input {
        width: 100px;
        margin: 0 10px;
      }
      .select-box {
        margin-left: 20px;

        .el-input-number {
          width: 80px;
        }
      }
      .el-button {
        font-size: 16px;
      }
    }
  }

  .footer {
    display: flex;
    justify-content: space-between;

    .info {
      display: flex;

      span {
        font-weight: bold;
        margin-right: 10px;
      }
      > div {
        margin-right: 20px;
      }
    }
  }
</style>
