<template>
  <a-spin :spinning="confirmLoading">
    <div class="card-style">
      <JFormContainer :disabled="disabled">
        <template #detail>
          <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol"
            name="DirectivePackageForm">
            <a-row>
              <a-col :span="12">
                <a-row>
                  <a-col :span="24">
                    <a-form-item label="指令包名称" v-bind="validateInfos.packageName" id="DirectivePackageForm-packageName"
                      name="packageName">
                      <a-input v-model:value="formData.packageName" placeholder="请输入服务指令包名称" allow-clear :maxlength="20"
                        :showCount="true"></a-input>
                    </a-form-item>
                  </a-col>
                  <a-col :span="24">
                    <a-form-item label="服务总时长" v-bind="validateInfos.totalDuration"
                      id="DirectivePackageForm-totalDuration" name="totalDuration">
                      <a-input-number v-model:value="formData.totalDuration" :min="0" :step="5" addon-after="分钟"
                        placeholder="请输入服务时长（分钟）" allow-clear @keydown="onDurationKeydown" :disabled="disabled" />
                    </a-form-item>
                  </a-col>
                  <a-col :span="24">
                    <a-form-item label="超时时长" v-bind="validateInfos.timeoutDuration"
                      id="DirectivePackageForm-timeoutDuration" name="timeoutDuration">
                      <a-input-number v-model:value="formData.timeoutDuration" :min="1" :step="5" addon-after="分钟"
                        placeholder="请输入超时时长（分钟）" allow-clear @keydown="onDurationKeydown" :disabled="disabled" />
                    </a-form-item>
                  </a-col>
                </a-row>
              </a-col>
              <a-col :span="12">
                <a-row>
                  <a-col :span="24">
                    <a-form-item label="分类标签" v-bind="validateInfos.instructionTagId"
                      id="DirectivePackageForm-instructionTagId" name="instructionTagId" :labelCol="labelCol2"
                      :wrapperCol="wrapperCol2">
                      <j-dict-select-tag v-model:value="formData.instructionTagId"
                        :dictCode="`nu_config_service_instruction_tag,instruction_name,id,del_flag = 0 and iz_enabled = 'Y' order by sort asc`"
                        placeholder="请选择分类标签" allowClear
                        :disabled="!!props.seletedRecord && !!props.seletedRecord.directives && !!props.seletedRecord.directives.length > 0" />
                    </a-form-item>
                  </a-col>
                  <a-col :span="24">
                    <a-form-item label="是否启用" v-bind="validateInfos.izEnabled" id="DirectivePackageForm-izEnabled"
                      name="izEnabled" :labelCol="labelCol2" :wrapperCol="wrapperCol2">
                      <j-dict-select-tag type='list' v-model:value="formData.izEnabled" dictCode="iz_enabled"
                        placeholder="是否启用" allow-clear />
                    </a-form-item>
                  </a-col>
                  <a-col :span="24">
                    <a-form-item label="说明" v-bind="validateInfos.description" id="DirectivePackageForm-description"
                      name="description" :labelCol="labelCol2" :wrapperCol="wrapperCol2">
                      <a-textarea v-model:value="formData.description" :maxlength="200" :autosize="{ minRows: 1 }"
                        :showCount="true" placeholder="请输入说明" />
                    </a-form-item>
                  </a-col>
                </a-row>
              </a-col>
            </a-row>
          </a-form>
        </template>
      </JFormContainer>
    </div>
  </a-spin>
</template>

<script lang="ts" setup>
import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
import { defHttp } from '/@/utils/http/axios';
import { useMessage } from '/@/hooks/web/useMessage';
import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
import { getValueType } from '/@/utils';
import { saveOrUpdate } from '../DirectivePackage.api';
import { Form } from 'ant-design-vue';
import dayjs from "dayjs";
import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
const props = defineProps({
  formDisabled: { type: Boolean, default: false },
  formData: { type: Object, default: () => ({}) },
  formBpm: { type: Boolean, default: true },
  seletedRecord: null,
});
setInterval(() => {
  console.log("🌊 ~ props:", props)
}, 2000);

