<template>
  <div>
    <el-form :model="formData" style="width: 100%;" ref="dataForm" :rules="formRules"
             label-width="auto"
    >
      <el-row :gutter="24">
        <el-col :span="12" class="el-col">
          <el-form-item label="货架编码:" prop="code" class="query-form-item">
            <el-input
              v-model="formData.code" style="width: 80%"
              auto-complete="off"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="el-col">
          <el-form-item label="货架说明:" class="query-form-item">
            <el-input
              :disabled="remarkStatus"
              v-model="formData.name" style="width: 80%"
              auto-complete="off"
              placeholder="请输入货架名称"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12" class="el-col">
          <el-form-item label="所属工位:" class="query-form-item" prop="workPlaceIdFk">
            <el-select
              disabled
              v-model="formData.workPlaceIdFk"
              filterable
              remote
              style="width: 80%"
              placeholder="请输入选择所属工位"
            >
              <el-option
                v-for="item in workPlaces"
                :key="item.code"
                :label="item.label"
                :value="item.code"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="el-col">
          <el-form-item label="是否启用单品种槽位:" class="query-form-item">
              <el-select v-model="formData.isSingQueue" style="width: 80%" placeholder="请选择是否启用单品种槽位"
              >
                <el-option label="否" :value="0"></el-option>
                <el-option label="是" :value="1"></el-option>
              </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
      <el-col :span="12" class="el-col">
       <!--<el-form-item label="区域编码:" prop="freightRow" class="query-form-item">-->
       <!--       <el-input-number-->
       <!--         v-model="formData.freightRow" style="width: 80%"-->
       <!--         auto-complete="off"-->
       <!--         :min="1"-->
       <!--         :max="30"-->
       <!--       ></el-input-number>-->
       <!--     </el-form-item>-->

        <el-form-item label="区域编码:" prop="freightRow" class="query-form-item">
          <el-select v-model="formData.freightRow" filterable placeholder="请选择"  style="width: 80%">
            <el-option
              v-for="item in regions"
              :key="item.regionCode"
              :label="item.regionName"
              :value="item.regionCode">
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>

      <!--  <el-col :span="12" class="el-col">-->
      <!--    <el-form-item label="备注:" prop="remake" class="query-form-item">-->
      <!--      <el-input-->
      <!--        v-model="formData.remark" style="width: 80%"-->
      <!--        auto-complete="off"-->
      <!--      ></el-input>-->
      <!--    </el-form-item>-->
      <!--  </el-col>-->
      </el-row>
    </el-form>
    <div style="float: right;margin-bottom: 10px">
      <el-button-group>
        <el-button type="primary" icon="el-icon-plus" @click="addWorkplaceLayer">新增摆货层</el-button>
      </el-button-group>
    </div>
    <el-table v-loading="loading" :data="layerList" style="width: 100%" :row-style="{height: '32px' }"
              highlight-current-row @current-change="handCurrentChange"
    >
      <el-table-column type="index" label="序号"></el-table-column>
      <el-table-column label="摆货层编号" prop="code"></el-table-column>
      <el-table-column label="摆货层名称" prop="layerName">
        <template slot-scope="scope">
          <div style="display: flex; justify-content: center; align-items: center; width: 100%;">
            <el-input
              size="small"
              v-model="scope.row.layerName"
              style="width: 100%"
              :disabled="scope.$index !== selectedIndex"
            ></el-input>
          </div>
        </template>
      </el-table-column>

      <!--<el-table-column label="摆货层高度" prop="height">-->
      <!--  <template slot-scope="scope">-->
      <!--    <div style="display: flex; justify-content: center; align-items: center; width: 80%;">-->
      <!--      <el-input-->
      <!--        size="small"-->
      <!--        v-model="scope.row.height"-->
      <!--        style="width: 100%"-->
      <!--        type="number"-->
      <!--        :disabled="scope.$index !== selectedIndex"-->
      <!--      ></el-input>-->
      <!--    </div>-->
      <!--  </template>-->
      <!--</el-table-column>-->
      <el-table-column label="出货槽数量" prop="queueNum">
        <template slot-scope="scope">
          <div style="display: flex; justify-content: center; align-items: center; width: 100%;">
            <el-input
              size="small"
              v-model="scope.row.queueNum"
              style="width: 100%"
              type="number"
              :disabled="scope.$index !== selectedIndex"
            ></el-input>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="操作" fixed="right" width="100">
        <template slot-scope="scope">
          <!--<el-button-->
          <!--  type="text"-->
          <!--  size="small"-->
          <!--  @click.native.stop="handleEdit(scope.row)"-->
          <!--&gt;编辑-->
          <!--</el-button>-->
          <el-button type="text" size="small" v-if="scope.$index == selectedIndex " @click.stop="true"
                     @click.native="handleSave(scope.row)"
          >保存
          </el-button>
          <el-button
            type="text"
            size="small"
            v-if="scope.$index != selectedIndex "
            @click.stop="true"
            @click.native="handleEdit(scope.$index,scope.row)"
          >编辑
          </el-button>
          <el-button
            type="text"
            size="small"
            @click.native.stop="handleDel(scope.$index, scope.row)"
          >删除
          </el-button
          >
        </template>

      </el-table-column>
      <!--<el-table-column label="货架名称" prop="name" ></el-table-column>-->
      <!--<el-table-column label="创建时间" prop="createTime" ></el-table-column>-->
      <!--<el-table-column label="备注" prop="remark"></el-table-column>-->
    </el-table>
    <div slot="footer" class="dialog-footer" style="margin-top: 50px">
      <el-button @click.native="hideForm">取消</el-button>
      <el-button
        type="primary"
        @click.native="formSubmit()"
      >提交
      </el-button
      >
    </div>
  </div>
