<template>
  <div>
    <el-tabs type="border-card">
      <el-tab-pane :label="item.key" v-for="(item, idx) in tableForm.detailList" :key="idx">
        <el-form :ref="'form' + idx" :model="tableForm">
          <ele-pro-table
            ref="table"
            :needPage="false"
            :columns="columns"
            :datasource="item.details"
            row-key="id"
            class="time-form"
          >
            <template v-slot:toolbar>
              <span>本次开票合计：{{ item.amountTotalPrice }}</span>
            </template>
            
            <template v-slot:invoiceAmount="scope">
            <el-form-item
              style="width: 100%;"
              :prop="'detailList.' + idx + '.details.' + scope.$index + '.invoiceAmount'"
              :rules="[
                {
                  required: true,
                  message: '请输入开票金额',
                  trigger: 'blur'
                },
                {
                  validator: (rule, value, callback) => {
                    if (value === undefined || value === null || value === '') {
                      callback('请输入开票金额');
                    } else if (parseFloat(value) < 0 || parseFloat(value) > item.amountTotalPrice) {
                      callback('开票金额不能小于0且小于等于本次开票合计');  
                    } else {
                      callback();
                    }
                  },
                  trigger: 'blur'
                }
              ]"
            > 
              <span v-if="dialogType === 'view'">{{ scope.row.invoiceAmount }}</span>
              <el-input v-else v-model="scope.row.invoiceAmount" type="number" @input="(val) => invoiceAmountChange(val, scope.row, idx, scope.$index)"></el-input>
            </el-form-item>
          </template>

          <template v-slot:taxRate="scope">
            <el-form-item
              style="width: 100%;"
              :prop="'detailList.' + idx + '.details.' + scope.$index + '.taxRate'"
              :rules="[
                {
                  required: true,
                  message: '请输入税率',
                  trigger: 'blur'
                },
                {
                  validator: (rule, value, callback) => {
                    if (value === undefined || value === null || value === '') {
                      callback('请输入税率');
                    } else if (parseFloat(value) < 0) {
                      callback('税率不能小于0');
                    } else {
                      callback();
                    }
                  },
                  trigger: 'blur'
                }
              ]"
            > 
              <span v-if="dialogType === 'view'">{{ scope.row.taxRate }}</span>
              <el-input v-else v-model="scope.row.taxRate" type="number" @input="getNotaxSinglePrice(scope.row, idx, scope.$index)" style="width: 80%;"></el-input>%
            </el-form-item>
          </template>

          </ele-pro-table>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    
  </div>
