<template>
  <ele-modal
    custom-class="ele-dialog-form long-dialog-form"
    :centered="true"
    :visible.sync="addAccountDialogFlag"
    :title="title"
    :append-to-body="true"
    :close-on-click-modal="false"
    :maxable="true"
    :resizable="true"
    width="85%"
    :before-close="cancel"
  >
    <div v-loading="loading">
      <!--销售表单-->
      <sale-form
        @handleSearch="handleSearch"
        :dataForm.sync="dataForm"
        :datasource.sync="datasource"
        :contactData="contactData"
        :saleOrderData="saleOrderData"
        :recorpayList.sync="recorpayList"
        :dialogType="dialogType"
        ref="saleFormRef"
      ></sale-form>
      <headerTitle title="对账明细" style="margin-top: 30px">
        <template v-slot>
          <el-row style="font-weight: 700; color: red">
            <span>订单总金额：</span>
            <span>{{ dataForm.orderTotalAmount || 0 }}</span>
            <el-divider direction="vertical"></el-divider>
            <span>已对账金额：</span>
            <span>{{ dataForm.amountCompletePrice || 0 }}</span>
            <el-divider direction="vertical"></el-divider>
            <span>未对账金额：</span>
            <span>{{ dataForm.amountUnCompletePrice || 0 }}</span>
            <el-divider direction="vertical"></el-divider>
            <span>本次对账总金额：</span>
            <span>{{ dataForm.amountTotalPrice || 0 }}</span>
          </el-row>
        </template>
      </headerTitle>
      <!-- <recorpayTableList
        ref="recorpayListRef"
        :dataForm="dataForm"
        :recorpayList.sync="recorpayList"
        :dialogType="dialogType"
      ></recorpayTableList> -->
      <inventoryTable
        ref="inventoryTableref"
        :dataForm="dataForm"
        :datasource.sync="datasource"
        :dialogType="dialogType"
        @changeDiscountPrice="changeDiscountPrice"
      ></inventoryTable>
    </div>
    <div slot="footer" class="footer">
      <el-button
        v-if="dialogType !== 'view'"
        type="primary"
        @click="save"
        v-click-once
        >保存
      </el-button>
      <el-button
        v-if="dialogType !== 'view'"
        type="primary"
        @click="save('sub')"
        v-click-once
        >提交
      </el-button>
      <el-button @click="cancel">返回</el-button>
    </div>
    <process-submit-dialog
      :processSubmitDialogFlag.sync="processSubmitDialogFlag"
      v-if="processSubmitDialogFlag"
      ref="processSubmitDialogRef"
      @reload="reload"
    ></process-submit-dialog>
  </ele-modal>
</template>

