<template>
  <a-spin :spinning="loading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form v-bind="formItemLayout" name="saleInvoiceForm" ref="formRef">
          <a-row>
            <a-col :span="12">
							<a-form-item label="发票编号(bill code)" v-bind="validateInfos.billCode" id="saleInvoiceForm-billCode" name="billCode" :labelCol="formItemLayout.labelCol1" :wrapperCol="formItemLayout.wrapperCol1">
								<a-input v-model:value="formData.billCode" placeholder="自动生成" disabled></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="发票日期(bill date)" v-bind="validateInfos.billDate" id="saleInvoiceForm-billDate" name="billDate">
								<a-date-picker placeholder="请选择发票日期(bill date)"  v-model:value="formData.billDate"  value-format="YYYY-MM-DD" disabled  style="width: 100%"  allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="项目(project)" v-bind="validateInfos.projectName" id="saleInvoiceForm-projectName" name="projectName">
								<a-input-search v-model:value="formData.projectName" placeholder="请输入项目(project)"  allow-clear enter-button="Search" :disabled="notAllowEdit" @search="onSearchProject"></a-input-search>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="购方(buyer)" v-bind="validateInfos.buyer" id="saleInvoiceForm-buyer" name="buyer" :labelCol="formItemLayout.labelCol1" :wrapperCol="formItemLayout.wrapperCol1">
                <JSelectInput   v-model:value="formData.buyer"  placeholder="请选择" :options="customerOption" disabled></JSelectInput>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="购方税号(buyer's tax number)" v-bind="validateInfos.buyerTaxNumber" id="saleInvoiceForm-buyerTaxNumber" name="buyerTaxNumber">
                <a-input v-model:value="formData.buyerTaxNumber" placeholder="请输入"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="购方电话(buyer's telphone)" v-bind="validateInfos.buyerTelphone" id="saleInvoiceForm-buyerTelphone" name="buyerTelphone">
                <a-input v-model:value="formData.buyerTelphone" placeholder="请输入"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="购方地址(buyer's addres)" v-bind="validateInfos.buyerAddres" id="saleInvoiceForm-buyerAddres" name="buyerAddres">
                <a-input v-model:value="formData.buyerAddres" placeholder="请输入"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="购方银行(buyer's bank)" v-bind="validateInfos.buyerBank" id="saleInvoiceForm-buyerBank" name="buyerBank">
                <a-input v-model:value="formData.buyerBank" placeholder="请输入"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="购方银行账户(buyer's bank account)" v-bind="validateInfos.buyerBankAccount" id="saleInvoiceForm-buyerBankAccount" name="buyerBankAccount">
                <a-input v-model:value="formData.buyerBankAccount" placeholder="请输入"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="开票抬头(invoice header)" v-bind="validateInfos.invoiceHeader" id="saleInvoiceForm-invoiceHeader" name="invoiceHeader">
                <a-input v-model:value="formData.invoiceHeader" placeholder="请输入"  allow-clear disabled></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="开票地址(invoice address)" v-bind="validateInfos.invoiceAddress" id="saleInvoiceForm-invoiceAddress" name="invoiceAddress">
                <a-input v-model:value="formData.invoiceAddress" placeholder="请输入"  allow-clear disabled></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="销方(saller)" v-bind="validateInfos.saller" id="saleInvoiceForm-saller" name="saller" :labelCol="formItemLayout.labelCol1" :wrapperCol="formItemLayout.wrapperCol1">
                <JSelectInput   v-model:value="formData.saller"  placeholder="请选择" :options="customerOption" ></JSelectInput>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="销方税号(saller's tax number)" v-bind="validateInfos.sallerTaxNumber" id="saleInvoiceForm-sallerTaxNumber" name="sallerTaxNumber">
                <a-input v-model:value="formData.sallerTaxNumber" placeholder="请输入"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="销方电话(saller's telphone)" v-bind="validateInfos.sallerTelphone" id="saleInvoiceForm-sallerTelphone" name="sallerTelphone">
                <a-input v-model:value="formData.sallerTelphone" placeholder="请输入"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="销方地址(saller's address)" v-bind="validateInfos.invoiceAddress" id="saleInvoiceForm-sallerAddress" name="sallerAddress">
                <a-input v-model:value="formData.sallerAddress" placeholder="请输入"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="销方银行(saller's bank)" v-bind="validateInfos.sallerBank" id="saleInvoiceForm-sallerBank" name="sallerBank">
                <a-input v-model:value="formData.sallerBank" placeholder="请输入"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="销方银行账户(saller's bank account)" v-bind="validateInfos.sallerBankAccount" id="saleInvoiceForm-sallerBankAccount" name="sallerBankAccount">
                <a-input v-model:value="formData.sallerBankAccount" placeholder="请输入"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="F号(F number)" v-bind="validateInfos.fnumber" id="saleInvoiceForm-fnumber" name="fnumber">
                <a-input v-model:value="formData.fnumber" placeholder="请输入"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						
            <a-col :span="12">
							<a-form-item label="备注(notes)" v-bind="validateInfos.quotationNotes" id="saleInvoiceForm-notes" name="notes" :labelCol="formItemLayout.labelCol1" :wrapperCol="formItemLayout.wrapperCol1">
								<a-input v-model:value="formData.notes" placeholder="请输入报价备注(quotation notes)"  allow-clear AutoComplete="off"></a-input>
							</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="销售发票 - 发票明细(invoice details)" key="saleInvoiceDetails" :forceRender="true">
        <a-button type="primary"  style="margin-right: 1%;margin-bottom: 1%;" @click="selectDeliveryList"> 选择发货通知单(select delevery notice)</a-button>
        <a-button type="primary" @click="selectCommissionList"> 选择佣金订单(selete commission order)</a-button>
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="saleInvoiceDetailsTableRef"
          :loading="saleInvoiceDetailsTable.loading"
          :columns="saleInvoiceDetailsTable.columns"
          :dataSource="saleInvoiceDetailsTable.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          asyncRemove
          @valueChange="changeValues"
          >
            <template #action="props">
                  <a-popconfirm title="确定删除吗？" @confirm="handleDelete1(props)">
                    <a>删除(delete)</a>
                  </a-popconfirm>
              </template>
          </j-vxe-table>
      </a-tab-pane>
      <a-tab-pane tab="销售发票 - 船明细(ship details)" key="saleInvoiceFormShip" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="saleInvoiceFormShipTableRef"
          :loading="saleInvoiceFormShipTable.loading"
          :columns="saleInvoiceFormShipTable.columns"
          :dataSource="saleInvoiceFormShipTable.dataSource"
          :height="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>
    <SelectDeliveryNoticeModal ref="SelectDeliveryNoticeModalRef"></SelectDeliveryNoticeModal>
    <BaseShipArchiveAccessoriesModal ref="BaseShipArchiveAccessoriesListRef"></BaseShipArchiveAccessoriesModal>
    <SelectCommissionOrderModal ref="SelectCommissionOrderModalRef"></SelectCommissionOrderModal>
    <SelectProjectModal ref="SelectProjectModalRef" @selectProject="addProject"></SelectProjectModal>
  </a-spin>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, computed, toRaw, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useValidateAntFormAndTable } from '/@/hooks/system/useJvxeMethods';
  import { querysaleInvoiceFormShipListByMainId,querySaleInvoiceDetailListByMainId,queryDataById, saveOrUpdate } from '../salesInvoiceForm.api';
  import { JVxeTable } from '/@/components/jeecg/JVxeTable';
  import {saleInvoiceShipColumns, saleInvoiceDetailColumns} from '../salesInvoiceForm.data';
  import BaseShipArchiveAccessoriesModal from '../../../publicComponents/BaseShipArchiveAccessoriesModal.vue';
  import SelectProjectModal from '../../../publicComponents/SelectProjectModal.vue';
  import SelectDeliveryNoticeModal from './SelectDeliveryNoticeModal.vue';
  import SelectCommissionOrderModal from './SelectCommissionOrderModal.vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
  import { JDictSelectTag,JSelectMultiple} from '/@/components/Form';
  import JSelectInput from '/@/components/Form/src/jeecg/components/JSelectInput.vue';
  import { Form,message } from 'ant-design-vue';
  import { useUserStore } from '/@/store/modules/user';
  import moment from 'moment';
  const userStore = useUserStore();
  const useForm = Form.useForm;
  export default defineComponent({
    name: "saleInvoiceForm",
    components:{
      JVxeTable,
			JFormContainer,
      BaseShipArchiveAccessoriesModal,
      JUpload,
      SelectProjectModal,
      JDictSelectTag,
      JSelectInput,
      JSelectMultiple,
      SelectDeliveryNoticeModal,
      SelectCommissionOrderModal
    },
    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 SelectDeliveryNoticeModalRef = ref();
      const SelectCommissionOrderModalRef = ref();
      var SelectProjectModalRef = ref()
      const saleInvoiceFormShipTableRef = ref();
      const saleInvoiceFormShipTable = reactive<Record<string, any>>({
        loading: false,
        columns:saleInvoiceShipColumns,
        dataSource: []
      });
      const saleInvoiceDetailsTableRef = ref();
      const saleInvoiceDetailsTable = reactive<Record<string, any>>({
        loading: false,
        columns: saleInvoiceDetailColumns,
        dataSource: []
      });
      var BaseShipArchiveAccessoriesListRef = ref();
      const activeKey = ref('saleInvoiceDetails');
      var notAllowEdit = ref(false);
      var classOption = ref([]);
      var customerOption =ref([]);
      const formData = reactive<Record<string, any>>({
        id: '',
        status: undefined,
        delFlag: undefined,
        sourceCode:'',
        billDate: moment(new Date()).format('YYYY-MM-DD'),   
        billCode: '',   
        project: '',   
        projectName: '',   
        buyer: '',   
        buyerName: '',   
        buyerTelphone: '',   
        buyerAddres: '',   
        buyerBank: '',   
        buyerBankAccount: '',   
        invoiceHeader: '',   
        invoiceAddress:"",
        sallerTaxNumber: '',   
        sallerTelphone: '',
        sallerAddress: '',
        sallerBank: '',
        sallerBankAccount: '',
        fnumber:'',
        notes:'',         
      });

      //表单验证
      const validatorRules = reactive({
      });
      const {resetFields, validate, validateInfos} = useForm(formData, validatorRules, {immediate: false});
      const dbData = {};
      const formItemLayout = {
        labelCol: {xs: {span: 24}, sm: {span: 8}},
        wrapperCol: {xs: {span: 24}, sm: {span: 13}},
        labelCol1: {xs: {span: 24}, sm: {span: 8}},
        wrapperCol1: {xs: {span: 24}, sm: {span: 13}},
      };

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

      
      //新增方法
      function add() {
        resetFields();
        saleInvoiceFormShipTable.dataSource = [];
        saleInvoiceDetailsTable.dataSource = [];
        activeKey.value = 'saleInvoiceDetails'
        getOptiom()
        getCustomerOptions()
        formData.salesman=userStore.getUserInfo.username;
        formData.saleDepartment = userStore.getUserInfo.orgCode
        notAllowEdit.value = false
      }
      //编辑方法
      async function edit(row) {
        //主表数据
        await queryMainData(row.id);
        //子表数据
        const saleInvoiceFormShipDataList = await querysaleInvoiceFormShipListByMainId(row['id']);
        saleInvoiceFormShipTable.dataSource = [...saleInvoiceFormShipDataList];
        const saleInvoiceDetailsDataList = await querySaleInvoiceDetailListByMainId(row['id']);
        saleInvoiceDetailsTable.dataSource = [...saleInvoiceDetailsDataList];
        getOptiom()
        getCustomerOptions()
        notAllowEdit.value=true
      }
      //获取主表
      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, {
        'saleQuotationShip': saleInvoiceFormShipTableRef,
        'saleQuotationProduct': saleInvoiceDetailsTableRef,
      });
      //获取表单信息
      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.warning('请选择发票明细')
        }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];
          });
        }
      }

      /**
       * 值改变事件触发-树控件回调
       * @param key
       * @param value
       */
      function handleFormChange(key, value) {
        formData[key] = value;
      }
       //产品明细-删除行
      async function handleDelete1(prop) {
        var newArray = [...saleInvoiceDetailsTable.dataSource]
        newArray.splice(prop.rowIndex, 1)
        saleInvoiceDetailsTable.dataSource = newArray  
        if( saleInvoiceDetailsTable.dataSource.length!==0){
          var arr = []
          saleInvoiceDetailsTable.dataSource.map(item=>{
            if(item.sourceId){
              arr.push(item.sourceId)
            } 
          })
          if(arr.length==0){
            formData.sourceCode=''
            notAllowEdit.value=false
          }
        }else{
           formData.sourceCode=''
           notAllowEdit.value=false
        }
      }
      //选择项目
      function addProject(data) {
        if(data.length==0){
          formData.quotationProject = 
          formData.quotationProjectName = ''
        }else{
          formData.quotationProject = data[0].id
          formData.quotationProjectName = data[0].name
          formData.quotationCustomer =data[0].customerId
          formData.quotationCustomerName =data[0].customerId_dictText
        }
      }
      //获取客户列表
      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,
                  intermediatorCommission:item.intermediatorCommission,
                  commission:item.commission
                })
              })
            }
          })
      }
      //查看配件信息
      function viewAccessory(prop){
        BaseShipArchiveAccessoriesListRef.value.getTable(prop.row)
      }
      //选择项目  
      function onSearchProject(){
        SelectProjectModalRef.value.getTable()
      }
      //获取产品分类下拉框
      function getOptiom(){
        defHttp
            .get({ url: 'baseCode/baseProductClass/list'}, { isTransformResponse: false })
            .then((res) => {
                if (res.success) {
                  classOption.value = []
                  res.result.records.forEach(element => {
                      var obj = {
                        label: element.name?element.name:'无名称请维护',
                        value: element.id?element.id:''
                      };
                      classOption.value.push( obj)
                  });    
                }
            })
            .finally(() => {
                // loading.value = false;
            });
      }  
      function changeValues(prop){
        if(prop.col.key=='purchasePrice'||prop.col.key=='taxRate'||prop.col.key=='tariff'||prop.col.key=='discount'||prop.col.key=='grossMargin'||prop.col.key=='customerCommision'||prop.col.key=='intermediatorCommission'){
          if(prop.row.purchasePrice&&prop.row.taxRate&&prop.row.tariff&&prop.row.discount&&prop.row.grossMargin&&prop.row.customerCommision&&prop.row.intermediatorCommission){
            var num= prop.row.purchasePrice/1*(1+prop.row.taxRate/100)*(1+prop.row.tariff/100)*(1-prop.row.discount/100)/(1-prop.row.grossMargin/100-prop.row.customerCommision/100-prop.row.intermediatorCommission/100)
            prop.row.salePrice = num.toFixed(2)
            if(prop.row.quantity){
              prop.row.taxAmount =  (prop.row.salePrice*prop.row.quantity).toFixed(2)
            }
          }
        }
        if(prop.col.key=='quantity'&&prop.row.salePrice&&prop.row.quantity){
          prop.row.taxAmount =  (prop.row.salePrice*prop.row.quantity).toFixed(2)
        }
      }
      function selectDeliveryList(){
        SelectDeliveryNoticeModalRef.value.getTable()
      }
      function selectCommissionList(){
        SelectCommissionOrderModalRef.value.getTable()
      }
      return {
        saleInvoiceFormShipTableRef,
        saleInvoiceFormShipTable,
        saleInvoiceDetailsTableRef,
        saleInvoiceDetailsTable,
        validatorRules,
        validateInfos,
        activeKey,
        loading,
        formData,
        setFieldsValue,
        handleFormChange,
        formItemLayout,
        disabled,
        getFormData,
        submitForm,
        add,
        edit,
        formRef,
        BaseShipArchiveAccessoriesListRef,
        viewAccessory,
        handleDelete1,
        SelectProjectModalRef,
        onSearchProject,
        addProject,
        getOptiom,
        classOption,
        getCustomerOptions,
        customerOption,
        notAllowEdit,
        changeValues,
        SelectDeliveryNoticeModalRef,
        selectDeliveryList,
        SelectCommissionOrderModalRef,
        selectCommissionList
      }
    }
  });
</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;
  }
      
</style>
