<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" width="95%" @ok="handleSubmit" :maskClosable="false">
    <BasicForm @register="registerForm" ref="formRef" name="SaleContractForm">
      <template #quotationProjectName="props">
        <a-input-search
          v-model:value="props.values.quotationProjectName"
          :disabled="notAllowEdit"
          readonly
          AutoComplete="off"
          allow-clear
          enter-button="Search"
          @search="onSearchProject(props)"
        />
      </template>
    </BasicForm>
    <!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated @change="handleChangeTabs" style="padding: 24px; padding-top: 0px">
      <a-tab-pane tab="销售合同-产品明细" key="saleContractProduct" :forceRender="true">
        <a-button type="primary" @click="seleteQuotation" style="margin-top: 10px; margin-bottom: 5px; margin-right: 1%">
          选择报价单(selete quotation)</a-button
        >
        <a-button type="primary" @click="selectProducts" style="margin-top: 10px; margin-bottom: 5px"> 选择产品(select product)</a-button>
        <JVxeTable
          keep-source
          resizable
          ref="saleContractProduct"
          :loading="saleContractProductTable.loading"
          :columns="saleContractProductTable.columns"
          :dataSource="saleContractProductTable.dataSource"
          :maxHeight="340"
          :rowNumber="true"
          :rowSelection="true"
          :disabled="formDisabled"
        >
          <template #action="props">
            <!-- <a>关闭(close)</a>
              <a-divider type="vertical"/> -->
            <a-popconfirm title="确定删除吗？" @confirm="handleDelete1(props)">
              <a>删除(delete)</a>
            </a-popconfirm>
          </template>
        </JVxeTable>
      </a-tab-pane>
      <a-tab-pane tab="销售合同-船明细" key="saleContractShip" :forceRender="true">
        <JVxeTable
          keep-source
          resizable
          ref="saleContractShip"
          :loading="saleContractShipTable.loading"
          :columns="saleContractShipTable.columns"
          :dataSource="saleContractShipTable.dataSource"
          :maxHeight="340"
          :rowNumber="true"
          :rowSelection="true"
          :disabled="formDisabled"
        >
          <template #action="props">
            <a @click="viewAccessory(props)">查看配件信息(view accessory information)</a>
            <a-divider type="vertical" />
            <a-popconfirm title="确定删除吗？" @confirm="handleDelete(props)">
              <a>删除(delete)</a>
            </a-popconfirm>
          </template>
        </JVxeTable>
      </a-tab-pane>
    </a-tabs>
    <SelectProjectModal ref="SelectProjectModalRef" @select-project="addProject" />
    <BaseShipArchiveAccessoriesModal ref="BaseShipArchiveAccessoriesListRef" />
    <SelectPrpductModal ref="SelectPrpductModalRef" @select-product="addProduct" />
    <SelectQuotationModal ref="SelectQuotationModalRef" @select-quotation="addQuotation" />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, unref, reactive } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { JVxeTable } from '/@/components/jeecg/JVxeTable';
  import { useJvxeMethod } from '/@/hooks/system/useJvxeMethods.ts';
  import { formSchema, saleContractShipColumns, saleContractProductColumns } from '../SaleContract.data';
  import {
    saveOrUpdate,
    saleContractShipList,
    saleContractProductList,
    querysaleVersonFormShipListByMainId,
    querySaleVersonProductListByMainId,
    queryVersonHistoryById,
  } from '../SaleContract.api';
  import { defHttp } from '/@/utils/http/axios';
  import SelectProjectModal from '../../../publicComponents/SelectProjectModal.vue';
  import SelectQuotationModal from '../../../publicComponents/SelectQuotationModal.vue';
  import BaseShipArchiveAccessoriesModal from '../../../publicComponents/BaseShipArchiveAccessoriesModal.vue';
  import SelectPrpductModal from '../../../publicComponents/SelectPrpductModal.vue';
  import { useUserStore } from '/@/store/modules/user';
  import moment from 'moment';
  import { message } from 'ant-design-vue';
  import { add } from '/@/components/Table/src/componentMap';
  // Emits声明
  const emit = defineEmits(['register', 'success']);
  const userStore = useUserStore();
  var customerOption = ref([]);
  const isUpdate = ref(true);
  var title = ref('');
  const formDisabled = ref(false);
  const refKeys = ref(['saleContractShip', 'saleContractProduct']);
  var notAllowEdit = ref(false);
  const activeKey = ref('saleContractProduct');
  const saleContractShip = ref();
  const saleContractProduct = ref();
  const SelectQuotationModalRef = ref();
  var SelectProjectModalRef = ref();
  var SelectPrpductModalRef = ref();
  var BaseShipArchiveAccessoriesListRef = ref();
  const tableRefs = { saleContractShip, saleContractProduct };
  const saleContractShipTable = reactive({
    loading: false,
    dataSource: [],
    columns: saleContractShipColumns,
  });
  const saleContractProductTable = reactive({
    loading: false,
    dataSource: [],
    columns: saleContractProductColumns,
  });
  //表单配置
  const [registerForm, { setProps, resetFields, setFieldsValue, validate, getFieldsValue }] = useForm({
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: { span: 12 },
  });
  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    //重置表单
    await reset();
    getCustomerOptions();
    setModalProps({ confirmLoading: false, showCancelBtn: data?.showFooter, showOkBtn: data?.showFooter });
    isUpdate.value = !!data?.isUpdate;
    formDisabled.value = !data?.showFooter;
    title.value = data?.isUpdate ? (unref(formDisabled) ? '详情' : '编辑') : '新增';
    title.value = data.isRevise ? '修订(Revise)' : title.value;
    if (data.history == 'yes') {
      const row = await queryVersonHistoryById(data.record.id);
      await setFieldsValue({ ...row });
      const saleContractShipList = await querysaleVersonFormShipListByMainId(data.record.id);
      saleContractShipTable.dataSource = [...saleContractShipList];
      const saleContractProductList = await querySaleVersonProductListByMainId(data.record.id);
      saleContractProductTable.dataSource = [...saleContractProductList];
    } else if (unref(isUpdate)) {
      //表单赋值
      await setFieldsValue({
        ...data.record,
      });
      requestSubTableData(saleContractShipList, { id: data?.record?.id }, saleContractShipTable);
      requestSubTableData(saleContractProductList, { id: data?.record?.id }, saleContractProductTable);
      notAllowEdit.value = true;
    } else {
      await setFieldsValue({ billDate: moment(new Date()).format('YYYY-MM-DD') });
      await setFieldsValue({ salesman: userStore.getUserInfo.username });
      await setFieldsValue({ saleDepartment: userStore.getUserInfo.orgCode });
      await setFieldsValue({ salesmanName: userStore.getUserInfo.realname });
      await setFieldsValue({ saleDepartmentName: userStore.getUserInfo.orgName });
    }
    // 隐藏底部时禁用整个表单
    setProps({ disabled: !data?.showFooter });
  });
  //方法配置
  const [handleChangeTabs, handleSubmit, requestSubTableData, formRef] = useJvxeMethod(
    requestAddOrEdit,
    classifyIntoFormData,
    tableRefs,
    activeKey,
    refKeys
  );

  // //设置标题
  // const title = computed(() => (!unref(isUpdate) ? '新增' : !unref(formDisabled) ? '编辑' : '详情'));

  async function reset() {
    await resetFields();
    activeKey.value = 'saleContractProduct';
    saleContractShipTable.dataSource = [];
    saleContractProductTable.dataSource = [];
  }
  function classifyIntoFormData(allValues) {
    if (allValues.formValue.sourceCode == '' || !allValues.formValue.sourceCode) {
      message.error('请选择报价单');
    } else {
      let main = Object.assign({}, allValues.formValue);
      return {
        ...main, // 展开
        saleContractShipList: allValues.tablesValue[0].tableData,
        saleContractProductList: allValues.tablesValue[1].tableData,
      };
    }
  }
  //表单提交事件
  async function requestAddOrEdit(values) {
    try {
      setModalProps({ confirmLoading: true });
      const isRevise = values.status == '1' ? true : false;
      //提交表单
      await saveOrUpdate(values, isUpdate.value, isRevise);
      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
  function onSearchProject(prop) {
    SelectProjectModalRef.value.getTable();
  }
  async function addProject(data) {
    if (data.length == 0) {
      await setFieldsValue({ quotationProjectName: '' });
      await setFieldsValue({ quotationProject: '' });
    } else {
      await setFieldsValue({ quotationProjectName: data[0].code });
      await setFieldsValue({ quotationProject: data[0].id });
      await setFieldsValue({ quotationCustomerName: data[0].customerId_dictText });
      await setFieldsValue({ quotationCustomer: data[0].customerId });
      customerOption.value.map((item) => {
        if (item.value == data[0].customerId) {
          setFieldsValue({ priority: item.priority });
        }
      });
    }
  }
  function getCustomerOptions() {
    let params = { pageSize: '-1', status: 1 };
    defHttp.get({ url: '/cuspCode/cuspCustomerProfile/list', params }, { isTransformResponse: false }).then((res) => {
      if (res) {
        customerOption.value = [];
        res.result.records.forEach((item) => {
          customerOption.value.push({
            label: item.name,
            value: item.id,
            priority: item.priority,
          });
        });
      }
    });
  }
  async function handleDelete(prop) {
    var newArray = [...saleContractShipTable.dataSource];
    newArray.splice(prop.rowIndex, 1);
    saleContractShipTable.dataSource = newArray;
  }
  function viewAccessory(prop) {
    BaseShipArchiveAccessoriesListRef.value.getTable(prop.row);
  }
  function selectProducts() {
    SelectPrpductModalRef.value.getTable();
  }
  async function seleteQuotation() {
    let fieldsValue = await getFieldsValue();
    fieldsValue.project = fieldsValue.quotationProject;
    fieldsValue.projectName = fieldsValue.quotationProjectName;
    SelectQuotationModalRef.value.getTable(fieldsValue);
  }
  function addProduct(data) {
    data.map((item) => {
      item.productClass = item.classId_dictText;
      item.productCode = item.code;
      item.unit = item.measurementUnit;
      item.productId = item.id;
    });
    var arrProduct = data.concat(saleContractProductTable.dataSource);
    saleContractProductTable.dataSource = arrProduct;
  }
  async function handleDelete1(prop) {
    var newArray = [...saleContractProductTable.dataSource];
    newArray.splice(prop.rowIndex, 1);
    saleContractProductTable.dataSource = newArray;
    if (saleContractProductTable.dataSource.length !== 0) {
      var arr = [];
      saleContractProductTable.dataSource.map((item) => {
        if (item.sourceId) {
          arr.push(item.sourceId);
        }
      });
      if (arr.length == 0) {
        setFieldsValue({ sourceCode: '' });
        notAllowEdit.value = false;
      }
    } else {
      setFieldsValue({ sourceCode: '' });
      notAllowEdit.value = false;
      reset();
      setFieldsValue({ billDate: moment(new Date()).format('YYYY-MM-DD') });
    }
  }
  function addQuotation(data) {
    var time = getFieldsValue()
    data.map((item) => {
      item.model = item.childModel;
      item.sourceId = item.childId;
      item.taxPrice = item.salePrice;
      item.deliveryTime = moment(time.billDate).add(Number(item.deliveryDayChild), 'days').format('YYYY-MM-DD');
    });
    var arrProduct = data.concat(saleContractProductTable.dataSource);
    saleContractProductTable.dataSource = arrProduct;
    notAllowEdit.value = true;
    setFieldsValue({
      sourceCode: data[0].billCode,
      quotationProjectName: data[0].quotationProjectName,
      quotationProject: data[0].quotationProject,
      quotationCustomerName: data[0].quotationCustomerName,
      quotationCustomer: data[0].quotationCustomer,
      priority: data[0].priority,
      productionClass: data[0].productionClass,
      model: data[0].headModel,
      maker: data[0].maker,
      currency: data[0].currency,
      exchangeRate: data[0].exchangeRate,
      paymentTerms:data[0].paymentTerms,
      deliveryTerms:data[0].deliveryTerms
    });
    getShipList(data[0].headId);
  }
  function getShipList(id) {
    let params = { id: id };
    defHttp.get({ url: '/saleCode/saleQuotation/querySaleQuotationShipByMainId', params }, { isTransformResponse: false }).then((res) => {
      if (res) {
        saleContractShipTable.dataSource = res.result;
      }
    });
  }
</script>

<style lang="less" scoped>
  /** 时间和数字输入框样式 */
  :deep(.ant-input-number) {
    width: 100%;
  }

  :deep(.ant-calendar-picker) {
    width: 100%;
  }
  /deep/.ant-form-item {
    margin-bottom: 8px;
  }
  /deep/.ant-tabs-nav {
    margin: 0px !important;
  }

  /deep/.ant-modal-body {
    padding: 24px !important;
  }
</style>
