<template>
  <base-list>
    <template slot="n_header">
      <el-form v-model="pagerDto" inline>
        <el-form-item label="库房名字">
          <el-select v-model="pagerDto._Eq_RoomId" placeholder="请选择库房" clearable>
            <el-option
              v-for="room in rooms"
              :key="room.Id"
              :label="room.Name"
              :value="room.Id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="库区名字">
          <el-select v-model="pagerDto._Eq_AreaId" placeholder="请选择库区" clearable>
            <el-option
              v-for="area in areas"
              :key="area.Id"
              :label="area.Name"
              :value="area.Id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="通道">
          <el-select v-model="pagerDto._Eq_PathId" placeholder="请选择通道" clearable>
            <el-option
              v-for="path in paths"
              :key="path.Id"
              :label="path.Name"
              :value="path.Id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="货架号">
          <el-input
            v-model="pagerDto._Eq_Name"
            type="number"
            placeholder="货架"
            clearable
          />
        </el-form-item>
        <el-form-item label="是否开放">
          <el-select v-model="pagerDto._Eq_IsActive" placeholder="请选择" clearable>
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            /> </el-select></el-form-item>
        <el-form-item>
          <el-button type="primary" @click="pagerSerach()">搜索</el-button>
        </el-form-item></el-form>
    </template>
    <template slot="n_option">
      <el-button size="mini" type="primary" @click="showAddShelf()"> 添加货架 </el-button>
      <el-button size="mini" type="success" @click="showImportGrid = true">
        批量导入货架
      </el-button>
    </template>
    <template>
      <el-table
        v-loading="dataLoading"
        :data="data"
        :highlight-current-row="true"
        :select-on-indeterminate="true"
        width="100%"
      >
        <el-table-column prop="ShelfName" label="货架号">
          <template slot-scope="r">
            <el-link type="primary" @click="showGridMap(r.row)">{{ r.row.Name }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="RoomName" label="库房" />
        <el-table-column prop="AreaName" label="库区" />
        <el-table-column prop="PathName" label="通道" />

        <el-table-column prop="Sort" label="排序" />
        <el-table-column prop="IsActive" label="是否激活">
          <template slot-scope="r">
            <el-switch
              v-model="r.row.IsEnable"
              active-color="#1890ff"
              inactive-color="#ccc"
              @change="changeActive($event, r.row.Id)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="Description" label="描述" />
        <el-table-column label="操作" width="300">
          <template slot-scope="r">
            <el-link
              class="margin-lr-sm"
              icon="el-icon-edit"
              type="primary"
              @click="showEditShelf(r.row)"
            >编辑</el-link>
            <el-link
              class="margin-lr-sm"
              icon="el-icon-edit"
              type="primary"
              @click="showGridMap(r.row)"
            >打印货架条码</el-link>
            <el-link
              class="margin-lr-sm"
              icon="el-icon-delete"
              type="danger"
              @click="showDeleteShelf(r.row)"
            >删除</el-link>
          </template>
        </el-table-column>
        <el-table-column />
      </el-table>
      <el-pagination
        :page-sizes="[10, 20, 40, 200, 400]"
        :current-page="pagerDto.PageIndex"
        :page-size.sync="pagerDto.PageSize"
        background
        layout="prev, pager, next ,total ,jumper,sizes,slot "
        :total="pagerDto.total"
        @current-change="pagerSerach"
        @size-change="changePager"
      />

      <el-dialog
        :title="mapTitle"
        :visible.sync="showGridMapModal"
        width="90%"
        center
        @opened="onShowGridMap"
      >
        <div v-loading="loadingGridInfos" element-loading-text="正在加载货架数据">
          <grid-map ref="gridmap" :grid-data="currentGridMapData" @printShelfLable="directPrint" />
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="showGridMapModal = false">确 定</el-button>
          <el-button type="primary" @click="printLabel">打印标签</el-button>
          <el-checkbox
            label="全选"
            border
            class="margin-lr-sm"
            @change="selectAllChanged"
          />
        </span>
      </el-dialog>

      <el-dialog title="导入货架数据" :visible.sync="showImportGrid" center>
        <div style="text-align: center">
          <el-upload
            ref="upload"
            :action="uploadUrl"
            accept=".xlsx"
            :file-list="fileList"
            :auto-upload="false"
            :headers="headers"
            :on-success="uploadSuccess"
            :on-error="uploadError"
          >
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <a :href="tempUrl" target="_blank">下载模板</a>
            <div slot="tip" class="el-upload__tip">只能上传.xlsx文件</div>
          </el-upload>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showImportGrid = false">取消</el-button>
          <el-button type="success" @click="uploadShelfGridData">确定上传</el-button>
        </span>
      </el-dialog>
      <el-dialog
        v-loading="modelLoading"
        title="添加/编辑货架"
        :visible.sync="modelDialogShow"
      >
        <edit-shelf
          :model="editModel"
          :rooms="rooms"
          :areas="areas"
          :paths="paths"
          @save="saveShelf"
        />
      </el-dialog>
    </template>
  </base-list>
</template>
<script>
import BaseList from '@/components/Xyy/baselist'
import {
  QueryShelf,
  CreateShelf,
  GetShelf,
  UpdateShelf,
  DeleteShelf,
  DisableShelf,
  EnableShelf,
  LoadShelInfo
} from '@/api/stock/shelf'
import { getAllEnabledRooms } from '@/api/stock/room'
import { getAllEnabledRoomAreas } from '@/api/stock/roomArea'
import { getAllEnabledPaths } from '@/api/stock/path'
import { LoadShelfGridInfo, LoadGridInfoList } from '@/api/stock/shelfGrid'
import editShelf from './components/editShelf'
import GridMap from './components/gridMap'
import { getToken } from '@/utils/auth'
import { printGridLabel } from '@/utils/print'
export default {
  name: 'StockShelfList',
  components: { 'base-list': BaseList, GridMap, editShelf },
  data: function() {
    return {
      tempUrl: `${process.env.VUE_APP_DS_API}/Grid/DownTemplate`,
      fileList: [],
      uploadUrl: `${process.env.VUE_APP_DS_API}/Grid/ImportGrids`,
      showImportGrid: false,
      showGridMapModal: false,
      loadingGridInfos: true,
      modelLoading: false,
      modelDialogShow: false,
      paths: [],
      rooms: [],
      areas: [],
      options: [
        { value: true, label: '是' },
        { value: false, label: '否' }
      ],

      data: [],
      currentShelf: null,
      currentGridMapData: {},
      dataLoading: false,
      editModel: {},
      checkedGridIds: [],
      pagerDto: {
        PageIndex: 0,
        PageSize: 10,
        total: 0,
        _Eq_IsActive: '',
        QuerySort: [{ Field: 'UpdateTime', IsDesc: 'true' }]
      }
    }
  },
  computed: {
    headers() {
      const token = getToken()
      return {
        token: token
      }
    },
    mapTitle() {
      let title = '货架示意图'
      if (this.currentShelf) {
        title += `(货架：${this.currentShelf.Name})`
      }
      return title
    }
  },
  mounted() {
    this.pagerSerach(1)
    this.getAllRooms()
    this.getAllEnabledRoomAreas()
    this.getAllEnabledPaths()
  },
  methods: {
    selectAllChanged(e) {
      this.$refs.gridmap.checkAll(e)
    },
    directPrint(grid) {
      console.log(grid)
      const id = grid.Id
      const name = grid.Position
      const number = grid.GridNumber
      const printItem = { id, name, number }
      printGridLabel(printItem)
    },
    printLabel() {
      const gridMap = this.$refs.gridmap
      const checkedGrids = gridMap.getCheckedGrids()
      if (!checkedGrids || checkedGrids.length == 0) {
        this.$message({ message: '请先选择要打印的格口', type: 'error' })
        return
      }
      const items = checkedGrids.map((grid) => {
        const id = grid.Id
        const name = grid.Position
        const number = grid.GridNumber
        const printItem = { id, name, number }
        return printItem
      })
      for (const grid of items) {
        printGridLabel(grid)
      }
    },

    gridCancelChecked(id) {
      const idx = this.checkedGridIds.findIndex((i) => i == id)
      if (idx > -1) {
        this.checkedGridIds.splice(idx, 1)
      }
    },
    gridChecked(id) {
      const idx = this.checkedGridIds.findIndex((i) => i == id)
      if (idx == -1) {
        this.checkedGridIds.push(id)
      }
    },

    uploadShelfGridData() {
      this.$refs.upload.submit()
    },
    uploadSuccess(response, file, fileList) {
      const data = response.Data
      this.showImportGrid = false
      if (!!data && data.length > 0) {
        this.errorMsgs = data
      } else {
        this.$message({
          message: '导入成功',
          type: 'success'
        })
      }
    },
    uploadError(err, file, fileList) {
      this.showImportGrid = false
      this.$message({
        message: err.message,
        type: 'error'
      })
    },
    showGridMap(shelf) {
      this.currentShelf = shelf
      this.loadingGridInfos = true
      this.showGridMapModal = true
    },
    onShowGridMap() {
      const shelfId = this.currentShelf.Id
      LoadShelfGridInfo({ shelfId })
        .then((res) => {
          for (const r of res.Rows) {
            for (const c of r.RowGrids) {
              c.isChecked = false
            }
          }
          this.currentGridMapData = res
        })
        .catch(() => {
          console.log('err')
        })
        .finally(() => {
          this.loadingGridInfos = false
        })
    },
    pagerSerach(index) {
      this.dataLoading = true
      if (index) {
        this.pagerDto.PageIndex = index
      }
      QueryShelf(this.pagerDto)
        .then((res) => {
          this.data = res.Result
          this.pagerDto.total = res.TotalCount
        })
        .finally((res) => {
          this.dataLoading = false
        })
    },
    changePager(v) {
      this.PageSize = v
      this.pagerSerach()
    },
    changeEnable($event, rowId) {
      var that = this
      if ($event) {
        EnableShelf({ Id: rowId }).then((r) => {
          that.$message({ type: 'success', message: '启用成功' })
        })
      } else {
        DisableShelf({ Id: rowId }).then((r) => {
          that.$message({ type: 'success', message: '停用成功' })
        })
      }
    },
    showEditShelf(row) {
      this.editModel = row
      this.modelDialogShow = true
    },
    showAddShelf() {
      this.editModel = { Id: 0 }
      this.modelDialogShow = true
    },
    showDeleteShelf(m) {
      this.$confirm('是否删除该货架?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      })
        .then(() => {
          DeleteShelf({ id: m.Id }).then(() => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.pagerSerach()
          })
        })
        .catch(() => {})
    },
    getAllRooms() {
      getAllEnabledRooms().then((res) => {
        this.rooms = res
      })
    },
    getAllEnabledRoomAreas() {
      getAllEnabledRoomAreas().then((res) => {
        this.areas = res
      })
    },
    getAllEnabledPaths() {
      getAllEnabledPaths().then((res) => {
        this.paths = res
      })
    },
    saveShelf(m) {
      if (m.Id > 0) {
        this.modelLoading = true
        UpdateShelf(m)
          .then((x) => {
            this.$message({ type: 'success', message: '修改成功' })
            this.pagerSerach()
            this.modelDialogShow = false
          })
          .finally((r) => {
            this.modelLoading = false
          })
      } else {
        this.modelDialogShow = true
        this.modelLoading = true
        CreateShelf(m)
          .then((x) => {
            this.$message({ type: 'success', message: '添加成功' })
            this.pagerSerach()
            this.modelDialogShow = false
          })
          .finally((r) => {
            this.modelLoading = false
          })
      }
    }
  }
}
</script>
<style lang="scss" scoped></style>
