<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" labelAlign="left" :labelCol="labelCol" :wrapperCol="wrapperCol" name="DqInspectProgressForm">
          <a-row class="form-content-row" :gutter="[12, 4]">
            <a-col :xs="24" :md="12">
              <a-form-item label="反馈部门ID" v-bind="validateInfos.feedbackDeptId" id="DqInspectProgressForm-feedbackDeptId" name="feedbackDeptId">
                <a-input v-model:value="formData.feedbackDeptId" placeholder="请输入反馈部门ID" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :md="12">
              <a-form-item label="反馈部门名称" v-bind="validateInfos.feedbackDeptName" id="DqInspectProgressForm-feedbackDeptName" name="feedbackDeptName">
                <a-input v-model:value="formData.feedbackDeptName" placeholder="请输入反馈部门名称" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :md="12">
              <a-form-item label="反馈人ID" v-bind="validateInfos.feedbackPersonId" id="DqInspectProgressForm-feedbackPersonId" name="feedbackPersonId">
                <a-input v-model:value="formData.feedbackPersonId" placeholder="请输入反馈人ID" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :md="12">
              <a-form-item label="反馈人姓名" v-bind="validateInfos.feedbackPersonName" id="DqInspectProgressForm-feedbackPersonName" name="feedbackPersonName">
                <a-input v-model:value="formData.feedbackPersonName" placeholder="请输入反馈人姓名" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :md="12">
              <a-form-item label="实际完成时间" v-bind="validateInfos.actualTime" id="DqInspectProgressForm-actualTime" name="actualTime">
                <a-date-picker placeholder="请选择实际完成时间" v-model:value="formData.actualTime" value-format="YYYY-MM-DD" style="width: 100%" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :md="12">
              <a-form-item label="工作进展" v-bind="validateInfos.workProgress" id="DqInspectProgressForm-workProgress" name="workProgress">
                <a-input v-model:value="formData.workProgress" placeholder="请输入工作进展" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :md="12">
              <a-form-item label="进展状态" v-bind="validateInfos.bpmStatus" id="DqInspectProgressForm-bpmStatus" name="bpmStatus">
                <a-input v-model:value="formData.bpmStatus" placeholder="请输入进展状态" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :md="12">
              <a-form-item label="整改措施任务ID" v-bind="validateInfos.mainId" id="DqInspectProgressForm-mainId" name="mainId">
                <a-input v-model:value="formData.mainId" placeholder="请输入整改措施任务ID" allow-clear />
              </a-form-item>
            </a-col>
            <a-col v-if="showFlowSubmitButton" :span="24" style="width: 100%;text-align: center;">
              <a-button preIcon="ant-design:check-outlined" style="width: 126px" type="primary" @click="submitForm">提 交</a-button>
            </a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </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 { getValueType } from '/@/utils';
  import { saveOrUpdate } from '../DqInspectProgress.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import { usePermission } from '/@/hooks/web/usePermission';
  const { isDisabledAuth, hasPermission, initBpmFormData } = usePermission();
  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']);
  const formData = reactive<Record<string, any>>({
    id: '',
    feedbackDeptId: '',   
    feedbackDeptName: '',   
    feedbackPersonId: '',   
    feedbackPersonName: '',   
    actualTime: '',   
    workProgress: '',   
    bpmStatus: '',   
    delFlag: '',   
    mainId: '',   
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 7 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 17 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = reactive({
  });
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

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

  onMounted(()=>{
    initBpmFormData(props.formData);
    initFormData();
  });
  //渲染流程表单数据
  const queryByIdUrl = '/dqinspecttask/dqInspectTask/queryDqInspectProgressById';
  async function initFormData(){
    if(props.formBpm === true){
      let params = {id: props.formData.dataId};
      const data = await defHttp.get({url: queryByIdUrl, params});
      //设置表单的值
      edit({...data});
    }
  }
  // 是否显示提交按钮
  const showFlowSubmitButton = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return true
      }
    }
    return false
  });
  
  /**
   * 新增
   */
  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) {
      //如果该数据是数组并且是字符串类型
      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;

    :deep(.ant-form-item-label) {
      padding-bottom: 0;
      text-align: left;
    }

    :deep(.ant-form-item-label > label) {
      width: 100%;
      justify-content: flex-start;
    }

    :deep(.ant-form-item-control),
    :deep(.ant-form-item-control-input),
    :deep(.ant-form-item-control-input-content) {
      text-align: left;
    }
  }

  .form-content-row {
    :deep(.ant-form-item) {
      margin-bottom: 6px;
    }

    :deep(.ant-input),
    :deep(.ant-input-affix-wrapper),
    :deep(.ant-input-number),
    :deep(.ant-picker),
    :deep(.ant-select-selector) {
      min-height: 30px;
    }
  }
</style>
