<template>
  <a-spin :spinning="loading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form v-bind="formItemLayout" name="PickForm" ref="formRef" class="jeecg-native-form">
          <a-row class="form-row" :gutter="24">
            <a-col :span="8">
              <a-form-item label="赛意单号" v-bind="validateInfos.thirdOrderNo" id="PickForm-thirdOrderNo" name="thirdOrderNo">
                <a-input v-model:value="formData.thirdOrderNo" placeholder="请输入外部单号" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="任务号" v-bind="validateInfos.no" id="PickForm-no" name="no">
                <a-input v-model:value="formData.no" placeholder="请输入任务号" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col class="form-row" :span="8">
              <a-form-item label="单据类型" v-bind="validateInfos.orderType" id="PickForm-orderType" name="orderType">
                <JDictSelectTag
                  type="select"
                  v-model:value="formData.orderType"
                  dictCode="pick_order_type"
                  placeholder="请选择单据类型"
                  :string-to-number="true"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row class="form-row" :gutter="24">
            <a-col class="form-row" :span="8">
              <a-form-item label="客户" v-bind="validateInfos.customerCode" id="PickForm-customerCode" name="customerCode">
                <a-input v-model:value="formData.customerCode" placeholder="请输入客户" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col class="form-row" :span="8">
              <a-form-item label="外部仓库" v-bind="validateInfos.whCode" id="PickForm-whCode" name="whCode">
                <a-input v-model:value="formData.whCode" placeholder="请输入外部仓库代码" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="订单日期" v-bind="validateInfos.orderDate" id="PickForm-orderDate" name="orderDate">
                <a-date-picker
                  placeholder="请选择订单日期"
                  v-model:value="formData.orderDate"
                  showTime
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                  allow-clear
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row class="form-row" :gutter="24">
            <a-col class="form-row" :span="8">
              <a-form-item label="柜号" v-bind="validateInfos.conNo" id="PickForm-conNo" name="conNo">
                <a-input v-model:value="formData.conNo" placeholder="请输入柜号" allow-clear></a-input>
              </a-form-item>
            </a-col>

          </a-row>
          <a-row class="form-row" :gutter="24">
            <a-col :span="24">
              <a-form-item
                label="描述"
                v-bind="validateInfos.description"
                id="PickForm-description"
                name="description"
                :labelCol="{ span: 2 }"
                :wrapperCol="{ span: 24 }"
              >
                <a-textarea v-model:value="formData.description" :rows="4" placeholder="请输入描述" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>

    <!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated style="overflow: hidden" class="jeecg-native-tab">
      <a-tab-pane tab="出库明细" key="pickDetail" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          ref="pickDetailTableRef"
          resizable
          :loading="pickDetailTable.loading"
          :columns="pickDetailTable.columns"
          :dataSource="pickDetailTable.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"
        />
      </a-tab-pane>
      <a-tab-pane tab="拣货详情" key="task" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="taskTableRef"
          :loading="taskTable.loading"
          :columns="taskTable.columns"
          :dataSource="taskTable.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="false"
        />
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, computed, toRaw } from 'vue';
  import { useValidateAntFormAndTable } from '/@/hooks/system/useJvxeMethods';
  import { queryPickDetailListByMainId, queryDataById, saveOrUpdate,queryTaskByMainId } from '../Pick.api';
  import { JVxeTable } from '/@/components/jeecg/JVxeTable';
  import { pickDetailColumns, taskColumns } from '../Pick.data';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import { JDictSelectTag } from '@/components/Form';
  import { Form } from 'ant-design-vue';
  import { getDateByPicker } from '/@/utils';
  import { getTenantId } from '@/utils/auth';
  import dayjs from 'dayjs';

  const useForm = Form.useForm;

  export default defineComponent({
    name: 'PickForm',
    components: {
      JVxeTable,
      JDictSelectTag,
      JFormContainer,
    },
    props: {
      formDisabled: {
        type: Boolean,
        default: false,
      },
      formData: {
        type: Object,
        default: () => {},
      },
      formBpm: { type: Boolean, default: true },
    },
    emits: ['success'],
    setup(props, { emit }) {
      const loading = ref(false);
      const formRef = ref();
      //出库明细
      const pickDetailTableRef = ref();
      const pickDetailTable = reactive<Record<string, any>>({
        loading: false,
        columns: pickDetailColumns,
        dataSource: [],
      });

      //拣货详细
      const taskTableRef = ref();
      const taskTable = reactive<Record<string, any>>({
        loading: false,
        columns: taskColumns,
        dataSource: [],
      });


      const activeKey = ref('pickDetail');
      //仓库 ID
      let tenantId = getTenantId();
      const formData = reactive<Record<string, any>>({
        id: '',
        orderNo: '',
        thirdOrderNo: '',
        no: '',
        whCode: '',
        customerCode: '',
        conNo: '',
        orderType: '',
        status: 1,
        orderDate: dayjs(),
        tenantId: tenantId,
        description: '',
      });

      //表单验证
      const validatorRules = reactive({
        thirdOrderNo: [{ required: true, message: '请输入外部单号!' }],
        no: [{ required: true, message: '请输入任务号!' }],
        orderType: [{ required: true, message: '请选择单据类型!' }],
        whCode: [{ required: true, message: '请输入外部仓库代码' }],
        conNo: [{ required: true, message: '请输入柜号' }],
      });
      const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });
      //日期个性化选择
      const fieldPickers = reactive({});
      const dbData = {};
      const formItemLayout = {
        labelCol: { xs: { span: 24 }, sm: { span: 6 } },
        wrapperCol: { xs: { span: 24 }, sm: { span: 24 } },
      };

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

      function add() {
        resetFields();
        pickDetailTable.dataSource = [];
        taskTable.dataSource = [];
      }

      async function edit(row) {
        //主表数据
        await queryMainData(row.id);
        //子表数据
        const pickDetailDataList = await queryPickDetailListByMainId(row['id']);
        pickDetailTable.dataSource = [...pickDetailDataList];

        //拣货详情数据
        const taskDataList = await queryTaskByMainId(row['id']);
        taskTable.dataSource = [...taskDataList];
      }

      async function queryMainData(id) {
        const row = await queryDataById(id);
        resetFields();
        const tmpData = {};
        Object.keys(formData).forEach((key) => {
          if (row.hasOwnProperty(key)) {
            tmpData[key] = row[key];
          }
        });
        //赋值
        Object.assign(formData, tmpData);
      }

      const { getSubFormAndTableData, transformData } = useValidateAntFormAndTable(activeKey, {
        pickDetail: pickDetailTableRef,
        task: taskTableRef,
      });

      async function getFormData() {
        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);
        }
        return transformData(toRaw(formData));
      }

      async function submitForm() {
        const mainData = await getFormData();
        const subData = await getSubFormAndTableData();
        // 预处理日期数据
        changeDateValue(mainData, subData);
        const values = Object.assign({}, dbData, mainData, subData);
        console.log('表单提交数据', values);
        const isUpdate = values.id ? true : false;
        await saveOrUpdate(values, isUpdate);
        //关闭弹窗
        emit('success');
      }

      function setFieldsValue(values) {
        if (values) {
          Object.keys(values).map((k) => {
            formData[k] = values[k];
          });
        }
      }

      /**
       * 处理日期值
       * @param formData 表单数据
       */
      const changeDateValue = (mainData, subData) => {
        for (let key in mainData) {
          // 更新个性化日期选择器的值
          mainData[key] = getDateByPicker(mainData[key], fieldPickers[key]);
        }
        if (subData.pickDetailList && subData.pickDetailList.length > 0) {
          pickDetailColumns.forEach((subFormField) => {
            if (subFormField && subFormField.picker && subFormField.key) {
              let subPicker = subFormField.picker;
              const subFieldName = subFormField.key;
              subData.pickDetailList.forEach((subFormData) => {
                if (subPicker === 'year') {
                  subFormData[subFieldName] = dayjs(subFormData[subFieldName]).set('month', 0).set('date', 1).format('YYYY-MM-DD');
                } else if (subPicker === 'month') {
                  subFormData[subFieldName] = dayjs(subFormData[subFieldName]).set('date', 1).format('YYYY-MM-DD');
                } else if (subPicker === 'week') {
                  subFormData[subFieldName] = dayjs(subFormData[subFieldName]).startOf('week').format('YYYY-MM-DD');
                }
              });
            }
          });
        }
      };

      /**
       * 值改变事件触发-树控件回调
       * @param key
       * @param value
       */
      function handleFormChange(key, value) {
        formData[key] = value;
      }

      return {
        pickDetailTableRef,
        pickDetailTable,
        taskTableRef,
        taskTable,
        validatorRules,
        validateInfos,
        activeKey,
        loading,
        formData,
        setFieldsValue,
        handleFormChange,
        formItemLayout,
        disabled,
        getFormData,
        submitForm,
        add,
        edit,
        formRef,
      };
    },
  });
</script>
<style lang="less" scoped>
  .ant-tabs-tabpane.sub-one-form {
    max-height: 340px;
    overflow: auto;
  }

  .jeecg-native-form,
  .jeecg-native-tab {
    padding: 0 20px;
  }
</style>
