<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="NuInvoicingCgdMainForm">
          <a-row>
						<a-col :span="8">
							<a-form-item label="采购单单号" v-bind="validateInfos.cgdNo" id="NuInvoicingCgdMainForm-cgdNo" name="cgdNo">
                <span>{{formData.cgdNo}}</span>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="机构名称" v-bind="validateInfos.gysName" id="NuInvoicingCgdMainForm-gysName" name="gysName">
                <span>{{formData.gysName}}</span>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="机构地址" v-bind="validateInfos.comRegisterAddress" id="NuInvoicingCgdMainForm-comRegisterAddress" name="comRegisterAddress">
                <span>{{formData.comRegisterAddress}}</span>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="采购时间" v-bind="validateInfos.qgDate" id="NuInvoicingCgdMainForm-qgDate" name="qgDate">
                <span>{{formData.qgDate}}</span>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="采购人" v-bind="validateInfos.qgBy" id="NuInvoicingCgdMainForm-qgBy" name="qgBy">
                <span>{{formData.qgBy}}</span>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="采购人电话" v-bind="validateInfos.qgTel" id="NuInvoicingCgdMainForm-qgTel" name="qgTel">
                <span>{{formData.qgTel}}</span>
							</a-form-item>
						</a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
    <a-table
      :columns="rkcolumnsDetail"
      row-key="id"
      :data-source="dataSource"
      :pagination="false"
    >
      <template #bodyCell="{ column, text ,record  }">
      </template>
    </a-table>
  </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 JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
  import { getValueType } from '/@/utils';
  import { rukuInfo } from '../NuInvoicingCgdMain.api';
  import { rkcolumnsDetail } from '../NuInvoicingCgdInfo.data';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import { useUserStore } from '/@/store/modules/user';
  import dayjs from 'dayjs';
  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 dataSource = ref([]);
  const userStore = useUserStore();
  const formData = reactive<Record<string, any>>({
    id: '',
    qgdId: '',   
    cgdNo: '',   
    gysId: '',   
    qgDate: '',   
    qgBy: '',   
    gysLxr: '',   
    gysLxrdh: '',   
    gysFkfs: '',   
    status: '',   
    cgdType: '',   
    sxdPath: '',   
    xzdPath: '',   
    jzdPath: '',   
    reviewedBy: '',   
    reviewedTime: '',   
    content: '',   
    gysName:'',
    qgTel:'',
    departName:'',
    comRegisterAddress:'',
    status_dictText:'',
    cgdType_dictText:'',
    gysFkfs_dictText:'',
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 9 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 15 } });
  const labelCol2 = ref<any>({ xs: { span: 24 }, sm: { span: 3 } });
  const wrapperCol2 = ref<any>({ xs: { span: 24 }, sm: { span: 19 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = reactive({
  });
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });
const handleInputChange = (record, field, value) => {
  // 更新当前行的数据
  record[field] = value;
  
  var b = record.purchaseQuantity - value;
  if(b<0){
    record.wrksl = 0;
    record.rksl = record.purchaseQuantity;
    return;
  }
    record.wrksl = b;
  // 如果是修改了 rksl，则 wrksl 会自动更新，因为它是计算属性
  // 如果需要强制更新视图，可以使用以下方法：
  
  // 方法1：使用 Vue 的强制更新（不推荐常规使用）
  // this.$forceUpdate();
  
  // 方法2：更好的方式是更新整个 dataSource（推荐）
  const index = dataSource.value.findIndex(item => item.id === record.id);
  if (index !== -1) {
    dataSource.value[index] = { ...record };
    dataSource.value = [...dataSource.value]; // 创建新数组触发响应式更新
  }
};
const handleRkslChange = (record, field, value) => {
  // 更新当前行的数据
  record[field] = value;
  
  // // 方法2：更好的方式是更新整个 dataSource（推荐）
  // const index = dataSource.value.findIndex(item => item.id === record.id);
  // if (index !== -1) {
  //   dataSource.value[index] = { ...record };
  //   dataSource.value = [...dataSource.value]; // 创建新数组触发响应式更新
  // }
};
  // 表单禁用
  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);

      getCgdInfoList();
    });
  }

  function getCgdInfoList() {
    defHttp.get({ url: '/api/suppliers/queryCgdInfoList', params: { cgdId: formData.id,pageSize:-1 } }).then((res) => {
      console.log("🚀 ~ queryCgdInfoList ~ res:", res)
      dataSource.value = res.records;
    });
  }

  /**
   * 提交数据
   */
  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(',');
        }
      }
    }
    console.log("🚀 ~ submitForm ~ model.status:", model.status)
    if(model.status == '3'){
      model.cgdType = '9'
    }
      console.log("🚀 ~ submitForm ~ model:", model)
      model.cgdInfoList = dataSource.value;
    await rukuInfo(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;
  }
</style>
