<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="AgvTaskForm">
          <a-row>
            <a-col :span="24">
              <a-form-item label="任务ID"  v-bind="validateInfos.id" v-if="formData.id" id="AgvTaskForm-id" name="id">
                <a-input v-model:value="formData.id"   allow-clear ></a-input>
              </a-form-item>
            </a-col>
						<a-col :span="24">
							<a-form-item label="容器" v-bind="validateInfos.carrierCode" id="AgvTaskForm-carrierCode" name="carrierCode">
                <JDictSelectTag v-model:value="formData.carrierCode" placeholder="请选择容器" dictCode="base_stock where iz_active=1 and del_flag=0,stock_code,stock_code" allowClear />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="任务类型" v-bind="validateInfos.taskType" id="AgvTaskForm-taskType" name="taskType">
								<a-input v-model:value="formData.taskType" placeholder="请输入任务类型"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="业务类型" v-bind="validateInfos.type" id="AgvTaskForm-type" name="type">
                <JDictSelectTag
                  type="select"
                  v-model:value="formData.type"
                  dictCode="business_type"
                  placeholder="请选择业务类型"
                />
              </a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="任务状态" v-bind="validateInfos.status" id="AgvTaskForm-status" name="status">
                <JDictSelectTag
                  type="select"
                  v-model:value="formData.status"
                  dictCode="agv_task_status"
                  placeholder="请选择任务状态"
                />
              </a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="优先级" v-bind="validateInfos.priority" id="AgvTaskForm-priority" name="priority">
								<a-input-number v-model:value="formData.priority" placeholder="请输入优先级" style="width: 100%" />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="起点" v-bind="validateInfos.startCode" id="AgvTaskForm-startCode" name="startCode">
                <JDictSelectTag v-model:value="formData.startCode" placeholder="请选择库位" dictCode="base_point where iz_active=1 and del_flag=0 ,point_code,point_code" allowClear />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="终点" v-bind="validateInfos.endCode" id="AgvTaskForm-endCode" name="endCode">
                <JDictSelectTag v-model:value="formData.endCode" placeholder="请选择库位" dictCode="base_point where iz_active=1 and del_flag=0 ,point_code,point_code" allowClear />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="返回报文" v-bind="validateInfos.resMessage" v-if="formData.id" id="AgvTaskForm-resMessage" name="resMessage">
								<a-textarea v-model:value="formData.resMessage" :rows="4" placeholder="请输入返回报文" />
							</a-form-item>
						</a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed } from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getDateByPicker, getValueType } from '/@/utils';
  import { getTenantId } from '@/utils/auth';
  import { saveOrUpdate } from '../AgvTask.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import { JDictSelectTag } from '@/components/Form';
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({})},
    formBpm: { type: Boolean, default: true }
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  //仓库 ID
  let tenantId = getTenantId();
  const formData = reactive<Record<string, any>>({
    id: '',
    carrierCode: '',
    carrierType: 'TRAY',
    taskType: '',
    type: '',
    status: 'CREATED',
    priority: 99,
    startCode: '',
    endCode: '',
    resMessage: '',
    tenantId: tenantId,
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = reactive({
    carrierCode: [{ required: true, message: '请选择容器!'},],
    type: [{ required: true, message: '请选择业务类型!'},],
    priority: [{ required: true, message: '请输入优先级!'},],
    startCode: [{ required: true, message: '请选择起点!'},],
    endCode: [{ required: true, message: '请选择终点!'},],
    status: [{ required: true, message: '请选择任务状态!'},]
  });
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });
  //日期个性化选择
  const fieldPickers = reactive({
  });

  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });


  /**
   * 新增
   */
  function add() {
    edit({});
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
      //赋值
      Object.assign(formData, tmpData);
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    try {
      // 触发表单验证
      await validate();
    } catch ({ errorFields }) {
      if (errorFields) {
        const firstField = errorFields[0];
        if (firstField) {
          formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(errorFields);
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      // 更新个性化日期选择器的值
      model[data] = getDateByPicker(model[data], fieldPickers[data]);
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }


  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px 20px;
  }
</style>
