<template>
  <div class="app-container">
    <el-form label-position="left" label-width="160px">
      <div class="itemGroup">
        <el-divider content-position="left">基础信息</el-divider>
        <el-form-item label="任务名称">
          <el-input v-model="dto.InventoryName" />
        </el-form-item>
        <el-form-item label="任务说明">
          <el-input
            type="textarea"
            rows="3"
            v-model="dto.InventoryDec"
            placeholder="任务说明，选填"
          />
        </el-form-item>
        <el-form-item label="所属库房">
          <el-select
            v-model="dto.RoomId"
            placeholder="请选择库房"
            @change="RoomIdChange"
            clearable
          >
            <el-option
              v-for="room in rooms"
              :key="room.Id"
              :label="room.Name"
              :value="room.Id"
            />
          </el-select>
        </el-form-item>
        <el-divider content-position="left">选择盘点区域</el-divider>
        <el-table
          v-loading="dataLoading"
          :data="data"
          :highlight-current-row="true"
          width="100%"
          :row-key="getRowKeys"
          :expand-row-keys="expands"
          @expand-change="toggleRowExpansion"
          @select="tbSelect"
          @select-all="tbSelectAll"
        >
          <!--扩展表格 start-->
          <el-table-column type="expand">
            <!-- <div v-loading
              v-loading="detailDataLoading"
              element-loading-text="正在加载货架数据"
            > -->

            <div class="wrap" slot-scope="props">
              <div v-if="props.row.childer && props.row.childer.length > 0">
                <el-row v-for="(row, index) in props.row.childer" :key="index"
                  ><el-col
                    v-for="(col, index) in row.RowGrids"
                    :key="index"
                    :span="calcColCount(row)"
                  >
                    <div class="grid-content bg-purple-dark shelf-grid-wrap">
                      <div class="shelf-grid">
                        {{ `${row.RowSort}层  ${col.Name}格` }}
                      </div>
                      <el-checkbox
                        v-model="col.isChecked"
                        class="margin-lr-sm"
                        label="选择"
                        border
                        :true-label="col.Id"
                        :false-label="col.Id * -1"
                      ></el-checkbox>
                      <div class="shelf-foot">
                        <a
                          v-if="col.isChecked > 0"
                          @click="openedDetail(col.Id)"
                          >盘点详情>></a
                        >
                      </div>
                    </div>
                  </el-col>
                </el-row>
              </div>

              <div v-else class="no-data">无货架数据</div>
            </div>
            <!-- </div> -->
          </el-table-column>
          <!--扩展表格 end-->
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column prop="Name" label="货架号" />
          <el-table-column prop="RoomName" label="库房" />
          <el-table-column prop="AreaName" label="库区" />
          <el-table-column prop="PathName" label="通道" />
        </el-table>
        <el-pagination
          :page-sizes="[10, 20, 40, 200, 400]"
          :current-page="pagerDto.PageIndex"
          :page-size="pagerDto.PageSize"
          background
          layout="prev, pager, next ,total ,jumper,sizes,slot "
          :total="pagerDto.total"
          @current-change="pagerSerach"
          @row-click="changePager"
        />
      </div>
      <div
        v-if="dto.InventoryStatus == 1 || dto.Id == 0"
        class="itemGroup"
        style="text-align: center"
      >
        <el-form-item>
          <el-button type="primary" :loading="saveLadding" @click="save()"
            >保存</el-button
          >
        </el-form-item>
      </div>
    </el-form>
    <el-dialog :visible.sync="detailVisible" width="90%" center>
      <detail-View ref="detailView" />
    </el-dialog>
  </div>
</template>

