<!--
  * 批量调整
  *
  * @Author:    霍锦
  * @Date:      2024-11-18 14:17:31
  * @Copyright  友仓
-->
<template>
  <a-modal
      :title="title"
      :width="600"
      :open="visibleFlag"
      @cancel="onClose"
      :maskClosable="false"
      :destroyOnClose="true"
  >
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 6 }">
      <a-divider orientation="left">基础信息</a-divider>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="库区" name="areaId">
            <AreaSelect width="100%" v-model:value="form.areaId" :area-names="['存储区']" :disabled-flag="true"
                        @change="changeAreaSelect"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="类型" name="locationType">
            <DictSelect width="100%" key-code="LOC_TYPE" v-model:value="form.locationType"/>
          </a-form-item>
        </a-col>
      </a-row>


      <a-divider orientation="left">编码规则</a-divider>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="前缀" name="code">
            <a-input style="width: 100%" v-model:value="form.code" placeholder="编码前缀"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="分隔符" name="separator">
            <a-select
                width="100%"
                v-model:value="form.separator"
            >
              <a-select-option value="-">-</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-divider orientation="left">规则配置</a-divider>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="起始排" name="startRow">
            <a-input-number style="width: 100%" v-model:value="form.startRow" :min="1" :max="10" placeholder="起始排"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="截止排" name="endRow">
            <a-input-number style="width: 100%" v-model:value="form.endRow" :min="1" :max="10" placeholder="截止排"/>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="起始列" name="startCol">
            <a-input-number style="width: 100%" v-model:value="form.startCol" :min="1" :max="10" placeholder="起始列"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="截止列" name="endCol">
            <a-input-number style="width: 100%" v-model:value="form.endCol" :min="1" :max="10" placeholder="截止列"/>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="起始层" name="startLay">
            <a-input-number style="width: 100%" v-model:value="form.startLay" :min="1" :max="10" placeholder="起始层"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="截止层" name="endLay">
            <a-input-number style="width: 100%" v-model:value="form.endLay" :min="1" :max="10" placeholder="截止层"/>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <template #footer>
      <a-space>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">保存</a-button>
      </a-space>
    </template>
  </a-modal>
</template>
<script setup lang="ts">
import {nextTick, reactive, ref} from 'vue';
import {message} from 'ant-design-vue';
import {SmartLoading} from '/@/components/framework/smart-loading';
import {locationApi} from '/@/api/business/base/location/location-api';
import {smartSentry} from '/@/lib/smart-sentry';
import AreaSelect from "/@/views/business/base/area/area-select.vue";
import DictSelect from "/@/components/support/dict-select/index.vue";


const title = ref('批量新建');

// ------------------------ 事件 ------------------------

const emits = defineEmits(['reloadList']);

// ------------------------ 显示与隐藏 ------------------------
const visibleFlag = ref(false);

function showMultipleInsert() {
  visibleFlag.value = true;
  nextTick(() => {
    formRef.value.clearValidate();
  });
}

//关闭
function onClose() {
  Object.assign(form, formDefault);
  visibleFlag.value = false;
}

// ------------------------ 表单 ------------------------

// 组件ref
const formRef = ref();

const formDefault = {
  areaId: undefined, //库区
  locationType: undefined,//库位类型
  code: undefined, //编码前缀
  separator: '-',//分隔符
  startRow: undefined,//起始排
  endRow: undefined,//截止排
  startCol: undefined,//起始列
  endCol: undefined,//截止列
  startLay: undefined,//起始层
  endLay: undefined,//截止层
  status: true, //状态
  disabledFlag: true, //是否禁用
  rowDigits: 2, //排编码位数
  colDigits: 2, //列编码位数
  layDigits: 2, //层编码位数
};

let form = reactive({...formDefault});

const rules = {
  areaId: [{required: true, message: '库区 必填'}],
  locationType: [{required: true, message: '类型 必填'}],
  code: [
    {required: true, message: '编码前缀 必填'},
    {pattern: /^[a-zA-Z]{1,4}$/, message: '请输入字母且不超四个'}
  ],
  separator: [{required: true, message: '分隔符 必填'}],
  startRow: [{required: true, message: '起始排 必填'}],
  endRow: [{required: true, message: '截止排 必填'}],
  startCol: [{required: true, message: '起始列 必填'}],
  endCol: [{required: true, message: '截止列 必填'}],
  startLay: [{required: true, message: '起始层 必填'}],
  endLay: [{required: true, message: '截止层 必填'}],
};

//选择库区
function changeAreaSelect(selectValue: any) {
  if (selectValue) {
    form.areaId = selectValue.areaId;
  }
}

// 点击确定，验证表单
async function onSubmit() {
  try {
    await formRef.value.validateFields();
    await save();
  } catch (err) {
    message.error('参数验证错误，请仔细填写表单数据!');
  }
}

// 保存生成编码
async function save() {
  SmartLoading.show();
  try {
    const locationCodes: string[] = [];
    for (let row = form.startRow!; row <= form.endRow!; row++) {
      const formattedRow = formatNumber(row, form.rowDigits);
      for (let col = form.startCol!; col <= form.endCol!; col++) {
        const formattedCol = formatNumber(col, form.colDigits);
        for (let lay = form.startLay!; lay <= form.endLay!; lay++) {
          const formattedLay = formatNumber(lay, form.layDigits);
          const locationCode = `${form.code}${form.separator}${formattedRow}${form.separator}${formattedCol}${form.separator}${formattedLay}`;
          locationCodes.push(locationCode);
        }
      }
    }
    const response = await locationApi.multipleInsert({
      locationCodes: locationCodes,
      areaId: form.areaId,
      locationType: form.locationType
    });
    const {error, success} = JSON.parse(response.msg);
    if (error) {
      message.error(error);
    }
    if (success) {
      message.success(success);
    }
    emits('reloadList');
    onClose();
  } catch (err) {
    smartSentry.captureError(err);
  } finally {
    SmartLoading.hide();
  }
}

// 格式化数字，补零到指定位数
const formatNumber = (num: number, digits: number): string => {
  return num.toString().padStart(digits, '0');
};


defineExpose({
  showMultipleInsert,
});
</script>