<script>
  import InventoryTable from './inventoryTable.vue';
  import recorpayTableList from './recorpayTableList.vue';

  import saleForm from './saleForm.vue';
  import {
    getStatementRecordListAPI,
    infoAccountStatementAPI,
    saveAccountStatementAPI,
    createAccountStatementAPI,
    updateAccountStatementAPI,
    accountstatementInfoAPI,
    accountstatementUpdateAPI
  } from '@/api/saleManage/accountstatement';
  import processSubmitDialog from '@/BIZComponents/processSubmitDialog/processSubmitDialog.vue';

  export default {
    name: 'addAccountDialog',
    components: {
      processSubmitDialog,
      InventoryTable,
      saleForm,
      recorpayTableList
    },
    //客户管理数据
    props: {
      addAccountDialogFlag: {
        type: Boolean,
        default: false
      },
      contactData: {
        type: Object,
        default: () => {
          return {};
        }
      },
      saleOrderData: {
        type: Object,
        default: () => {
          return {};
        }
      }
    },
    data() {
      return {
        fullscreen: false,
        loading: false,
        saveLoading: false,
        datasource: [],
        recorpayList: [],
        dataForm: {
          sourceType: 1,
          dateType: 1,
          queryDimension: 1,
          dateValue: '',
          contactId: '',
          contactName: '',
          sourceName: '',
          sourceId: '',
          type: '',
          year: '',
          quarter: '',
          month: '',
          dateTimeRange: [],
          orderNo: '',
          orderId: '',
          id: '',
          startDate: '',
          endDate: '',
          repliedFiles: []
        },
        title: '',
        processSubmitDialogFlag: false,
        dialogType: '',
        businessId: ''
      };
    },
    computed: {},
    methods: {
      changeDiscountPrice(price, tableIndex) {
        console.log('price~~~', price, tableIndex)
        this.datasource[tableIndex].statementAmount = price;
        this.datasource[tableIndex].unStatementAmount = price;
        console.log('this.datasource', this.datasource)
        this.dataForm.amountTotalPrice = this.datasource.reduce((pre, cur) => pre + Math.round(+cur.statementAmount * 100), 0) / 100;
        this.dataForm.amountUnCompletePrice = this.datasource.reduce((pre, cur) => pre + Math.round(+cur.unStatementAmount * 100), 0) / 100;
      },
      open(dialogType, row, type = '') {
        this.dialogType = dialogType;
        this.title =
          dialogType == 'add'
            ? '新增'
            : dialogType == 'update'
            ? '修改'
            : '详情';
        this.dataForm.type = type;
        this.$nextTick(() => {
          if (this.contactData.id) {
            this.$refs.saleFormRef.getCusInfo(this.contactData);
          }
          if (this.saleOrderData.id) {
            this.$refs.saleFormRef.getOrderInfo(this.saleOrderData);
          }
        });
        if (this.dialogType !== 'add') {
          this.businessId = row.id;
          this.getInfo(row);
        }
      },
      //获取对账单详情
      async getInfo(row) {
        let data = await accountstatementInfoAPI(row.id);
        // this.recorpayList = data.recorpayList || [];
        // 解决小数精度丢失问题，使用分进行计算
        data.orderTotalAmount = data.orderList.reduce((pre, cur) => pre + Math.round(+cur.orderAmount * 100), 0) / 100;
        data.amountTotalPrice = data.orderList.reduce((pre, cur) => pre + Math.round(+cur.statementAmount * 100), 0) / 100;
        data.amountCompletePrice = data.orderList.reduce((pre, cur) => pre + Math.round(+cur.statementedAmount * 100), 0) / 100;
        data.amountUnCompletePrice = data.orderList.reduce((pre, cur) => pre + Math.round(+cur.unStatementAmount * 100), 0) / 100;
        data.orderList = data.orderList.map(item => {
            item.deliveryProducts = item.deliveryProducts.map(i => {
              return {
                ...i,
                taxRate: i.taxRate || 0,
                discountRatio: i.discountRatio || 100,
                singlePrice: i.singlePrice || 0,
              }
            })
            return item;
          })
        this.datasource = data.orderList || [];
        this.dataForm = data;
        switch (this.dataForm.dateType) {
          case 1:
            // this.dataForm.year = this.dataForm.dateValue;
            this.$set(this.dataForm, 'year', this.dataForm.dateValue);
            break;
          case 2:
            //2023年-四季度
            let data = this.dataForm.dateValue.split('年-');

            this.$set(this.dataForm, 'year', data[0]);
            this.$set(this.dataForm, 'quarter', data[1]);
            break;
          case 3:
            this.$set(this.dataForm, 'month', this.dataForm.dateValue);

            break;
          default:
            this.dataForm.dateValue = '';
            this.$set(this.dataForm, 'dateTimeRange', [
              this.dataForm.startDate,
              this.dataForm.endDate
            ]);
        }
        this.$forceUpdate();
      },
      //关闭弹窗
      cancel() {
        this.$emit('update:addAccountDialogFlag', false);
      },
      //查询获取订单数据
      async handleSearch(params) {
        console.log('this.$refs.inventoryTableRef~~~', this.$refs.inventoryTableref);
        let searchQuery = {
          endDate: params.endDate,
          sourceId: params.sourceId,
          sourceType: params.sourceType,
          startDate: params.startDate,
          queryDimension: params.queryDimension,
          type: 1
        };

        // const searchQuery = ["SALES20251225007","SALES20251225005","SALES20251225009"];
        this.loading = true;
        try {
          let data = await getStatementRecordListAPI(searchQuery);
          console.log(data, 'data');
          this.loading = false;
          data = data.map(item => {
            item.deliveryProducts = item.deliveryProducts.map(i => {
              return {
                ...i,
                taxRate: i.taxRate || 0,
                discountRatio: i.discountRatio || 100,
                singlePrice: i.singlePrice || 0,
              }
            })
            return item;
          })
          this.datasource = data || [];

          console.log(this.datasource, 'this.datasource~~~');
          // this.recorpayList = data.recorpayList || [];
          this.dataForm = {
            ...this.dataForm,
            // amountPayablePrice: data.amountPayablePrice,
            // amountReceivablePrice: data.amountReceivablePrice,
            // amountTotalPrice: data.amountTotalPrice,
            // amountPayablePass: data.amountPayablePass,
            // amountReceivablePass: data.amountReceivablePass
            orderTotalAmount: data.reduce((pre, cur) => pre + Math.round(+cur.orderAmount * 100), 0) / 100,
            amountTotalPrice: data.reduce((pre, cur) => pre + Math.round(+cur.statementAmount * 100), 0) / 100,
            amountCompletePrice: data.reduce((pre, cur) => pre + Math.round(+cur.statementedAmount * 100), 0) / 100,
            amountUnCompletePrice: data.reduce((pre, cur) => pre + Math.round(+cur.unStatementAmount * 100), 0) / 100
          };
          this.$forceUpdate();
        } catch (error) {
          this.loading = false;
        }
        // if (!this.datasource.length) this.$message.warning('暂无订单信息');
      },
      //保存
      async save(is) {
        if (!this.datasource.length)
          return this.$message.warning('暂无对账信息');
        
        try {
          // 校验 inventoryTableref 组件的表单
          await this.$refs.inventoryTableref.getValidForm();
          
          let api =
            this.dialogType == 'add'
              ? createAccountStatementAPI
              : accountstatementUpdateAPI;
          let params = {
            ...this.dataForm,
            orderList: this.datasource,
            // recorpayList: this.recorpayList
          };
          this.saveLoading = true;
          let data = await api(params);
          if (is == 'sub') {
            await this.submitApprove(data);
            return;
            // await submitAccountStatementApproveAPI({
            //   businessId: data,
            //   type: this.dataForm.type
            // });
          }
          this.$message.success('操作成功');
          this.reload();
          this.saveLoading = false;
        } catch (error) {
          console.error('保存失败:', error);
          // 错误提示已经在 getValidForm 方法中处理
          this.saveLoading = false;
        }
      },
      async submitApprove(res) {
        console.log(res, 'res~~~');
        console.log(this.businessId || res, 'this.businessId || res');
        const data = await accountstatementInfoAPI(this.businessId || res);
        console.log(data, 'data~~~');
        this.processSubmitDialogFlag = true;
        this.$nextTick(() => {
          const params = {
            businessId: data.id,
            businessKey: 'sales_account_statement_approve',
            formCreateUserId: data.createUserId,
            variables: {
              type: data.type,
              businessCode: data.statementNo,
              businessName: data.contactName,
              businessType: '对账单'
            }
            // callBackMethodType : '1',
            // callBackMethod : 'proTargetPlanApproveApiImpl.updatePlanApprovalStatus',
            // pcHandle : '/bpm/handleTask/components/project-manage/plan-manage/submit.vue',
            // pcView : '/bpm/handleTask/components/project-manage/plan-manage/detailDialog.vue',
            // miniHandle : '',
            // miniView : '',
          };
          this.$refs.processSubmitDialogRef.init(params);
        });
      },
      reload() {
        this.cancel();
        //刷新主页面
        this.$emit('done');
      }
    }
  };
</script>
<style scoped lang="scss">
  ::v-deep.el-divider {
    margin: 10px;
    font-weight: bold;
  }
</style>
