<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="发票编号(invoice code)" v-bind="validateInfos.invoiceCode" id="saleInvoiceForm-invoiceCode" name="invoiceCode" :labelCol="formItemLayout.labelCol1" :wrapperCol="formItemLayout.wrapperCol1">
								<a-input v-model:value="formData.invoiceCode" 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)" readonly 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="业务类型(busymess type)" v-bind="validateInfos.busynessType" id="saleInvoiceForm-busynessType" name="busynessType">
								<JDictSelectTag v-model:value="formData.busynessType" placeholder="请选择" dictCode="	busyness_type" style="width: 100%;" :disabled="notAllowEdit"/>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="购方(buyer)" v-bind="validateInfos.customer" id="saleInvoiceForm-customer" name="customer" :labelCol="formItemLayout.labelCol1" :wrapperCol="formItemLayout.wrapperCol1">   
                <ApiSelect
                  :api="getCustomerOptions"
                  showSearch
                  v-model:value="formData.customer"
                  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="购方税号(buyer's tax number)" v-bind="validateInfos.buyerTaxNumber" id="saleInvoiceForm-buyerTaxNumber" name="buyerTaxNumber">
                <a-input v-model:value="formData.buyerTaxNumber" placeholder="请输入"  allow-clear AutoComplete="off"></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 AutoComplete="off"></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="购方地址(buyer's address)" v-bind="validateInfos.buyerAddress" id="saleInvoiceForm-buyerAddress" name="buyerAddress">
                <a-input v-model:value="formData.buyerAddress" placeholder="请输入"  allow-clear AutoComplete="off"></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 AutoComplete="off"></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="购方银行账户(buyer's bank account)" v-bind="validateInfos.buyerAccount" id="saleInvoiceForm-buyerAccount" name="buyerAccount">
                <a-input v-model:value="formData.buyerAccount" placeholder="请输入"  allow-clear AutoComplete="off"></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="销方(seller)" v-bind="validateInfos.seller" id="saleInvoiceForm-seller" name="saller" :labelCol="formItemLayout.labelCol1" :wrapperCol="formItemLayout.wrapperCol1">
                <ApiSelect
                  :api="listHeard"
                  showSearch
                  v-model:value="formData.seller"
                  optionFilterProp="label"
                  resultField="records"
                  labelField="name"
                  valueField="id"
                  :params='{pageSize:-1}'
                  @change="changeSeller"
                />
              </a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="销方税号(seller's tax number)" v-bind="validateInfos.sellerTaxNumber" id="saleInvoiceForm-sellerTaxNumber" name="sellerTaxNumber">
                <a-input v-model:value="formData.sellerTaxNumber" placeholder="请输入"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="销方电话(seller's telphone)" v-bind="validateInfos.sellerTelphone" id="saleInvoiceForm-sellerTelphone" name="sellerTelphone">
                <a-input v-model:value="formData.sellerTelphone" placeholder="请输入"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="销方地址(seller's address)" v-bind="validateInfos.sellerAddress" id="saleInvoiceForm-sellerAddress" name="sellerAddress">
                <a-input v-model:value="formData.sellerAddress" placeholder="请输入"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="销方银行(seller's bank)" v-bind="validateInfos.sellerBank" id="saleInvoiceForm-sellerBank" name="sellerBank">
                <a-input v-model:value="formData.sellerBank" placeholder="请输入"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="销方银行账户(seller's bank account)" v-bind="validateInfos.sellerBankAccount" id="saleInvoiceForm-sellerBankAccount" name="sellerBankAccount">
                <a-input v-model:value="formData.sellerBankAccount" 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 AutoComplete="off"></a-input>
							</a-form-item>
						</a-col>
						
            <a-col :span="12">
							<a-form-item label="备注(notes)" v-bind="validateInfos.notes" id="saleInvoiceForm-notes" name="notes" :labelCol="formItemLayout.labelCol1" :wrapperCol="formItemLayout.wrapperCol1">
								<a-input v-model:value="formData.notes" placeholder="请输入备注(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"
          :maxHeight="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"
          :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>
    <SelectDeliveryNoticeModal ref="SelectDeliveryNoticeModalRef" @addDelivery="addSonList"></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,listHeard } 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 {  ApiSelect, } from '/@/components/Form/index';
  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,
      JSelectMultiple,
      SelectDeliveryNoticeModal,
      SelectCommissionOrderModal,
      ApiSelect
    },
    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 customerOption =ref([]);
      const formData = reactive<Record<string, any>>({
        id: '',
        status: undefined,
        delFlag: undefined,
        sourceCode:'',
        billDate: moment(new Date()).format('YYYY-MM-DD'),   
        invoiceCode: '',   
        project: '',   
        projectName: '',   
        customer: '',   
        customerName: '',   
        buyerTaxNumber: '',  
        buyerTelphone:'', 
        buyerAddress: '',   
        buyerBank: '',   
        buyerAccount: '',   
        invoiceHeader: '',   
        invoiceAddress:"",
        seller:'',
        sellerName:'',
        sellerTaxNumber: '',   
        sellerTelphone: '',
        sellerAddress: '',
        sellerBank: '',
        sellerBankAccount: '',
        fnumber:'',
        notes:'',         
        busynessType:''
      });

      //表单验证
      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'
        getCustomerOptions()
        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];
        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, {
        'saleInvoiceShip': saleInvoiceFormShipTableRef,
        'saleInvoiceProduct': 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() {
        const mainData = await getFormData();
        const subData = await getSubFormAndTableData();
        if(!subData.saleInvoiceProductList||subData.saleInvoiceProductList.lenght==0){
          message.warning('请添加发票明细')
        }else{
          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){
            notAllowEdit.value=true
        }else{
           notAllowEdit.value=false
        }
      }
      //选择项目
      function addProject(data) {
        if(data.length==0){
          formData.project = 
          formData.projectName = ''
        }else{
          formData.project = data[0].id
          formData.projectName = data[0].code
          formData.customer =data[0].customerId
          formData.customerName =data[0].customerId_dictText
        }
      }
      //获取客户列表
      function getCustomerOptions(params){
        return defHttp.get({url:'/cuspCode/cuspCustomerProfile/list',params});
      }
      //查看配件信息
      function viewAccessory(prop){
        BaseShipArchiveAccessoriesListRef.value.getTable(prop.row)
      }
      //选择项目  
      function onSearchProject(){
        SelectProjectModalRef.value.getTable()
      }
      function changeValues(prop){
        if(prop.col.key=='taxPrice'||prop.col.key=='quantity'){
          prop.row.taxPrice = prop.row.taxPrice&&prop.row.taxPrice!==''?prop.row.taxPrice:0
          prop.row.quantity = prop.row.quantity&&prop.row.quantity!==''?prop.row.quantity:0
          var num= Number(prop.row.taxPrice)*Number(prop.row.quantity)
          prop.row.taxMoney = num.toFixed(2)
          prop.row.taxRate  = prop.row.taxRate?prop.row.taxRate:0
          prop.row.taxAmount = Number(prop.row.taxMoney)* Number(prop.row.taxRate)/100
        }
      }
      function selectDeliveryList(){
        if(formData.busynessType=='佣金业务'){
          message.warning('佣金业务不能选择发货通知单')
        }else if(saleInvoiceDetailsTable.dataSource==0||saleInvoiceDetailsTable.dataSource==undefined){
          SelectDeliveryNoticeModalRef.value.getTable(formData)
        }else{
          message.warning('发票明细只可有一条数据')
        }
      }
      function selectCommissionList(){
        if(formData.busynessType=='普通业务'){
          message.warning('普通业务不能选择佣金订单')
        }else if(saleInvoiceDetailsTable.dataSource==0||saleInvoiceDetailsTable.dataSource==undefined){
          SelectCommissionOrderModalRef.value.getTable()
        }else{
          message.warning('发票明细只可有一条数据')
        }
      }
      function addSonList(data){
        data.map(item=>{
          item.sourceId = item.childId
          item.quantity =  item.quantity&& item.quantity!==''?item.quantity:0
          item.taxPrice =  item.taxPrice&& item.taxPrice!==''?item.taxPrice:0
          item.taxMoney =  item.money&& item.money!==''?item.money:0
          //暂无税率字段，设置默认为1
          item.taxRate = item.taxRate?item.taxRate:0
          item.taxAmount =item.taxMoney*item.taxRate/100
        })
        notAllowEdit.value=true
        var arrSonFormDelivery = data.concat(saleInvoiceDetailsTable.dataSource)
        saleInvoiceDetailsTable.dataSource=arrSonFormDelivery     
        formData.project = data[0].project
        formData.projectName = data[0].projectName
        formData.customer = data[0].customer
        formData.customerName = data[0].customerName
        formData.sourceCode =data[0].billCode
        formData.invoiceHeader=data[0].invoiceHeader
        formData.invoiceAddress=data[0].invoiceAddress
        formData.busynessType = '普通业务'
        getCustomerOptions({pageSize:-1,id:data[0].customer}).then(res=>{
          formData.buyerTaxNumber = res.records[0].dutyParagraph
          formData.buyerTelphone = res.records[0].phone
          formData.buyerAddress = res.records[0].invoiceAddress
        })

        getShipDetail(data[0].headId,'delivery')
      }
      function getShipDetail(id,status){
        let params = {id:id}
        let url = status=='delivery'?'/saleCode/saleDelivery/querySaleDeliveryShipByMainId':'/saleCode/saleDelivery/querySaleContractShipByMainId'
        defHttp.get({url:url,params}, { isTransformResponse: false }).then(res=>{
           if(res){
            saleInvoiceFormShipTable.dataSource = res.result
           }
        })
      }
      async function changeSeller(value){
        var param={id:value}
        var result=await listHeard(param)     
        formData.sellerName =result.records[0].name
        formData.sellerTaxNumber =result.records[0].taxcode
        formData.sellerTelphone =result.records[0].telphone
        formData.sellerAddress =result.records[0].address
        formData.sellerBank =result.records[0].bank
        formData.sellerBankAccount =result.records[0].bankAccount
      }
      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,
        getCustomerOptions,
        customerOption,
        notAllowEdit,
        changeValues,
        SelectDeliveryNoticeModalRef,
        selectDeliveryList,
        SelectCommissionOrderModalRef,
        selectCommissionList,
        addSonList,
        listHeard,
        changeSeller
      }
    }
  });
</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>