</template>
<script>
  export default {
    name: 'tableInfo',
    components: {},
    props: {
      form: {
        type: Object,
        default: () => {
          return {
            productMap: [],
            receiptPayments: []
          };
        }
      },
      dialogType: {
        type: String,
        default: ''
      },
      isOtherSourceFlag: {
        type: Boolean,
        default: false
      },
      contactData: {
        type: Object,
        default: () => {
          return {};
        }
      },
      invoiceAmount: {
        type: Number,
        default: 0
      }
    },
    data() {
      return {
        columns: [
          {
            width: 45,
            type: 'index',
            columnKey: 'index',
            align: 'center',
            fixed: 'left'
          },

          {
            width: 100,
            prop: 'typeName',
            label: '类型',
            slot: 'typeName',
            align: 'center'
          },
          // {
          //   minWidth: 100,
          //   prop: 'sourceCode',
          //   label: '类型编码',
          //   slot: 'sourceCode',
          //   align: 'center'
          // },
          // {
          //   width: 100,
          //   prop: 'productCategoryName',
          //   label: '分类',
          //   slot: 'productCategoryName',
          //   align: "center"
          // },
          // {
          //   width: 100,
          //   prop: 'productCode',
          //   label: '编码',
          //   slot: 'productCode',
          //   align: "center"
          // },
          {
            minWidth: 100,
            prop: 'productName',
            label: '产品名称',
            slot: 'productName',
            align: 'center'
          },
          {
            minWidth: 100,
            prop: 'modelType',
            label: '型号',
            slot: 'modelType',
            align: 'center'
          },

          {
            minWidth: 100,
            prop: 'specification',
            label: '规格',
            slot: 'specification',
            align: 'center'
          },
          // {
          //   width: 100,
          //   prop: 'unInvoiceAmount',
          //   label: '未开票金额',
          //   slot: 'unInvoiceAmount',
          //   align: "center"
          // },
          
          // {
          //   width: 80,
          //   prop: 'singleWeight',
          //   label: '单量',
          //   align: 'center'
          // },

          {
            minWidth: 150,
            prop: 'invoiceAmount',
            label: '开票金额',
            slot: 'invoiceAmount',
            align: 'center'
          },
          {
            minWidth: 150,
            prop: 'taxRate',
            label: '税率',
            align: 'center',
            slot: 'taxRate',
            // formatter: (_row, _column, cellValue) => {
            //   return _row.taxRate
            //     ? _row.taxRate+'%'
            //     : '';
            // },
          },
          {
            minWidth: 100,
            prop: 'noTaxSinglePrice',
            label: '不含税单价',
            slot: 'noTaxSinglePrice',
            align: 'center'
          },
          {
            width: 100,
            prop: 'totalCount',
            label: '订单数量',
            // slot: 'totalCount',
            align: 'center',
          },
          {
            width: 150,
            prop: 'quoteWay',
            label: '报价方式',
            formatter: (row, column) => {
              return row.quoteWay == 1
                ? '常规价'
                : row.quoteWay == 2
                ? '内部价'
                : row.quoteWay == 3 ? '议价' : '';
            },
            align: 'center'

          },
          {
            minWidth: 80,
            prop: 'singlePrice',
            label: '单价',
            slot: 'singlePrice',
            align: 'center'
          },
          {
            width: 100,
            prop: 'totalPrice',
            label: '合计',
            align: 'center'
          },
          {
            width: 100,
            prop: 'discountRatio',
            label: '折让比例',
            align: 'center'
          },
          {
            width: 100,
            prop: 'discountSinglePrice',
            label: '折让单价',
            align: 'center'
          },
          {
            width: 100,
            prop: 'discountAmount',
            label: '折让合计',
            align: 'center'
          },
          // {
          //   width: 100,
          //   prop: 'sourceType',
          //   label: '来源类型',
          //   slot: 'sourceType',
          //   align: "center",
          //   formatter: (row, column) => {
          //     return row.sourceType == 2 ? '对账销售订单' : '对账采购订单';
          //   }
          // },
        ],
        tableForm: {
          detailList: [
            {
              key: '',
              amountTotalPrice: 0,
              details: [{
                invoiceAmount: 0,
                taxRate: 0,
                noTaxSinglePrice: 0,
                totalCount: 0,
                quoteWay: '',
                singlePrice: 0,
                totalPrice: 0,
                discountRatio: 0,
                discountSinglePrice: 0,
                discountAmount: 0,
              }]
            }
          ],
          productMap: [],
          link: []
        },
        typeList: [
          {
            label: '销售发货',
            value: '10'
          },
          {
            label: '销售退货',
            value: '11'
          },
          {
            label: '采购收货',
            value: '20'
          },
          {
            label: '采购退货',
            value: '21'
          }
        ],
      };
    },
    mounted() {
      // this.tableForm = this.form;
    },
    watch: {
    form: {
      handler(val) {
        console.log('tableInfoNew form', val);
        const data = JSON.parse(JSON.stringify(val));
        data.detailList = data.productMap ? this.convertToArrayFormat(data) : [
          {
            key: '',
            amountTotalPrice: 0,
            details: []
          }
        ];
        console.log('tableInfoNew detailList', data.detailList);
        this.tableForm = data;
      },
      deep: true
    }
  },
    methods: {
      convertToArrayFormat(data) {
          return Object.keys(data.productMap).map(key => {
            console.log('key', key);
              const paymentItem = data.receiptPayments?.filter(item => item?.relatedOrderNo == key)|| [];
              return {
                  key: key,
                  amountTotalPrice: paymentItem.length ? paymentItem.reduce((acc, cur) => acc + cur.invoiceAmount, 0) : 0,
                  defaultAmountTotalPrice: paymentItem.length ? paymentItem.reduce((acc, cur) => acc + cur.invoiceAmount, 0) : 0,
                  details: data.productMap[key] || []
              };
          });
      },
      // 校验发票金额
      invoiceAmountChange(val, item, idx, index) {
        console.log('invoiceAmountChange', val, item, idx, index);
        console.log('this.tableForm.detailList', this.tableForm.detailList)
        if(index !=null) {
          let newData = this.tableForm.detailList[idx].details;
          console.log('newData', newData);
          let sum =0;
          newData.forEach((r) => {
            if (r.invoiceAmount) {
              sum += Number(r.invoiceAmount);
            }
          });
          if(val && +val > +this.tableForm.detailList[idx].details[index].discountAmount) {
            this.$message.error('物品开票金额不能大于折让合计');
            this.$set(this.tableForm.detailList[idx].details[index], 'invoiceAmount', '');
            return;
          }
          if(sum > this.tableForm.detailList[idx].defaultAmountTotalPrice) {
            this.$message.error('物品开票金额不能大于本次开票合计');
            this.$set(this.tableForm.detailList[idx].details[index], 'invoiceAmount', '');
            return;
          }
          this.$set(this.tableForm.detailList[idx].details[index], 'invoiceAmount', val);
          this.$set(this.tableForm.detailList[idx], 'amountTotalPrice', sum);
          console.log('sum', sum, this.tableForm.detailList[idx].details[index].invoiceAmount);
        }
      },
      //计算不含税单价
      getNotaxSinglePrice(item, idx, index) {
        if (item.singlePrice && item.taxRate) {
          this.$set(
            this.tableForm.detailList[idx].details[index],
            'noTaxSinglePrice',
            parseFloat(
              (item.singlePrice / (1 + item.taxRate / 100)).toFixed(2)
            )
          );
        } else {
          this.$set(this.tableForm.detailList[idx].details[index], 'noTaxSinglePrice', '');
        }
      },
      //获取选择的对账单数据
      async getAccountData(params) {
        if (params.children.orderType == 6) {
          this.tableForm.productMap = params.children.productMap;
          this.tableForm.productMap.forEach((item, index) => {
            item.sourceCode = params.children.orderNo;
            item.sourceId = params.children.id;
            item.sourceType = params.type == 1 ? 2 : 3;
            item.type = 12;
            item.singlePrice = item.discountSinglePrice;
            item.totalPrice = item.discountTotalPrice;
            item.typeName = '销售赔付';
          });
        } else {
          this.tableForm.productMap = [];
          params.children.subList.forEach((item, index) => {
            item.productMap.forEach((i, n) => {
              i.sourceCode = item.statementSubOrderCode;
              i.sourceId = params.children.id;
              i.sourceType = params.type == 1 ? 2 : 3;
              i.type = item.subType;
              console.log(item.subType);
              i.typeName = this.typeList.find(
                (i) => i.value == item.subType
              ).label;
              // i.singlePrice = item.discountSinglePrice
              i.totalPrice = i.discountTotalPrice;
            });
            this.tableForm.productMap.push(...item.productMap);
          });
          this.$refs.table.reload();
        }
        this.$emit(
          'setPrice',
          params.children.amountTotalPrice - this.invoiceAmount
        );
        let row = {
          id: params.id,
          name: params.statementNo,
          code: params.statementNo,
          linkType: params.type == 1 ? 190 : 290,
          linkTypeName: params.type == 1 ? '销售对账单' : '采购对账单'
        };
        this.setSelectData(row);
      },
      putValue(data) {
        console.log('tableInfoNew putValue', data);
        data.detailList = this.convertToArrayFormat(data);
        this.tableForm = data;
      },
      setValue(data) {
        let tempData = JSON.parse(JSON.stringify(data));
        tempData.detailList = this.convertToArrayFormat(tempData);
        // data.detailList = this.allocateInvoiceAmount(data.detailList);
        for(let item of tempData.detailList) {
          const total = item.amountTotalPrice;
          const details = item.details;
          const count = details.length;
          
          if (count === 0) continue;
          
          // 计算基础金额（向下取整）
          const baseAmount = Math.floor(total / count);
          // 计算余数
          const remainder = total - (baseAmount * count);
          
          // 为所有项设置基础金额
          details.forEach((detail) => {
            detail.invoiceAmount = baseAmount;
          });
          
          // 将余数加到最后一项
          if (remainder > 0 && details.length > 0) {
            details[details.length - 1].invoiceAmount += remainder;
          }
        }
        // this.$set(this, 'tableForm', data);
        this.tableForm = tempData;
        // console.log('tableInfoNew detailList~~~', tempData.detailList);
        // this.$refs.table.reload();
      },
      /**
       * 分配开票金额到明细项
       * @param {Array|Object} data - 明细列表或单个明细对象
       * @returns {Array|Object} 处理后的数据
       */
      allocateInvoiceAmount(data) {
        if (Array.isArray(data)) {
          // 处理数组
          data.forEach(item => {
            if (item && typeof item === 'object') {
              const total = Number(item.amountTotalPrice) || 0;
              const details = item.details || [];
              const count = details.length;
              
              if (count > 0) {
                const baseAmount = Math.floor(total / count);
                const remainder = total - (baseAmount * count);
                
                details.forEach((detail) => {
                  detail.invoiceAmount = baseAmount;
                });
                
                if (remainder > 0) {
                  details[count - 1].invoiceAmount += remainder;
                }
              }
            }
          });
          return data;
        } else if (data && typeof data === 'object') {
          // 处理单个对象
          const total = Number(data.amountTotalPrice) || 0;
          const details = data.details || [];
          const count = details.length;
          
          if (count > 0) {
            const baseAmount = Math.floor(total / count);
            const remainder = total - (baseAmount * count);
            
            details.forEach((detail) => {
              detail.invoiceAmount = baseAmount;
            });
            
            if (remainder > 0) {
              details[count - 1].invoiceAmount += remainder;
            }
          }
          
          return data;
        }
        return data;
      },
      getSingleInvoiceAmount(detailList) {
        for(let item of detailList) {
          const total = item.amountTotalPrice;
          const details = item.details;
          const count = details.length;
          
          if (count === 0) continue;
          
          // 计算基础金额（向下取整）
          const baseAmount = Math.floor(total / count);
          // 计算余数
          const remainder = total - (baseAmount * count);
          
          // 为所有项设置基础金额
          details.forEach((detail) => {
            detail.invoiceAmount = baseAmount;
          });
          
          // 将余数加到最后一项
          if (remainder > 0 && details.length > 0) {
            details[details.length - 1].invoiceAmount += remainder;
          }
        }
        return detailList;
      },
      setSinglePrice(row, data) {
        let index = this.tableForm.detailList.findIndex(item => item.key == row.relatedOrderNo);
        // let detail = this.tableForm.detailList[index];
        // console.log('tableInfoNew setPrice', row, data, index);
        const paymentItem = data.filter(item => item?.relatedOrderNo == row.relatedOrderNo);
        // console.log('tableInfoNew paymentItem', paymentItem);
        this.tableForm.detailList[index].amountTotalPrice = paymentItem.length ? paymentItem.reduce((acc, cur) => acc + +cur.invoiceAmount, 0) : 0;
        this.tableForm.detailList[index].defaultAmountTotalPrice = paymentItem.length ? paymentItem.reduce((acc, cur) => acc + +cur.invoiceAmount, 0) : 0;
        // console.log('tableInfoNew tableForm', this.tableForm.detailList);
        // detail =this.allocateInvoiceAmount(detail);
        this.tableForm.detailList[index] = this.allocateInvoiceAmount(this.tableForm.detailList[index]);
        // this.tableForm.detailList[index] = detail;

        this.tableForm = {...this.tableForm};
        this.$forceUpdate();
      },
      clearTable() {
        this.tableForm = {
          detailList: [],
          productMap: [],
          receiptPayments: [],
          link: []
        };
      },
      // 当数量变化时更新金额
      updateTotalPrice(row) {
        if (row.totalCount && row.singlePrice) {
          row.totalPrice = (parseFloat(row.totalCount) * parseFloat(row.singlePrice)).toFixed(2);
        }
      },
      getTableValidate() {
        return new Promise(async (resolve, reject) => {
          // 2. 验证每个表格表单
          const validationPromises = [];
          this.tableForm.detailList.forEach((item, index) => {
            validationPromises.push(
              new Promise((formResolve, formReject) => {
                // 正确获取表单实例
                const formInstance = this.$refs['form' + index];
                
                if (formInstance) {
                  // 确保formInstance有validate方法
                  if (typeof formInstance.validate === 'function') {
                    formInstance.validate((valid, errors) => {
                      if (!valid && errors) {
                        // 显示第一个错误信息
                        const firstError = Object.values(errors)[0][0];
                        if (firstError) {
                          this.$message.warning(firstError.message);
                        }
                        formReject(false);
                      } else {
                        formResolve(true);
                      }
                    });
                  } else {
                    // 如果没有validate方法，检查是否是数组（多个表单实例）
                    if (Array.isArray(formInstance) && formInstance.length > 0) {
                      const firstForm = formInstance[0];
                      if (typeof firstForm.validate === 'function') {
                        firstForm.validate((valid, errors) => {
                          if (!valid && errors) {
                            const firstError = Object.values(errors)[0][0];
                            if (firstError) {
                              this.$message.warning(firstError.message);
                            }
                            formReject(false);
                          } else {
                            formResolve(true);
                          }
                        });
                      } else {
                        formResolve(true); // 没有validate方法时默认通过
                      }
                    } else {
                      formResolve(true); // 不是预期的表单实例时默认通过
                    }
                  }
                } else {
                  formResolve(true); // 表单不存在时默认通过
                }
              })
            );
          });

          console.log('validationPromises~~~',validationPromises);
          
          // 3. 处理验证结果
          try {
            await Promise.all(validationPromises);
            resolve(this.tableForm);
            console.log('this.tableForm~~~',this.tableForm);
          } catch (error) {
            reject(false);
          }
        });
      },
      validateForm(callback) {
        //开始表单校验
        this.$refs.form.validate((valid, obj) => {
          if (obj) {
            let messages = Object.keys(obj).map((key) => obj[key][0]);
            if (messages.length > 0) {
              this.$message.warning(messages[0].message);
            }
          }
          callback(valid);
        });
      },
      setSelectData(val) {
        this.tableForm.link = [{}];
        this.$set(this.tableForm.link[0], 'linkId', val.id);
        this.$set(this.tableForm.link[0], 'linkName', val.name);
        this.$set(this.tableForm.link[0], 'linkCode', val.code);
        this.$set(this.tableForm.link[0], 'linkType', val.linkType);
        this.$set(this.tableForm.link[0], 'linkTypeName', val.linkTypeName);
      },
      getTableData() {
        const  data = JSON.parse(JSON.stringify(this.tableForm.detailList));
        const transformedData = data.reduce((result, item) => {
          result[item.key] = item.details;
          return result;
        }, {});
        return transformedData;
      }
    }
  };
</script>

<style scoped lang="scss">
.time-form .el-form-item {
  margin-bottom: 0 !important;
}
</style>