<script>
import { getAllEnabledRooms } from "@/api/stock/room";
import { QueryShelf } from "@/api/stock/shelf";
import { LoadShelfGridInfo } from "@/api/stock/shelfGrid";
import { EditData, GetDataById } from "@/api/adminStock/InventoryTask";
import detailView from "./Detail";
export default {
  name: 'InventoryTaskEdit',
  components: {
    detailView,
  },
  data() {
    return {
      rooms: [],
      saveLadding: false,
      detailVisible: false,
      expands: [],
      shelfIds: [],
      dto: {
        chooseValue: [{}],
      },
      seleteData: [],
      //列表部分
      data: [],
      dataLoading: false,
      detailDataLoading: false,
      pagerDto: {
        PageIndex: 0,
        PageSize: 10,
        total: 0,
        _Eq_IsActive: "",
        QuerySort: [{ Field: "UpdateTime", IsDesc: "true" }],
      },
    };
  },
  created() {
    this.getAllRooms();
    GetDataById(this.$route.params.Id).then((response) => {
      this.dto = response;
      this.RoomIdChange();
    });
  },
  methods: {
    getAllRooms() {
      getAllEnabledRooms().then((res) => {
        this.rooms = res;
      });
    },
    save() {
      //保存处理
      if (this.dto.RoomId < 1) {
        this.$message({ type: "warning", message: "库房为必选项！" });
        return false;
      }
      this.selectValues();
      if (this.dto.chooseValue.length < 1) {
        this.$message({ type: "warning", message: "请勾选盘点区域！" });
        return false;
      }
      EditData(this.dto)
        .then((reponse) => {
          this.$message("操作成功");
          this.saveLadding = false;
        })
        .catch(() => {
          console.log("err");
        })
        .finally(() => {
          this.saveLadding = false;
        });
    },
    //货架部分
    RoomIdChange() {
      this.pagerDto._Eq_RoomId = this.dto.RoomId <= 0 ? -1 : this.dto.RoomId;
      this.pagerSerach(1);
    },
    //boolValue  仅全选设置为true,其余都是false
    onShowGridMap(shelfId, boolValue) {
      this.detailDataLoading = true;
      LoadShelfGridInfo({ shelfId })
        .then((res) => {
          for (const r of res.Rows) {
            for (const c of r.RowGrids) {
              let tempChoose = this.dto.chooseValue.find(
                (x) => x.shelf == shelfId
              );
              if (
                boolValue ||
                (tempChoose != null && tempChoose.gridIds.indexOf(c.Id) > -1)
              ) {
                c.isChecked = true;
              }
            }
          }
          this.data.forEach((temp, index) => {
            if (temp.Id == shelfId) {
              this.data[index].childer = res.Rows;
            }
          });
        })
        .catch(() => {
          console.log("err");
        })
        .finally(() => {
          this.detailDataLoading = false;
        });
    },
    calcColCount(row) {
      let gridCount = row.RowGrids && row.RowGrids.length;
      gridCount = gridCount > 0 ? gridCount : 1;
      const span = Math.floor(24 / gridCount);
      return span > 0 ? span : 24;
    },
    getRowKeys(row) {
      // 行数据的Key
      return row.Id;
    },
    toggleRowExpansion(row, expandedRows) {
      this.expands = [];
      if (expandedRows.length > 0) {
        if (row.childer.length == 0) {
          let boolValue = this.shelfIds.indexOf(row.Id) > -1;
          this.onShowGridMap(row.Id, boolValue);
        }
        row ? this.expands.push(row.Id) : "";
      }
    },
    //选择框处理
    tbSelect(val, row) {
      if (val && val.length > 0 && val.indexOf(row) != -1) {
        this.shelfIds.push(row.Id);
        var arrRes = this.data.filter((x) => x.Id == row.Id);
        arrRes[0].childer.map((shelf) => {
          shelf.RowGrids.map((grid) => (grid.isChecked = true));
        });
      } else {
        this.shelfIds = this.shelfIds.filter((item) => item !== row.Id);
        var arrRes = this.data.filter((x) => x.Id == row.Id);
        arrRes[0].childer.map((shelf) => {
          shelf.RowGrids.map((grid) => (grid.isChecked = false));
        });
      }
    },
    tbSelectAll(val) {
      if (val && val.length > 0) {
        this.shelfIds.push(
          val.forEach((element) => {
            element.Id;
          })
        );
        this.data.map((ch) => {
          ch.childer.map((shelf) => {
            shelf.RowGrids.map((grid) => (grid.isChecked = true));
          });
        });
      } else {
        this.shelfIds = [];
        this.data.map((ch) => {
          ch.childer.map((shelf) => {
            shelf.RowGrids.map((grid) => (grid.isChecked = false));
          });
        });
      }
    },
    //处理选中数据
    selectValues() {
      this.dto.chooseValue = [{}];
      this.data.forEach((item) => {
        let tempList = [];
        item.childer.forEach((childItem) => {
          tempList=tempList.concat(
            childItem.RowGrids.filter((x) => x.isChecked > 0).map((x) => {
              return x.Id;
            })
          );
        });
        if (tempList.length > 0) {
          this.dto.chooseValue.push({
            shelf: item.Id,
            gridIds: tempList,
          });
        }
      });
      let tempList2 = this.dto.chooseValue.map((x) => {
        return x.shelf;
      });
      this.shelfIds.forEach((item) => {
        if (tempList2.indexOf(item) < 0) {
          this.dto.chooseValue.push({ shelf: item, gridIds: [] });
        }
      });
      this.dto.chooseValue = this.dto.chooseValue.filter((x) => x.shelf > 0);
    },
    openedDetail(gridId) {
      this.detailVisible = true;
      let data = { TaskId: this.dto.Id, gridId: gridId, op: "Detail" };
      this.$nextTick(() => {
        this.$refs.detailView.getParam(data);
      });
    },
    //列表部分
    pagerSerach(index) {
      this.dataLoading = true;
      if (index) {
        this.pagerDto.PageIndex = index;
      }
      QueryShelf(this.pagerDto)
        .then((res) => {
          res.Result.map((item) => {
            item.childer = [];
          });
          this.data = res.Result;
          this.pagerDto.total = res.TotalCount;
          this.expands = this.dto.chooseValue.map((x) => {
            return x.shelf;
          });
          if (this.data.length > this.expands.length) {
            this.expands.forEach((element) => {
              this.onShowGridMap(element, false);
            });
          } else {
            let dataMap = this.data.map((p) => {
              return p.Id;
            });
            let tempArry = this.expands.map((x) => {
              if (dataMap.indexOf(x) > -1) {
                return x;
              }
            });
            tempArry.forEach((element) => {
              this.onShowGridMap(element, false);
            });
          }
        })
        .finally((res) => {
          this.dataLoading = false;
        });
    },
    changePager(v) {
      this.PageSize = v;
      this.pagerSerach();
    },
  },
};
</script>
<style>
.itemGroup {
  margin: 10px;
  border: 1px solid #ebebeb;
  padding: 30px;
}
</style>
<style lang="scss" scoped>
.wrap {
  min-height: 400px;
}
.shelf-grid-wrap {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 150px;
  margin: 5px;
  font-size: 20px;
  background-color: #eee;
}

.no-data {
  text-align: center;
  font-size: 26px;
  color: #ccc;
}
.shelf-foot {
  line-height: 17px;
  margin-top: 120px;
  font-size: 14px;
  color: #1890ff;
}
</style>
