<template>
  <div style="margin-bottom: 10px">
    <el-config-provider :locale="zhCn">
      <el-row style="align-items: center;">
        <!-- <span>选择库区：</span>
        <el-select v-model="areaId" placeholder="请选择库区" style="width: 120px;" @change="getAllLocations">
            <el-option label="3楼库区" :value='1' />
            <el-option label="2楼库区" :value='2' />
        </el-select> -->
        <span style="margin-left: 5px;">状态说明：</span>
        <el-button color="green">空闲</el-button>
        <el-button color="red">占用</el-button>
        <el-button color="yellow">锁定</el-button>
        <el-tag style="margin-left: 15px;font-size: 20px;color: black" type="success" size="large">A: 毛坯区域 B: 待置区域
          C:半成品区域 D:空托盘区域
        </el-tag>
        <span style="margin-left: 20px;">层数选择：</span>
        <el-select v-model="chooseLayer" placeholder="层数选择" @change="getAllLocations">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
        <el-button type="primary" style="margin-left: 16px" @click="openDrawer = true">
          区域划分
        </el-button>
        <el-button type="warning" style="margin-left: 16px" @click="resetArea">
          重置区域
        </el-button>
        <el-button color="#00BFFF" style="margin: 0 0 0 auto;" @click="getAllLocations">刷新</el-button>
      </el-row>
      <hr style="border: 1px solid #ff0000"/>
      <div>
        <el-scrollbar max-height="900px" :native="true">
          <div v-for="currentRowLocation in allLocations" class="scrollbar-flex-content">
                        <span class="row" v-for="currentLayerLocation in currentRowLocation.currentLayerLocations">
                            <span class="col" v-for="currentColLocation in currentLayerLocation.currentColLocations">
                                <el-button :class="getStyle(currentColLocation)"
                                           :color="getLocationStatus(currentColLocation)"
                                           @click="showDialog(currentColLocation)">
                                   <el-icon style="position: relative; left: 3px"
                                            v-if="isException(currentColLocation)"><WarningFilled/></el-icon>
                                  <!--                                 <span   style="font-size: 13px;"> {{ currentColLocation.queue}}排{{ currentColLocation.line}}列{{ currentColLocation.layer}}层 -   {{ currentColLocation.wareArea}} </span>-->
                                 <span
                                     style="font-size: 13px;">  {{ currentColLocation.wareArea }} {{ currentColLocation.locationId.slice(1, 9) }}</span>
                                </el-button>
                                  <span v-if="currentColLocation.line >= 41 && currentColLocation.line < 43"
                                        style="width: 12px;height: 50px;margin-left: 19px"></span>
                                  <span v-if="currentColLocation.line >= 34 && currentColLocation.line < 36"
                                        style="width: 12px;height: 50px;margin-left: 19px"></span>
                                  <span v-if="currentColLocation.line >= 27 && currentColLocation.line < 29"
                                        style="width: 12px;height: 50px;margin-left: 19px"></span>
                                  <span v-if="currentColLocation.line >= 20 && currentColLocation.line < 22"
                                        style="width: 12px;height: 50px;margin-left: 19px"></span>
                                  <span v-if="currentColLocation.line >= 13 && currentColLocation.line < 15"
                                        style="width: 12px;height: 50px;margin-left: 19px"></span>
                            </span>
                        </span>
          </div>
        </el-scrollbar>
        <!-- 库位信息和物料信息弹出框             -->
        <el-dialog v-model="dialogVisible" :title="currentLocationTitle" width="30%" draggable :show-close="false">
          <el-tabs
              v-model="activeTabName"
              type="card"
              class="demo-tabs"
              @tab-click="handleTabClick"
          >
            <el-tab-pane label="库位信息" name="location">
              <el-form :model="location">
                <el-form-item label="库位号" :label-width="140">
                  <el-input v-model="this.currentSelectedLocation.locationId" style="width: 70%;" readonly/>
                </el-form-item>
                <el-form-item label="占用/解除占用库位" :label-width="140">
                  <el-select v-model="location.locationStatus" placeholder="库位是否占用" style="width: 70%;">
                    <el-option label="空闲" :value='0'/>
                    <el-option label="占用" :value='1'/>
                  </el-select>
                </el-form-item>
                <el-form-item label="锁定/解锁库位" :label-width="140">
                  <el-select v-model="location.isLock" placeholder="库位是否锁定" style="width: 70%;">
                    <el-option label="解锁" :value='0'/>
                    <el-option label="锁定" :value='1'/>
                  </el-select>
                </el-form-item>
                <el-form-item label="载具" :label-width="140">
                  <el-input v-model="location.vehicleId" style="width: 70%;"/>
                </el-form-item>
                <el-form-item label="库区选择" :label-width="140">
                  <el-select v-model="location.wareArea" placeholder="选择库区" style="width: 70%;">
                    <el-option label="毛坯区域" value="A"/>
                    <el-option label="待置区域" value="B"/>
                    <el-option label="半成品区域" value="C"/>
                    <el-option label="空托盘区域" value="D"/>
                  </el-select>
                </el-form-item>
                <el-form-item label="移库交换区域" :label-width="140">
                  <el-select v-model="location.isChangeArea" style="width: 70%;">
                    <el-option label="否" :value="0"/>
                    <el-option label="是" :value="1"/>
                  </el-select>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="物料信息" name="stock">
              <el-form :model="stock">
                <el-form-item label="托盘号" :label-width="140">
                  <el-input v-model="stock.vehicleId" style="width: 70%;"/>
                </el-form-item>
                <el-form-item label="物料号" :label-width="140">
                  <el-input v-model="stock.goodsId" style="width: 70%;"/>
                </el-form-item>
                <el-form-item label="数量" :label-width="140">
                  <el-input v-model="stock.availableNum" style="width: 70%;"/>
                </el-form-item>
                <el-form-item label="规格描述" :label-width="140">
                  <el-input v-model="stock.goodsName" style="width: 70%;"/>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="托盘信息" name="vehicle">
              <el-form :model="vehicle">
                <el-form-item label="托盘号" :label-width="140">
                  <el-input v-model="vehicle.vehicleId" style="width: 70%;"/>
                </el-form-item>
                <el-form-item label="托盘当前位置" :label-width="140">
                  <el-input v-model="vehicle.currentLocation" style="width: 70%;"/>
                </el-form-item>
                <el-form-item label="托盘状态" :label-width="140">
                  <el-select v-model="vehicle.vehicleStatus" placeholder="区域选择" @change="getAllLocations">
                    <el-option
                        v-for="item in vehicleStatusOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="是否是空托盘" :label-width="140">
                  <el-select v-model="vehicle.isEmpty" placeholder="区域选择" @change="getAllLocations">
                    <el-option
                        v-for="item in emptyOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
          <template #footer>
                          <span class="dialog-footer">
                              <el-button @click="dialogVisible = false">取消</el-button>
                              <el-button v-if="activeTabName == 'location'" type="primary"
                                         @click="submitLocationStatus()">
                                    更新库位信息
                              </el-button>
                               <el-button v-if="activeTabName == 'stock'" type="primary">
                                  <span v-if="isAddStock" @click="handleAddStock">
                                    添加物料信息
                                  </span>
                                  <span v-else @click="handleAddStock">
                                      更新物料信息
                                  </span>
                              </el-button>
                               <el-button v-if="activeTabName == 'vehicle'" type="primary"
                                         >
                                  <span v-if="isAddVehicle" @click="addVehicle">
                                    添加托盘信息
                                  </span>
                                 <span v-else  @click="updateCurrentVehicleInfo">
                                    更新托盘信息
                                  </span>
                              </el-button>
                          </span>
          </template>
        </el-dialog>
      </div>
    </el-config-provider>
    <!--区域选择 -->
    <el-drawer v-model="openDrawer" :direction="direction">
      <template #header>
        <h4>区域划分</h4>
      </template>
      <template #default>
        <div>
          <el-form ref="areaForm" :model="areaForm" label-width="100px">
            <el-form-item label="区域选择">
              <el-select v-model="areaForm.chooseArea" placeholder="区域选择" @change="getAllLocations">
                <el-option
                    v-for="item in areaOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="开始排">
              <el-input v-model="areaForm.startQueue" placeholder="请输入排编号（如13）"></el-input>
            </el-form-item>
            <el-form-item label="结束排">
              <el-input v-model="areaForm.endQueue" placeholder="请输入排编号（如13）"></el-input>
            </el-form-item>
            <el-form-item label="开始列">
              <el-input v-model="areaForm.startLine" placeholder="请输入列编号（如42）"></el-input>
            </el-form-item>
            <el-form-item label="结束列">
              <el-input v-model="areaForm.endLine" placeholder="请输入列编号（如42）"></el-input>
            </el-form-item>
            <el-form-item label="开始层">
              <el-input v-model="areaForm.startLayer" placeholder="请输入层编号（如02）"></el-input>
            </el-form-item>
            <el-form-item label="结束层">
              <el-input v-model="areaForm.endLayer" placeholder="请输入层编号（如02）"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancelClick">取消</el-button>
          <el-button type="primary" @click="confirmClick">确认划分</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import {getLocations, updateLocation} from '@/api/location.js'