const formRef = ref();
const useForm = Form.useForm;
const emit = defineEmits(['register', 'ok']);
const formData = reactive<Record<string, any>>({
  id: '',
  packageName: '',
  description: '',
  sort: 99,
  izEnabled: 'Y',
  startTimeStr: '',
  endTimeStr: '',
  instructionTagId: '',
  totalDuration: 0,
  timeoutDuration: 0,
});
const { createMessage } = useMessage();
const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
const labelCol2 = ref<any>({ xs: { span: 24 }, sm: { span: 3 } });
const wrapperCol2 = ref<any>({ xs: { span: 24 }, sm: { span: 21 } });
const confirmLoading = ref<boolean>(false);
//表单验证
const validatorRules = reactive({
  packageName: [{ required: true, message: '请输入服务指令包名称!' },],
  instructionTagId: [{ required: true, message: '请选择分类标签!' },],
  totalDuration: [{ required: true, message: '请输入服务总时长（分钟）!' }, {
    validator: (_, value) => {
      if (value < 0) {
        return Promise.reject('请输入服务总时长!');
      }
      return Promise.resolve();
    },
  },],
  izEnabled: [{ required: true, message: '请选择是否启用!' },],
});
const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

const onDurationKeydown = (e: KeyboardEvent) => {
  const key = e.key;
  // 放行控制键
  if (['Backspace', 'Delete', 'ArrowLeft', 'ArrowRight', 'Tab'].includes(key)) return;
  // 只能输数字和点
  if (!/[\d.]/.test(key)) {
    e.preventDefault();
    return;
  }
  const input = e.target as HTMLInputElement;
  const { value, selectionStart: s, selectionEnd: t } = input;
  const next = value.slice(0, s!) + key + value.slice(t!);
  // 整数最多5位，小数最多2位
  if (!/^\d{0,3}$/.test(next)) {
    e.preventDefault();
  }
};

// 表单禁用
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]
      }
    })
    console.log("🚀 ~ nextTick ~ tmpData:", tmpData)
    //赋值
    Object.assign(formData, tmpData);

    if (formData.startTimeStr) {
      formData.startTimeStr = dayjs(formData.startTimeStr, "YYYY-MM-DD hh:mm:ss")
    }
    if (formData.endTimeStr) {
      formData.endTimeStr = dayjs(formData.endTimeStr, "YYYY-MM-DD hh:mm:ss")
    }
    console.log("🚀 ~ nextTick ~ formData:", formData)
  });
}

/**
 * 提交数据
 */
async function submitForm(directives) {
  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) {
    //如果该数据是数组并且是字符串类型
    if (model[data] instanceof Array) {
      let valueType = getValueType(formRef.value.getProps, data);
      //如果是字符串类型的需要变成以逗号分割的字符串
      if (valueType === 'string') {
        model[data] = model[data].join(',');
      }
    }
  }
  if (directives.length > 0) {
    model.directives = directives
  }
  // if (!model.packageName) {
  //   createMessage.warning('请填写服务指令包名称');
  //   confirmLoading.value = false;
  //   return;
  // }
  // if (!model.startTimeStr) {
  //   createMessage.warning('请选择开始时间');
  //   confirmLoading.value = false;
  //   return;
  // }
  // if (!model.endTimeStr) {
  //   createMessage.warning('请选择结束时间');
  //   confirmLoading.value = false;
  //   return;
  // }
  var directivesList = model.directives;
  if (!directivesList || directivesList.length == 0) {
    createMessage.warning('请选择服务指令');
    confirmLoading.value = false;
    return;
  } else {
    model.instructionTagId = directivesList[0].instructionTagId;
  }
  console.log('model', model);
  // confirmLoading.value = false;
  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,
  formData,
});
</script>

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

.card-style {
  padding-top: 14px;
  padding-left: 14px;
  padding-right: 14px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 14px;
}

:deep .ant-input-number-group-wrapper {
  width: 100%;
}
</style>
