<template>
  <a-spin :spinning="loading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form v-bind="formItemLayout" name="SaleOrderForm" ref="formRef">
          <a-row>
            <a-col :span="12">
              <a-form-item label="入库单号(bill code)" v-bind="validateInfos.billCode" id="SaleOrderForm-billCode" name="billCode">
                <a-input v-model:value="formData.billCode" placeholder="自动生成" disabled />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="入库日期(bill date)" v-bind="validateInfos.billDate" id="SaleOrderForm-billDate" name="billDate">
                <a-date-picker
                  placeholder="请选择入库日期(bill date)"
                  v-model:value="formData.billDate"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                  allow-clear
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="项目(project)" v-bind="validateInfos.projectName" id="SaleOrderForm-projectName" name="projectName">
                <a-input v-model:value="formData.projectName" placeholder="请输入项目(project)" disabled allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="供应商(supplier)" v-bind="validateInfos.supplierName" id="SaleOrderForm-supplierName" name="supplierName">
                <a-input v-model:value="formData.supplierName" placeholder="请输入" disabled allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="发货方式(delivery)" v-bind="validateInfos.delivery" id="SaleOrderForm-delivery" name="delivery">
                <JDictSelectTag v-model:value="formData.delivery" placeholder="请选择" dictCode="delivery_methods" disabled />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="产品分类(production class)"
                v-bind="validateInfos.productionClass"
                id="SaleOrderForm-productionClass"
                name="productionClass"
              >
                <ApiSelect
                  :api="ClassList"
                  showSearch
                  v-model:value="formData.productionClass"
                  optionFilterProp="label"
                  resultField="records"
                  labelField="name"
                  valueField="id"
                  :params="{ pageSize: -1 }"
                  disabled
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="机型(model)" v-bind="validateInfos.model" id="SaleOrderForm-model" name="model">
                <a-input v-model:value="formData.model" placeholder="请输入" allow-clear disabled />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="厂家(maker)" v-bind="validateInfos.maker" id="SaleOrderForm-maker" name="maker">
                <a-input v-model:value="formData.maker" placeholder="请输入厂家(maker)" allow-clear disabled />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="货位(goods allocation)"
                v-bind="validateInfos.goodsAllocation"
                id="SaleOrderForm-goodsAllocation"
                name="goodsAllocation"
              >
                <JDictSelectTag v-model:value="formData.goodsAllocation" placeholder="请选择" dictCode="goods_allocation" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="仓库(warehouse)" v-bind="validateInfos.warehouse" id="SaleOrderForm-warehouse" name="warehouse">
                <JDictSelectTag v-model:value="formData.warehouse" placeholder="请选择" dictCode="warehouse" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="包装详情(packaging details)" v-bind="validateInfos.method" id="SaleOrderForm-method" name="method">
                <a-textarea  v-model:value="formData.method" placeholder="请输入" allow-clear row="3"/>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="备注(notes)" v-bind="validateInfos.notes" id="SaleOrderForm-notes" name="notes">
                <a-textarea  v-model:value="formData.notes" AutoComplete="off" row="3"/>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="到货详情(arrival details)"
                v-bind="validateInfos.arrivalDetails"
                id="PuechaseInquiryFormForm-attachs"
                name="arrivalDetails"
              >
                <a :href="baseUrl + formData.arrivalDetails">{{ formData.arrivalDetails }}</a>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="附件(attachs)" v-bind="validateInfos.attachs" id="PuechaseInquiryFormForm-attachs" name="attachs">
                <JUpload v-model:value="formData.attachs" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>

    <!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated style="padding: 24px; padding-top: 0px">
      <a-tab-pane tab="采购入库 - 入库明细(stock in details)" key="stockIn" :forceRender="true">
        <a-button type="primary" style="margin-right: 1%; margin-bottom: 1%" @click="selectArrivalList"> 选择到货单(select arrival)</a-button>
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="stockInTableRef"
          :loading="stockInTable.loading"
          :columns="stockInTable.columns"
          :dataSource="stockInTable.dataSource"
          :maxHeight="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          asyncRemove
        >
          <template #action="props">
            <a-popconfirm title="确定删除吗？" @confirm="handleDelete(props)">
              <a>删除(delete)</a>
            </a-popconfirm>
            <!-- 逻辑不通暂时取消次功能 -->
            <!-- <a>复制(copy)</a> -->
          </template>
        </j-vxe-table>
      </a-tab-pane>
      <a-tab-pane tab="采购入库 - 船明细(ship details)" key="purInShip" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="purInShipTableRef"
          :loading="purInShipTable.loading"
          :columns="purInShipTable.columns"
          :dataSource="purInShipTable.dataSource"
          :maxHeight="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
        >
          <template #action="props">
            <a @click="viewAccessory(props)">查看配件信息(view accessory information)</a>
          </template>
        </j-vxe-table>
      </a-tab-pane>
    </a-tabs>
    <BaseShipArchiveAccessoriesModal ref="BaseShipArchiveAccessoriesModalRef" />
    <selectArrivalList ref="SelectArrivalListRef" @select-arrrival-order="addStockInList" />
  </a-spin>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, computed, toRaw } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useValidateAntFormAndTable } from '/@/hooks/system/useJvxeMethods';
  import { queryPurInFormShipFormShippTable, querystockInByMainId, queryDataById, saveOrUpdate, ClassList } from '../purchaseInForm.api';
  import { JVxeTable } from '/@/components/jeecg/JVxeTable';
  import { purInShipColumns, stockInColumns } from '../puechaseInForm.data';
  import BaseShipArchiveAccessoriesModal from '../../../publicComponents/BaseShipArchiveAccessoriesModal.vue';
  import selectArrivalList from '../../../publicComponents/selectArrivalList.vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
  import { JDictSelectTag } from '/@/components/Form';
  import { Form, message } from 'ant-design-vue';
  import { useGlobSetting } from '/@/hooks/setting';
  import { ApiSelect } from '/@/components/Form/index';
  import { initDictOptions } from '/@/utils/dict';

  import moment from 'moment';
  const useForm = Form.useForm;
  export default defineComponent({
    name: 'PurchaseInForm',
    components: {
      JVxeTable,
      JFormContainer,
      JUpload,
      JDictSelectTag,
      BaseShipArchiveAccessoriesModal,
      selectArrivalList,
      ApiSelect,
    },
    props: {
      formDisabled: {
        type: Boolean,
        default: false,
      },
      formData: { type: Object, default: () => {} },
      formBpm: { type: Boolean, default: true },
    },
    emits: ['success'],
    setup(props, { emit }) {
      const { domainUrl } = useGlobSetting();
      const baseUrl = domainUrl + '/sys/common/static/';
      const loading = ref(false);
      const formRef = ref();
      const SelectArrivalListRef = ref();
      const purInShipTableRef = ref();
      const BaseShipArchiveAccessoriesModalRef = ref();
      const purInShipTable = reactive<Record<string, any>>({
        loading: false,
        columns: purInShipColumns,
        dataSource: [],
      });
      const stockInTableRef = ref();
      const stockInTable = reactive<Record<string, any>>({
        loading: false,
        columns: stockInColumns,
        dataSource: [],
      });
      const activeKey = ref('stockIn');
      const formData = reactive<Record<string, any>>({
        id: '',
        status: undefined,
        delFlag: undefined,
        sourceCode: '',
        billCode: '',
        billDate: moment(new Date()).format('YYYY-MM-DD'),
        project: '',
        projectName: '',
        supplier: '',
        supplierName: '',
        delivery: '',
        productionClass: '',
        model: '',
        maker: '',
        goodsAllocation: '',
        warehouse: '',
        notes: '',
        attachs: '',
        arrivalDetails: '',
        typr: '1',
        method: '',
      });
      //表单验证
      const validatorRules = reactive({});
      const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });
      const dbData = {};
      const formItemLayout = {
        labelCol: { xs: { span: 24 }, sm: { span: 5 } },
        wrapperCol: { xs: { span: 24 }, sm: { span: 16 } },
        labelCol1: { xs: { span: 24 }, sm: { span: 7 } },
        wrapperCol1: { xs: { span: 24 }, sm: { span: 15 } },
      };

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

      async function add() {
        resetFields();
        purInShipTable.dataSource = [];
        stockInTable.dataSource = [];
        activeKey.value = 'stockIn';
        var warehouseArr = await initDictOptions('warehouse');
        var goodsAllocationArr = await initDictOptions('goods_allocation');
        formData.warehouse = warehouseArr[0].value;
        formData.goodsAllocation = goodsAllocationArr[0].value;
      }
      async function edit(row) {
        //主表数据
        await queryMainData(row.id);
        //子表数据
        const purInShipDataList = await queryPurInFormShipFormShippTable(row['id']);
        purInShipTable.dataSource = [...purInShipDataList];
        const stockInDataList = await querystockInByMainId(row['id']);
        stockInTable.dataSource = [...stockInDataList];
      }

      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, {
        storePurchaseInShip: purInShipTableRef,
        storePurchaseInDetails: stockInTableRef,
      });

      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() {
        if (formData.sourceCode == '') {
          message.error('请添加入库明细！');
        } else {
          stockInTableRef.value!.validateTable().then(async (errMap) =>  {
            if (errMap) {
              console.log('表单验证未通过：', { errMap });
            } else {
              const mainData = await getFormData();
              const subData = await getSubFormAndTableData();
              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];
          });
        }
      }
      function getShipList(id) {
        let params = { id: id };
        let url = '/purCode/purDeliveryNote/queryPurDeliveryNodeShipByMainId';
        defHttp.get({ url: url, params }, { isTransformResponse: false }).then((res) => {
          if (res) {
            purInShipTable.dataSource = res.result;
          }
        });
      }

      //查看配件信息
      function viewAccessory(prop) {
        BaseShipArchiveAccessoriesModalRef.value.getTable(prop.row);
      }
      //产品明细-删除行
      function handleDelete(prop) {
        var xTable = stockInTableRef.value!.getXTable()
        var newArray = [...xTable.data];
        newArray.splice(prop.rowIndex, 1);
        stockInTable.dataSource = newArray;
        if (stockInTable.dataSource.length == 0) {
          formData.sourceCode = '';
          add();
        }
      }
      function selectArrivalList() {
        SelectArrivalListRef.value.getTable(formData);
      }
      function addStockInList(data) {
        formData.project = data[0].project;
        formData.projectName = data[0].projectName;
        formData.supplier = data[0].supplier;
        formData.supplierName = data[0].supplierName;
        formData.delivery = data[0].delivery;
        formData.productionClass = data[0].productionClass;
        formData.model = data[0].model;
        formData.maker = data[0].maker;
        formData.sourceCode = data[0].billCode;
        formData.arrivalDetails = data[0].arrivalDetails;
        getShipList(data[0].headId);
        data.map((item) => {
          item.model = item.childModel;
          item.sourceId = item.childId;
          item.arrivalQuantity = item.quantity;
          item.stockInQuantity = item.quantity;
        });
        var xTable = stockInTableRef.value!.getXTable()
        var arr = xTable.data.concat(data);
        stockInTable.dataSource = arr;
      }
      /**
       * 值改变事件触发-树控件回调
       * @param key
       * @param value
       */
      function handleFormChange(key, value) {
        formData[key] = value;
      }
      return {
        purInShipTableRef,
        purInShipTable,
        stockInTableRef,
        stockInTable,
        validatorRules,
        validateInfos,
        activeKey,
        loading,
        formData,
        setFieldsValue,
        handleFormChange,
        formItemLayout,
        disabled,
        getFormData,
        submitForm,
        add,
        edit,
        formRef,
        handleDelete,
        BaseShipArchiveAccessoriesModalRef,
        viewAccessory,
        SelectArrivalListRef,
        selectArrivalList,
        addStockInList,
        baseUrl,
        ClassList,
      };
    },
  });
</script>
<style lang="less" scoped>
  /** 时间和数字输入框样式 */
  :deep(.ant-input-number) {
    width: 100%;
  }

  :deep(.ant-calendar-picker) {
    width: 100%;
  }
  /deep/.vxe-table--body-wrapper {
    height: 100% !important;
  }
  /deep/.ant-modal-body {
    padding: 24px !important;
  }

  /deep/.ant-form-item {
    margin-bottom: 8px !important;
  }
  /deep/.vxe-cell--valid-error-msg{
    color: white !important;
    background-color: white !important;
  }
</style>
