<template>
  <ele-modal :visible.sync="visible" :close-on-click-modal="false"  title="货位管理" width="60%" @close="cancel">


    <el-form ref="form" :model="form" :rules="rules" label-width="140px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="层数" prop="levelNum">
            <el-input v-model="form.levelNum" :disabled="form.positionList.length != 0" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="列数" prop="lineNum">
            <el-input v-model="form.lineNum" :disabled="form.positionList.length != 0" />
          </el-form-item>
        </el-col>


        <el-col :span="8">
          <el-form-item label="长" prop="vehicleLen">
            <el-input v-model="form.vehicleLen" :disabled="form.positionList.length != 0">
              <template slot="append">cm</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="宽" prop="wilde">
            <el-input v-model="form.wilde" :disabled="form.positionList.length != 0">
              <template slot="append">cm</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="高" prop="hight">
            <el-input v-model="form.hight" :disabled="form.positionList.length != 0">
              <template slot="append">cm</template>
            </el-input>
          </el-form-item>
        </el-col>


        <el-col :span="8">
          <el-form-item>
            <el-button size="small" v-if="form.positionList.length == 0" type="primary"
              @click="handleHjCode">生成货位</el-button>
            <el-button size="small" v-else type="primary" @click="addHjCode">添加货位</el-button>
          </el-form-item>

        </el-col>
      </el-row>
    </el-form>


    <el-form :model="form" ref="tableForm" class="tableForm" :rules="tableFormRules">
      <el-table ref="multipleTable" :data="form.positionList" tooltip-effect="dark" style="width: 100%" stripe
        :header-cell-style="{ background: '#EEEEEE', border: 'none' }">


        <el-table-column label="货位编号" prop="code" min-width="120">
          <template slot-scope="{ row, $index }">
            <el-form-item :prop="'positionList.' + $index + '.code'" :rules="tableFormRules.code">
              <el-input placeholder="请输入" clearable v-model="row.code"></el-input>
            </el-form-item>

          </template></el-table-column>
        <el-table-column label="货位长(cm)" min-width="120">
          <template slot-scope="scope">
            <el-form-item :prop="'positionList.' +
              scope.$index +
              'length'
              " :rules="tableFormRules.length">
              <el-input placeholder="请输入" type="number" v-model.number="scope.row.length
                " clearable></el-input>
            </el-form-item>

          </template>
        </el-table-column>
        <el-table-column label="货位宽(cm)" min-width="120">
          <template slot-scope="scope">
            <el-form-item :prop="'positionList.' +
              scope.$index +
              '.breadth'
              " :rules="tableFormRules.breadth">
              <el-input placeholder="请输入" type="number" v-model.number="scope.row.breadth"></el-input>
            </el-form-item>

          </template>
        </el-table-column>
        <el-table-column label="货位高(cm)" min-width="120">
          <template slot-scope="scope">
            <el-form-item :prop="'positionList.' +
              scope.$index +
              '.altitude'
              " :rules="tableFormRules.altitude">
              <el-input placeholder="请输入" type="number" v-model.number="scope.row.altitude"></el-input>
            </el-form-item>

          </template>
        </el-table-column>
        <el-table-column label="限重(kg)" min-width="120">
          <template slot-scope="scope">
            <el-form-item :prop="'positionList.' +
              scope.$index +
              '.weightLimit'
              " :rules="tableFormRules.weightLimit">
              <el-input placeholder="请输入" type="number" v-model.number="scope.row.weightLimit"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="基本货位容积(cm³)" min-width="120">
          <template slot-scope="scope">
            <el-form-item :prop="'positionList.' +
              scope.$index +
              '.volume'
              " :rules="tableFormRules.volume">
              <el-input placeholder="请输入" type="number" v-model.number="scope.row.volume"></el-input>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column label="操作" fixed="right">
          <template slot-scope="{ $index, row }">
            <el-button type="text" @click="removeGoods($index, row)">删除货架</el-button>
          </template>
        </el-table-column>


      </el-table>
    </el-form>


    <div slot="footer" class="footer">
      <el-button type="primary" @click="save">保存</el-button>
      <el-button @click="cancel">取消</el-button>
    </div>


    <!-- 规则货架编号 -->
    <el-dialog title="规则货架编号" append-to-body :visible.sync="hjCodeFalg" width="35%">
      <el-form :model="hjForm">
        <el-form-item label="规则类型" label-width="100px">
          <el-radio-group v-model="hjForm.type">
            <el-radio :label="1">字母</el-radio>
            <el-radio :label="2">字母+数字</el-radio>
            <el-radio :label="3">字母+数字(层级)</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="规则名称定义" label-width="100px">
          <el-input v-model="hjForm.code" @input="handleInput"></el-input>
          <span style="color: #dab8b8">注：只可输入大写A-Z</span>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="hjCodeFalg = false">取 消</el-button>
        <el-button @click="handleMine" type="primary">确 定</el-button>
      </span>
    </el-dialog>


  </ele-modal>
</template>
  
