<template>
  <a-spin :spinning="loading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form v-bind="formItemLayout" name="commissionOrderForm" ref="formRef">
          <a-row>
            <a-col :span="12">
              <a-form-item label="订单编号(bill code)" v-bind="validateInfos.billCode" id="commissionOrderForm-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="commissionOrderForm-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="供应商(supplier)" v-bind="validateInfos.supplierId" id="commissionOrderForm-supplierId" name="supplierId">
                <JSelect   v-model:value="formData.supplierId" :get-option-url="supplierOption" :showField="showField"  @change="handleSupplierChange"></JSelect>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="客户(customer)" v-bind="validateInfos.customer" id="commissionOrderForm-customer" name="customer">
                <JSelect   v-model:value="formData.customerId" :get-option-url="CustomerOption" :showField="showField"  @change="handleCustomerChange"></JSelect>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="佣金合同(commission contract)" v-bind="validateInfos.commissionContract" id="SaleOrderForm-commissionContract" name="commissionContract">
                <a-input-search
                  v-model:value="formData.commissionContractCode"
                  placeholder=""
                  readonly
                  allow-clear
                  enter-button="Search"
                  AutoComplete="off"
                  @search="onSearchCommissionContract"
                  :disabled ='commissionOrderFormProductTable.dataSource&&commissionOrderFormProductTable.dataSource.length!==0'
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="币种(currency)" v-bind="validateInfos.currency" id="commissionContractForm-currency" name="currency">
                <JDictSelectTag v-model:value="formData.currency" placeholder="请选择" dictCode="currency"  />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="佣金(commission)" v-bind="validateInfos.commission" id="commissionOrderForm-commission" name="commission">
                <a-input v-model:value="formData.commission" placeholder="" allow-clear  disabled/>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="佣金比例(commissionRate)" v-bind="validateInfos.commissionRate" id="commissionOrderForm-commissionRate" name="commissionRate">
                <a-input v-model:value="formData.commissionRate" placeholder="" allow-clear  :disabled="formData.commissionContractCode&&formData.commissionContractCode!==''"/>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="销售部门(sale department)"
                v-bind="validateInfos.saleDepartmen"
                id="commissionOrderForm-saleDepartmen"
                name="saleDepartmen"
              >
                <a-input v-model:value="formData.saleDepartmenName" placeholder="请输入" allow-clear disabled />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="业务员(salesman)" v-bind="validateInfos.salesman" id="commissionOrderForm-salesman" name="salesman">
                <a-input v-model:value="formData.salesmanName" placeholder="请输入采购员(salesman)" allow-clear disabled />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="备注(notes)" v-bind="validateInfos.notes" id="commissionOrderForm-notes" name="notes">
                <a-input v-model:value="formData.notes" AutoComplete="off" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="附件(attachs)"  v-bind="validateInfos.attachs"  id="commissionOrderForm-attachs"   name="attachs">
                <JUpload v-model:value="formData.attachs"></JUpload>
              </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="佣金订单 - 产品明细(product details)" key="commissionOrderFormProduct" :forceRender="true">
        <a-button type="primary" style="margin-right: 1%;margin-bottom: 1%;" @click="selectProductList" :disabled="formData.commissionContractCode!==''"> 选择产品(select products)</a-button>
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="commissionOrderFormProductTableRef"
          :loading="commissionOrderFormProductTable.loading"
          :columns="commissionOrderFormProductTable.columns"
          :dataSource="commissionOrderFormProductTable.dataSource"
          :maxHeight="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          asyncRemove
          @valueChange="changeValues"
        >
          <template #action="props">
            <a-popconfirm title="确定删除吗？" @confirm="handleDelete(props)">
              <a>删除(delete)</a>
            </a-popconfirm>
          </template>
        </j-vxe-table>
      </a-tab-pane>
    </a-tabs>
    <SelectPrpductModal ref="SelectPrpductModalRef" @selectProduct ='addProduct'></SelectPrpductModal>
    <SelectCommissionContractModal ref="SelectCommissionContractModalRef" @selectCommissionContract ='addCommissionContract'></SelectCommissionContractModal>
  </a-spin>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, computed, toRaw } from 'vue';
  import { useValidateAntFormAndTable } from '/@/hooks/system/useJvxeMethods';
  import { queryProductListByMainId, queryDataById, supplierOption, saveOrUpdate,CustomerOption,queryProductListByMainIdFormCon} from '../commissionOrderForm.api';
  import { JVxeTable } from '/@/components/jeecg/JVxeTable';
  import { ProductColumns } from '../commissionOrderForm.data';
  import SelectPrpductModal from '../../../publicComponents/SelectPrpductModal.vue';
  import SelectCommissionContractModal from './SelectCommissionContractModal.vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
  import { JDictSelectTag, ApiSelect,JSelect } from '/@/components/Form';
  import { Form, message } from 'ant-design-vue';
  import { useUserStore } from '/@/store/modules/user';
  import moment from 'moment';
  const useForm = Form.useForm;
  export default defineComponent({
    name: 'commissionOrderForm',
    components: {
      JVxeTable,
      JFormContainer,
      SelectPrpductModal,
      JUpload,
      JDictSelectTag,
      ApiSelect,
      SelectCommissionContractModal,
      JSelect
    },
    props: {
      formDisabled: {
        type: Boolean,
        default: false,
      },
      formData: { type: Object, default: () => {} },
      formBpm: { type: Boolean, default: true },
    },
    emits: ['success'],
    setup(props, { emit }) {
      var showField = ref('currency_dictText+name');
      const userStore = useUserStore();
      const loading = ref(false);
      const formRef = ref();
      const SelectCommissionContractModalRef = ref();
      const SelectPrpductModalRef = ref();
      const commissionOrderFormProductTableRef = ref();
      const commissionOrderFormProductTable = reactive<Record<string, any>>({
        loading: false,
        columns: ProductColumns,
        dataSource: [],
      });
      const activeKey = ref('commissionOrderFormProduct');
      const formData = reactive<Record<string, any>>({
        id: '',
        status: undefined,
        delFlag: undefined,
        submit: undefined,
        supplierPayment:undefined,
        billCode: '',
        billDate: moment(new Date()).format('YYYY-MM-DD'),
        supplierId: '',
        supplierName: '',
        customerId:'',
        customerName:'',
        currency: '',
        salesman:'',
        salesmanName:'',
        saleDepartmen:'',
        saleDepartmenName:'',
        notes: '',
        attachs: '',
        commissionContractCode:'',
        commissionContract:''
      });

      //表单验证
      const validatorRules = reactive({
        supplierId: [
          { required: true, message: '请选择供应商(supplier)' }
        ],
        currency: [
          { required: true, message: '请选择币种(currency)' }
        ],
      });
      const {resetFields, validate, validateInfos} = useForm(formData, validatorRules, {immediate: false});
      const dbData = {};
      const formItemLayout = {
        labelCol: { xs: { span: 24 }, sm: { span: 7 } },
        wrapperCol: { xs: { span: 24 }, sm: { span: 15 } },
        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;
      });

      function add() {
        resetFields();
        commissionOrderFormProductTable.dataSource = [];
        activeKey.value = 'commissionOrderFormProduct';
        formData.salesman = userStore.getUserInfo.username;
        formData.salesmanName = userStore.getUserInfo.realname;
        formData.saleDepartmen = userStore.getUserInfo.orgCode;
        formData.saleDepartmenName = userStore.getUserInfo.orgName;
      }
      async function edit(row) {
        //主表数据
        await queryMainData(row.id);
        const commissionOrderFormProductDataList = await queryProductListByMainId(row['id']);
        commissionOrderFormProductTable.dataSource = [...commissionOrderFormProductDataList];
      }

      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, {
        platCommissionOrderProduct: commissionOrderFormProductTableRef,
      });

      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() {
        var xTable = commissionOrderFormProductTableRef.value!.getXTable()
        if(xTable.data.length==0){
          message.warning('请添加产品明细')
        }else{
          commissionOrderFormProductTableRef.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 selectProductList(){
        SelectPrpductModalRef.value.getTable()
      }
      function addProduct(data) {
        formData.commissionContractCode = ''
        formData.commissionContract =''
        formData.currency = ''
        formData.commissionRate =''
        data.map((item) => {
          item.productClass = item.classId_dictText;
          item.productCode = item.code;
          item.productId = item.id;
          item.id = undefined
          item.notesChild = ''
        });
        var xTable = commissionOrderFormProductTableRef.value!.getXTable();
        var arrProduct = xTable.data.concat(data);
        commissionOrderFormProductTable.dataSource = arrProduct;
        var arr = commissionOrderFormProductTable.columns
        arr.map(item=>{
          if(item.key=='commissionRateChild'){
            item.type = "input-number"
          }
        })
        commissionOrderFormProductTable.columns=arr
      }      
      //产品明细-删除行
      function handleDelete(prop) {
        var xTable = commissionOrderFormProductTableRef.value!.getXTable()
        var newArray = [...xTable.data]
        newArray.splice(prop.rowIndex, 1)
        commissionOrderFormProductTable.dataSource = newArray  
        if(commissionOrderFormProductTable.dataSource.length==0){
          formData.commissionContractCode = ''
          formData.commissionContract =''
          formData.currency = ''
          formData.commissionRate =''
        }
      }      
      /**
       * 值改变事件触发-树控件回调
       * @param key
       * @param value
       */
      function handleFormChange(key, value) {
        formData[key] = value;
      }
      function onSearchCommissionContract(){
        SelectCommissionContractModalRef.value.getTable()
      }
      function addCommissionContract(data){
        formData.commissionContractCode = data[0].billCode
        formData.commissionContract = data[0].id
        formData.currency = data[0].currency
        formData.commissionRate = data[0].commissionRate
        formData.supplierId = data[0].supplierId
        formData.supplierName = data[0].supplierName
        getSonListFormCon(data[0].id)
      }
      async function getSonListFormCon(id){
        commissionOrderFormProductTable.dataSource=[]
        const commissionOrderFormProductDataList = await queryProductListByMainIdFormCon(id);
        commissionOrderFormProductTable.dataSource = [...commissionOrderFormProductDataList];
        var arr = commissionOrderFormProductTable.columns
        arr.map(item=>{
          if(item.key=='commissionRateChild'){
            item.type = "normal"
          }
        })
        commissionOrderFormProductTable.columns=arr
      }
      function changeValues(prop){
        if (prop.col.key == 'taxPrice'||prop.col.key == 'quantity') {
          if (prop.row.taxPrice&&prop.row.quantity) {
            prop.row.taxMoney = Number(prop.row.taxPrice)*Number(prop.row.quantity);
            if(prop.row.commissionRateChild){
              prop.row.commission = Number(prop.row.taxMoney)*Number(prop.row.commissionRateChild)/100
            }
          }
        }
        if (prop.col.key == 'commissionRateChild') {
          if (prop.row.taxMoney) {
            prop.row.commission = Number(prop.row.taxMoney)*Number(prop.row.commissionRateChild)/100
          }
        }
        getMainCommission()
      }
      function getMainCommission(){
        var xTable = commissionOrderFormProductTableRef.value!.getXTable()
        var newArray = [...xTable.data]
        var allCommission = 0,
        allMoney = 0
        newArray.map(item=>{
          allCommission += item.commission&&item.commission!==''?Number(item.commission):0
          allMoney+=item.taxMoney&&item.taxMoney!==''?Number(item.taxMoney):0
        })
        formData.commission = allCommission
        formData.commissionRate = (Number(allCommission)/Number(allMoney)*100).toFixed(2)
      }
      async function handleSupplierChange(prop){
        if (prop) {
          var params = { id: prop };
          var obj = await supplierOption(params);
          formData.supplierName = obj.records[0].name;
        } else {
          formData.supplierId = '';
          formData.supplierName = '';
        }
      }
      async function handleCustomerChange(prop){
        if (prop) {
          var params = { id: prop };
          var obj = await CustomerOption(params);
          formData.customerName = obj.records[0].name;
        } else {
          formData.customerId = '';
          formData.customerName = '';
        }
      }
      return {
        commissionOrderFormProductTableRef,
        commissionOrderFormProductTable,
        validatorRules,
        validateInfos,
        activeKey,
        loading,
        formData,
        setFieldsValue,
        handleFormChange,
        formItemLayout,
        disabled,
        getFormData,
        submitForm,
        add,
        edit,
        formRef,
        selectProductList,
        SelectPrpductModalRef,
        addProduct,
        handleDelete,
        supplierOption,
        CustomerOption,
        onSearchCommissionContract,
        SelectCommissionContractModalRef,
        addCommissionContract,
        changeValues,
        showField,
        handleSupplierChange,
        handleCustomerChange
      };
    },
  });
</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>