import {ElMessage, ElLoading} from 'element-plus'
import {reactive} from 'vue'
</script>
<script>
import {reactive} from "vue";
import {addStockInfo, getAllStocks, getStockByLocation, updateStockInfo} from "@/api/stock";
import {ElLoading, ElMessage} from "element-plus";
import {getStockList, getVehicleList, updateArea} from "@/api/location";
import {addVehicleInfo, getAllVehicles, getVehiclesByLocation, updateVehicleInfo} from "@/api/vehicle";

export default {
  name: 'location',
  data() {
    return {
      vehicle: {},
      stockList: [],
      vehicleList: [],
      vehicleStatusOptions: [{
        value: 1,
        label: '入库中'
      }, {
        value: 2,
        label: '在库中',
      }, {
        value: 3,
        label: '出库中',
      }],
      emptyOptions: [{
        value: 1,
        label: '空托盘'
      }, {
        value: 0,
        label: '非空托盘'
      }],
      areaOptions: [{
        value: 'A',
        label: '毛坯区域'
      }, {
        value: 'B',
        label: '待置区域'
      }, {
        value: 'C',
        label: '半成品区域'
      },
        {
          value: 'D',
          label: '空托盘区域'
        }],
      areaForm: {},
      direction: 'rtl',
      openDrawer: false,
      isAddStock: true,
      isAddVehicle: true,
      stock: {},
      activeTabName: 'location',
      options: [{
        value: 1,
        label: '第一层'
      }, {
        value: 2,
        label: '第二层'
      }, {
        value: 3,
        label: '第三层'
      }, {
        value: 4,
        label: '第四层'
      }],
      chooseLayer: 1,
      dialogVisible: false,
      currentSelectedLocation: {},
      allLocations: [],
      location: reactive({
        locationId: 'this.currentSelectedLocation.locationId',
        locationStatus: '',
        isLock: '',
        vehicleId: '',
        wareArea: '',
        isChangeArea: 0
      }),
      currentLocationTitle: '',
      areaId: 1
    }
  },
  mounted() {
    this.getAllLocations()
    this.getAllStock()
    this.getAllVechicle()
  },
  methods: {
    addVehicle(){
      addVehicleInfo(this.vehicle).then(res =>{
        if (res.data.code == 0) {
          ElMessage.success(res.data.message)
        } else {
          ElMessage.error(res.data.message)
        }
      }).catch(err => {
        ElMessage.error('添加托盘信息失败！', err)
      })
    },
    getAllStock() {
      getStockList().then(res => {
        if (res.data.code == 0) {
          ElMessage.success(res.data.message)
          this.stockList = res.data.returnData
        } else {
          ElMessage.error(res.data.message)
        }
      }).catch(err => {
        ElMessage.error('查询所有托盘信息失败！', err)
      })
    },
    getAllVechicle() {
      getVehicleList().then(res => {
        if (res.data.code == 0) {
          ElMessage.success(res.data.message)
          this.vehicleList = res.data.returnData;
        } else {
          ElMessage.error(res.data.message)
        }
      }).catch(err => {
        ElMessage.error('查询所有托盘信息失败！', err)
      })
    },
    isException(locationInfo) {
      if (locationInfo.locationStatus == 1) {
        const vehicleList = this.vehicleList.filter(item => item.currentLocation == locationInfo.locationId)
        const stockList = this.stockList.filter(item => item.locationId == locationInfo.locationId)
        if (vehicleList.length == 0 || stockList.length == 0) {
          return true
        }
      } else {
        return false
      }

    },
    updateCurrentVehicleInfo() {
      updateVehicleInfo(this.vehicle).then(res => {
        if (res.data.code == 0) {
          ElMessage.success(res.data.message)
          this.getCurrentVehicleInfo(this.currentSelectedLocation.locationId)
        } else {
          ElMessage.error(res.data.message)
        }
      }).catch(err => {
        ElMessage.error('更新托盘信息失败！', err)
      })
    },
    getCurrentVehicleInfo(locationId) {
      getVehiclesByLocation({locationId: locationId}).then(res => {
        if (res.data.code === 0) {
          this.vehicle = res.data.returnData
          if (res.data.returnData.length > 0){
            this.isAddVehicle = false
          }
        } else {
          ElMessage.error(res.data.message)
          this.isAddVehicle = true
          this.vehicle = {}
        }
      }).catch(err => {
        ElMessage.error('查询托盘信息失败！', err)
      })
    },
    resetArea() {
      updateArea({chooseArea: 'reset'}).then(res => {
        if (res.data.code == 0) {
          this.dialogVisible = false
          ElMessage({
            message: '重置成功！',
            type: 'success',
          })
          this.getAllLocations()
        } else {
          ElMessage.error(res.data.message)
        }
      }).catch(err => {
        ElMessage.error('重置失败', err)
      })
    },
    getStyle(val) {
      let colorClass = [];
      if (val.wareArea === 'A') {
        colorClass.push('red-text');
      } else if (val.wareArea === 'B') {
        colorClass.push('green-text');
      } else if (val.wareArea === 'C') {
        colorClass.push('blue-text');
      } else if (val.wareArea === 'D') {
        colorClass.push('purple-text');
      }
      if (val.isChangeArea == 1) {
        colorClass.push('change-area-style')
      }
      return colorClass;
    },
    cancelClick() {
      this.openDrawer = false
    },
    confirmClick() {
      updateArea(this.areaForm).then(res => {
        if (res.data.code == 0) {
          this.dialogVisible = false
          ElMessage({
            message: '划分区域成功！',
            type: 'success',
          })
          this.getAllLocations()
        } else {
          ElMessage.error(res.data.message)
        }
      }).catch(err => {
        ElMessage.error('划分失败', err)
      })
    },
    handleAddStock() {
      if (this.isAddStock) {
        this.stock.locationId = this.location.locationId
        addStockInfo(this.stock).then(res => {
          if (res.data.code == 0) {
            this.dialogVisible = false
            ElMessage({
              message: '添加物料信息成功！',
              type: 'success',
            })
            this.getAllLocations()
          } else {
            ElMessage.error(res.data.message)
          }
        }).catch(err => {
          ElMessage.error('添加物料信息失败！', err)
        })
      } else {
        updateStockInfo(this.stock).then(res => {
          if (res.data.code == 0) {
            this.dialogVisible = false
            ElMessage({
              message: '更新物料信息成功！',
              type: 'success',
            })
            this.getAllLocations()
          } else {
            ElMessage.error(res.data.message)
          }
        }).catch(err => {
          ElMessage.error('更新物料信息失败！', err)
        })
      }

    },
    handleTabClick(tab, event) {
      console.log(tab, event)
    },
    getLocationStatus: (currentColLocation) => {
      if (currentColLocation.isLock === 1) {
        return 'yellow'
      }
      if (currentColLocation.locationStatus === 1) {
        return 'red'
      }
      return 'green'
    },
    getStockLocation(locationId) {
      getStockByLocation({locationId: locationId}).then(res => {
        if (res.data.code == 0) {
          this.isAddStock = false
          this.stock = res.data.returnData
        } else {
          this.isAddStock = true
          this.stock = {}
        }
      }).catch(err => {
        loading.close()
        ElMessage.error('查询库存信息失败！')
      })
    },
    getAllLocations() {
      const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      const data = {areaId: this.areaId, layer: this.chooseLayer}
      getLocations(data).then(res => {
        loading.close()
        let sum = 0
        if (res.data.code == 0) {

          this.allLocations = res.data.returnData
        } else {
          ElMessage.error(res.data.message)
        }
      }).catch(err => {
        loading.close()
        ElMessage.error('查询库位失败！')
      })
    },
    showDialog(currentColLocation) {
      this.dialogVisible = true
      this.currentSelectedLocation = currentColLocation
      this.getStockLocation(this.currentSelectedLocation.locationId)
      this.getCurrentVehicleInfo(this.currentSelectedLocation.locationId)
      this.setCurrentLocationTitle()
      this.location.locationId = this.currentSelectedLocation.locationId
      this.location.locationStatus = this.currentSelectedLocation.locationStatus
      this.location.isLock = this.currentSelectedLocation.isLock
      this.location.vehicleId = this.currentSelectedLocation.vehicleId
      this.location.wareArea = this.currentSelectedLocation.wareArea
      this.location.isChangeArea = this.currentSelectedLocation.isChangeArea
    },
    submitLocationStatus() {
      const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      this.currentSelectedLocation.locationId = this.location.locationId
      this.currentSelectedLocation.locationStatus = this.location.locationStatus
      this.currentSelectedLocation.isLock = this.location.isLock
      this.currentSelectedLocation.vehicleId = this.location.vehicleId
      this.currentSelectedLocation.wareArea = this.location.wareArea
      this.currentSelectedLocation.isChangeArea = this.location.isChangeArea
      updateLocation(this.currentSelectedLocation).then(res => {
        if (res.data.code == 0) {
          loading.close()
          this.dialogVisible = false
          ElMessage({
            message: '更新库位信息成功！',
            type: 'success',
          })
          this.getAllLocations()
        } else {
          ElMessage.error(res.data.message)
        }
      }).catch(err => {
        loading.close()
        ElMessage.error('更新库位信息失败')
      })
    },
    setCurrentLocationTitle() {
      const parts = this.currentSelectedLocation.locationId.split('-');
      this.currentLocationTitle = '当前选择库位：' + parts[0] + '排' + parts[1] + '列' + parts[2] + '层';
      //this.currentLocationTitle = '当前选择库位：' + this.currentSelectedLocation.queue + '排' + this.currentSelectedLocation.line + '列' + this.currentSelectedLocation.layer + '层' +  '(' + this.currentSelectedLocation.warearea + ')'
    }
  }
}
</script>

<style scoped>
.el-pagination {
  padding-left: 5px;
}

.row {
//display: flex; //justify-content: space-between; margin: 5px;
}

.col {
  /* width: 100px; */
  /* height: 40px; */
  padding: 1px;
  margin: 1px;
}

.col .el-button {
  width: 100px;
  height: 50px;
  padding: 4px;
}

.scrollbar-flex-content {
  display: flex;
}

.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

.red-text {
  color: white;
}

.green-text {
  color: black;
}

.blue-text {
  color: blue;
}

.purple-text {
  color: purple;
}

.change-area-style {
  border: 4px solid black;
}
</style>