<script>
import { categoryVehicle, categoryVehicleList } from '@/api/material/product';
export default {

  data() {
    const defaultForm = {
      categoryId: null,
      levelNum: null,
      lineNum: null,
      hight: null,
      wilde: null,
      vehicleLen: null,
      positionList: [],
      removeIds: []
    };

    return {
      visible: false,

      form: {
        ...defaultForm
      },


      hjCodeFalg: false,

      hjForm: { code: '', type: 1 },

      rules: {
        levelNum: [
          { required: true, message: '请输入层数', trigger: 'blur' }
        ],
        lineNum: [
          { required: true, message: '请输入列数', trigger: 'blur' }
        ],
      },

      tableFormRules: {
        code: {
          required: true,
          message: '请输入货位编号',
          trigger: 'blur'
        },
      }

    };
  },
  created() {

  },
  computed: {




  },
  methods: {
    open(row) {


      this.visible = true;


      this.form.categoryId = row.id
      this.getList()
    },
    cancel() {
      this.$refs.form.clearValidate();
      this.form = { ...this.defaultForm };
      this.form.positionList = []
      this.visible = false;



    },

    getList() {
      categoryVehicleList(this.form.categoryId).then(res => {
        if (res) {
          this.form = res
          this.form['removeIds'] = []
        }
      })
    },

    removeGoods(idx, row) {
      if (this.form.positionList.length == 1) {
        return this.$message.error('至少保留一个货架！');
      }

      this.$confirm(`是否删除这个货架？`).then(async () => {
        this.form.positionList.splice(idx, 1)


        this.form['removeIds'].push(row.id)

      })
    },

    handleHjCode() {

      this.$refs.form.validate((valid) => {
        if (valid) {
          this.hjCodeFalg = true;
        }
      })


    },


    addHjCode() {
      this.$prompt('请输入', '添加货位数', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /[1-9]\d*/,
        inputErrorMessage: '请输入正整数'
      }).then(({ value }) => {

        for (var i = 0; i < value; i++) {
          let obj1111 = {
            code: '',
            length: this.form.vehicleLen ? Number(this.form.vehicleLen / Number(this.form.lineNum)).toFixed(0) : '',
            breadth: this.form.wilde,
            altitude: this.form.hight ? Number(this.form.hight / Number(this.form.levelNum)).toFixed(0) : '',
            weightLimit: '',
            volume: ''
          };

          this.form.positionList.push(obj1111)
        }
      }).catch(() => {



      });
    },

    handleMine() {
      this.$refs.form.clearValidate()
      const ruleName = this.hjForm.code;
      let preCode = 0;
      let codeEng = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
      let currentLetterIndex = 0;
      this.form.positionList = []

      if (ruleName.length > 0) {
        // 计算初始索引
        let multiplier = Math.pow(codeEng.length, ruleName.length - 1);
        for (let i = 0; i < ruleName.length; i++) {
          currentLetterIndex +=
            (codeEng.indexOf(ruleName[i]) + 1) * multiplier;
          multiplier /= codeEng.length;
        }
      }


      if (this.hjForm.type == 3) {
        for (let i = 0; i < this.form.lineNum; i++) {
          // 获取当前字母
          let index = currentLetterIndex;
          let dividend = codeEng.length;
          let remainder;
          let quotient;
          let code = '';


          while (index > 0) {
            remainder = index % dividend;
            quotient = Math.floor(index / dividend);

            if (remainder === 0) {
              remainder = codeEng.length;
              quotient--;
            }
            code = codeEng[remainder - 1] + code;
            index = quotient;
          }

          for (let j = 0; j < this.form.levelNum; j++) {
            let obj1111 = {
              code: code + (j + 1),
              length: this.form.vehicleLen ? Number(this.form.vehicleLen / Number(this.form.lineNum)).toFixed(0) : '',
              breadth: this.form.wilde,
              altitude: this.form.hight ? Number(this.form.hight / Number(this.form.levelNum)).toFixed(0) : '',
              weightLimit: '',
              volume: ''
            };

            this.form.positionList.push(obj1111)



          }



          currentLetterIndex++; // 自增索引
          this.hjCodeFalg = false
        }

      } else {
        let num = Number(this.form.levelNum) * Number(this.form.lineNum)


        for (let i = 0; i < num; i++) {
          // 获取当前字母
          let index = currentLetterIndex;
          let dividend = codeEng.length;
          let remainder;
          let quotient;
          let code = '';


          while (index > 0) {
            remainder = index % dividend;
            quotient = Math.floor(index / dividend);

            if (remainder === 0) {
              remainder = codeEng.length;
              quotient--;
            }
            code = codeEng[remainder - 1] + code;
            index = quotient;
          }




          let obj1111 = {
            code: this.hjForm.type === 1 ? code : ruleName + (i + 1),
            length: this.form.vehicleLen ? Number(this.form.vehicleLen / Number(this.form.lineNum)).toFixed(0) : '',
            breadth: this.form.wilde,
            altitude: this.form.levelNum ? Number(this.form.hight / Number(this.form.levelNum)).toFixed(0) : '',
            weightLimit: '',
            volume: ''
          };
          this.form.positionList.push(obj1111)


          currentLetterIndex++; // 自增索引
          this.hjCodeFalg = false
        }
      }



    },

    handleInput(event) {
      // 只允许输入 A-Z 的大写字母
      let filteredValue = this.hjForm.code.replace(/[^A-Z]/g, '');
      this.hjForm.code = filteredValue;
    },

    save() {
      console.log(this.form)
      this.$refs.tableForm.validate((valid) => {
        if (valid) {
          categoryVehicle(this.form).then(res => {
            this.cancel()
          })
        }
      })
    }




  }
};
</script>
  
<style lang="scss" scoped>
.el-form-item {
  margin-bottom: 20px !important;
}
</style>
  