</template>

<script>
import { filterWorkOptimize } from '@/api/basic/workPlace/sysWorkplaceManage'
import {
  addWorkplaceFreight,
  createFreightCode,
  updateWorkplaceFreight
} from '@/api/basic/workPlace/SysWorkplaceFreight'
import { deleteLayer, getLayerCode, getLayerList, saveLayer } from '@/api/basic/workPlace/SysWorkplaceLayer'
import { isBlank } from '@/utils/strUtil'
import { getRegions } from '@/api/basic/workPlace/regionManage'

export default {
  props: {
    closeDialog: {
      type: Function,
      required: true
    },
    rowData: {
      type: Object,
      required: true
    },
    workplaceId: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      formData: {
        code: '',
        name: '',
        remark: null,
        workPlaceIdFk: '',
        freightRow: null,
        isSingQueue: 1
      },
      freightData: null,
      workPlaces: [],
      formRules: {
        // name: [
        //   { required: true, message: '请输入货架说明', trigger: 'blur' }
        // ],
        workPlaceIdFk: [
          { required: true, message: '请选择所属工位', trigger: 'blur' }
        ]
      },
      LayerQuery: {
        page: 1,
        limit: 10,
        freightCode: ''
      },
      layerList: [],
      saveStatus: false, //记录保存状态
      selectedIndex: null,//记录下标位置
      remarkStatus: false,
      //区域
      regions:[],
      regionQuery:{
        page:1,
        limit:10
      },
      // {
      //   code:null,
      //     queueNum:null,
      // }
    }
  },
  methods: {
    findWorkPlace(val) {
      let query = {
        // chargeUser: _this.$store.getters.userId,
        userIdFlag: true,
        key: val,
        page: 1,
        limit: 10,
        workPlaceClass: 2
      }
      filterWorkOptimize(query)
        .then((response) => {
          this.workPlaces = response.data || []
        })
        .catch(() => {
          this.options.getWorkPlaceList = []
        })
    },
    getCode() {
      createFreightCode().then(res => {
        if (res.code == 20000) {
          this.formData.code = res.data
        } else {
          this.formData = ''
        }
      })
    },
    formSubmit() {
      if (this.layerList.length == 0){
        return this.$message.error("请增加摆货层")
      }
      if(this.layerList.length > 0){
        let layerData = this.layerList[this.layerList.length - 1]
        if (layerData.queueNum == null || layerData.queueNum == 0){
          return this.$message.error("请设置当前" +layerData.code + "出货槽数量")
        }
        if (this.saveStatus == true){
          return this.$message.error("请保存数据")
        }
      }

      // this.formData.workPlaceIdFk = this.workplaceId
      this.$refs['dataForm'].validate((rules) => {
        if (rules) {
          if (this.rowData != null) {
            updateWorkplaceFreight(this.formData).then(res => {
              if (res.code == 20000) {
                this.$message.success('成功')
                this.closeDialog()
              } else {
                this.$message.error(res.message)
              }
            })
          } else {
            this.closeDialog()
          }

        }
      })
    },
    hideForm() {
      this.closeDialog()
    },

    //新增摆货层
    addWorkplaceLayer() {
      // if (isBlank(this.formData.remark)){
      //   return this.$message.error('请输入货架说明')
      // }
      if (this.saveStatus == true){
        return this.$message.error('请完成编辑摆货层')
      }
      //摆货层列表
      if (this.layerList.length == 0) {
        getLayerCode({ freightCode: this.formData.code }).then(res => {
          if (res.code == 20000) {
            this.layerList.push({
              code: res.data,
              queueNum: null,
              layerName:""
            })
          } else {
            this.$message.error('系统繁忙')
          }
        })
      } else {
        //不为空
        let lastLayer = this.layerList[this.layerList.length - 1]
        if (lastLayer.queueNum == null || lastLayer.queueNum == 0) {
          return this.$message.error('请编辑上层摆货层出货槽数量')
        }
        let code = this.createLayerCode(lastLayer)
        this.layerList.push({
          code: code,
          queueNum: null,
          layerName:""
        })
      }

      // this.addStatus = true
    },
    createLayerCode(lastLayer) {
      let code
      code = lastLayer.code.slice(lastLayer.code.indexOf('-') + 1);
      code = parseInt(code, 10) + 1
      let incrementedValue = code.toString().padStart(2, '0')
      code = this.formData.code + "-" +  incrementedValue
      return code

    },
    //编辑
    handleEdit(index, val) {
      if (this.saveStatus == true) {
        this.$message.error('请先保存当前摆货层')
        return
      }
      this.selectedIndex = index
      this.saveStatus = true
    },
    handleSave(row) {
      if (row.queueNum == null || row.queueNum == 0) {
        return this.$message.error('请输入出货槽数量')
      }
      row.freightCode = this.formData.code
      row.workPlaceIdFk = this.formData.workPlaceIdFk
      row.name = this.formData.name
      row.isSingQueue = this.formData.isSingQueue
      row.freightRow = this.formData.freightRow
      this.remarkStatus = true
      saveLayer(row).then(res => {
        if (res.code == 20000){
          this.selectedIndex = null
          this.saveStatus = false
          // this.closeDialog()
          this.$message.success("保存成功!")
        }
      })
    },
    getLayers() {
      this.LayerQuery.freightCode = this.formData.code
      getLayerList(this.LayerQuery).then(res => {
        if (res.code == 20000) {
          this.layerList = res.data.list || []
        } else {
          this.layerList = []
        }
      })
    },
    handleDel(index,row){
      if (this.saveStatus == true){
        return this.$message.error("请保存数据")
      }
      let query = {
        code : row.code
      }
      this.$confirm('此操作将永久删除该摆货层及出货槽, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteLayer(query).then(res => {
          if (res.code == 20000){
            this.getLayers()
            this.$message.success("删除成功")
          }else if (res.code == 501){
           this.layerList.splice(index, 1);
          }else {
            this.$message.error("删除失败")
          }
        })
      }).catch(() => {

      })

    },
    getRegionList(){
      getRegions(this.query).then(res => {
        if (res.code == 20000){
          this.regions = res.data.list
        }
      })
    },
  },
  created() {
    if (this.rowData != null) {
      this.formData = this.rowData
      if (this.rowData.isSingQueue == null){
        this.formData.isSingQueue = 1
      }
      this.formData.workPlaceIdFk = String(this.rowData.workPlaceIdFk)
      this.getLayers()
    } else {
      this.formData.workPlaceIdFk = String(this.workplaceId)
      this.getCode()
    }
    this.findWorkPlace('')
    this.getRegionList()

  }
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
}
</style>
