<template>
  <ele-modal
    custom-class="ele-dialog-form long-dialog-form"
    :centered="true"
    :visible="addAdjustDialogFlag"
    :title="title"
    :append-to-body="true"
    :close-on-click-modal="false"
    width="70%"
    :maxable="true"
    :resizable="true"
    @close="handleClose"
  >
    <div style="margin-bottom: 20px;">
      <!-- <el-alert
        title="目前冲差功能仅适用于销售订单已审核，未执行发货的情况"
        type="warning"
        center
        show-icon>
      </el-alert> -->
    </div>
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      class="el-form-box"
      label-width="160px"
    >
      <headerTitle title="基本信息"></headerTitle>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item labelWidth="100px" label="冲差单编码" prop="orderNo">
            <el-input
              clearable
              v-model="form.orderNo"
              disabled
              placeholder="自动生成"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
             labelWidth="100px"
            label="冲差类型"
            prop="type"
          >
            <DictSelection
              dictName="冲差类型"
              disabled
              clearable
              v-model="form.type"
            >
            </DictSelection>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item
            labelWidth="100px"
            label="冲差原因"
            prop="reason"
          >
            <DictSelection
              dictName="冲差原因"
              clearable
              v-model="form.reason"
            >
            </DictSelection>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item labelWidth="100px" label="冲差方式" prop="method">
            <DictSelection
              dictName="冲差方式"
              disabled
              clearable
              v-model="form.method"
            >
            </DictSelection>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item
            labelWidth="100px"
            label="调整类型"
            prop="adjustType"
          >
            <DictSelection
              dictName="调整类型"
              clearable
              v-model="form.adjustType"
            >
            </DictSelection>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item labelWidth="100px" label="冲差范围" prop="rangeType">
            <DictSelection
              dictName="冲差范围"
              clearable
              v-model="form.rangeType"
            >
            </DictSelection>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item labelWidth="100px" label="调整说明" prop="remark">
            <el-input
              clearable
              v-model="form.remark"
              type="textarea"
              rows="1"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item labelWidth="100px" prop="files" label="附件">
            <fileMain v-model="form.files"></fileMain>
          </el-form-item>
        </el-col>
      </el-row>
      <headerTitle title="物品清单" style="margin-top: 30px"></headerTitle>
      <inventoryTableDetails
        ref="inventoryTableDetailsRef"
        :isDiscountTotalPrice="true"
        :isSelected="true"
        :selectedIds="selectIds"
        @selection-change="handleSelectionChange"
      ></inventoryTableDetails>
      <headerTitle
        title="冲差信息"
        style="margin-top: 30px"
      ></headerTitle>
      <inventoryTable
        ref="inventoryTableRef"
        @changePrice="handleChangePrice"
        @setCountAmount="setCountAmount"
      ></inventoryTable>
      <div style="margin-top: 20px;">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label-width="100px" label="总差异金额:" prop="differenceAmount">
              <el-input
                clearable
                v-model="form.differenceAmount"
                disabled
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label-width="100px" label="总金额:" prop="adjustAmount">
              <el-input
                clearable
                disabled
                v-model="form.adjustAmount"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label-width="115px" label="优惠后总金额:" prop="adjustDiscountAmount">
              <el-input
                clearable
                type="number"
                v-model="form.adjustDiscountAmount"
                placeholder="请输入"
                @input="discountInput"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>

    <div slot="footer" class="footer">
      <el-button type="primary" @click="save" v-click-once>保存</el-button>
      <el-button
        type="primary"
        v-if="isNeed_process_is_close"
        @click="save('sub')"
        v-click-once
        >提交</el-button
      >
      <el-button @click="cancel">返回</el-button>
    </div>
    <process-submit-dialog
      :isNotNeedProcess="false"
      :processSubmitDialogFlag.sync="processSubmitDialogFlag"
      v-if="processSubmitDialogFlag"
      ref="processSubmitDialogRef"
      @reload="reload"
    ></process-submit-dialog>
 
  </ele-modal>
</template>

<script>
  import { acceptUnpackoptions } from '@/enum/dict';
  import fileUpload from '@/components/upload/fileUpload';
  import dictMixins from '@/mixins/dictMixins';
  import deptSelect from '@/components/CommomSelect/dept-select.vue';
  import personSelect from '@/components/CommomSelect/person-select.vue';
  import parentList from '@/views/saleManage/contact/components/parentList.vue';
  import inventoryTable from './inventoryTable.vue';
  import { copyObj } from '@/utils/util';
  import { getWarehouseListByIds } from '@/api/purchasingManage/returnGoods';
  import fileMain from '@/components/addDoc/index.vue';
  import processSubmitDialog from '@/BIZComponents/processSubmitDialog/processSubmitDialog.vue';
  import orderListDialog from '@/views/saleManage/saleOrder/invoice/components/orderListDialog.vue';
  import inventoryTable1 from '@/BIZComponents/inventoryTable.vue';
  import inventoryTableDetails from '@/BIZComponents/inventoryTableDetails.vue';
  import {
    getSaleOrderDetail,
  } from '@/api/saleManage/saleorder';
  import { addCreate, getInfo, updateInfo } from '@/api/saleManage/adjustmentNote‌';

  export default {
    mixins: [dictMixins],
    components: {
      orderListDialog,
      processSubmitDialog,
      fileMain,
      fileUpload,
      deptSelect,
      inventoryTable,
      inventoryTable1,
      parentList,
      personSelect,
      inventoryTableDetails
    },
    //客户管理数据
    props: {
      addAdjustDialogFlag: {
        type: Boolean,
        default: false
      },
      saleOrderData: {
        type: Object,
        default: () => {
          return {};
        }
      }
    },
    data() {
      let formDef = {
        orderNo: '',
        type: '1',
        method: '1',
        reason: '1',
        rangeType: '',
        adjustType: '1',
        sourceType: '1',
        sourceNo: '',
        sourceId: '',
        files: [],
        differenceAmount: '',
        amount: '',
        discountAmount: '',
        sourceNo: '',
        sourceId: '',
        adjustAmount: '',
        adjustDiscountAmount: '',
        detailList: [],
        originalList: [],
      };

      return {
        visible: false,
        processSubmitDialogFlag: false,
        title: '',
        row: {},
        activeName: 'base',
        formDef,
        form: copyObj(formDef),
        orderForm: {},
        rules: {
          type: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          method: [{ required: true, message: '请选择', trigger: 'change' }],
          reason: [{ required: true, message: '请选择', trigger: 'change' }],
          rangeType: [{ required: true, message: '请选择', trigger: 'change' }],
          adjustType: [{ required: true, message: '请选择', trigger: 'change' }],
          // files: [{ required: true, message: '请上传附件', trigger: 'change' }],
          adjustDiscountAmount: [{ required: true, message: '请输入', trigger: 'change' }],
        },
        // 提交状态
        loading: false,
        // 是否是修改
        isUpdate: false,
        businessId: '',
        orderId: '',
        productList: [],
        adjustData: [],
        selectIds: [],
      };
    },
    async created() {
    
    },
    computed: {
      totalAmount() {
        let allcountAmount = 0;
        let totalAmount =
          (this.$refs.inventoryTableRef &&
            this.$refs.inventoryTableRef.totalAmount) ||
          0;
        if (this.form.returnSourceType == 1) {
          if (this.form.type === '10') {
            allcountAmount = Number(totalAmount);
          }
          if (this.form.type === '20') {
            allcountAmount =
              Number(totalAmount) +
              Number(
                this.$refs.inventoryTableref1 &&
                  this.$refs.inventoryTableref1.getPrice()[0]
              );
          }
          if (this.form.type === '30') {
            allcountAmount =
              Number(totalAmount) + Number(this.form.redressAmount || 0);
          }
          if (this.form.type === '40') {
            allcountAmount =
              this.$refs.inventoryTableref1 &&
              this.$refs.inventoryTableref1.getPrice()[0];
          }
          if (this.form.type === '50') {
            allcountAmount = Number(this.form.redressAmount || 0);
          }
        } else {
          allcountAmount = Number(totalAmount);
        }

        return parseFloat(allcountAmount).toFixed(2);
      }
    },

    methods: {
      // 选择需要冲差的产品
      handleSelectionChange(list) {
        // this.form.productList = val;
        console.log('select------list', list);
        // 创建深拷贝避免引用关系
        this.adjustData = JSON.parse(JSON.stringify(list))?.map(item => ({
          ...item,
          price: item.singlePrice,
          adjustPrice: item.singlePrice,
          quantity: item.saleCount,
          adjustDiscountPrice: item.discountSinglePrice,
          adjustDiscountAmount: item.discountTotalPrice,
          adjustAmount: item.totalPrice,
          sourceDetailId: item.id,
          discountPrice: item.discountSinglePrice,
          unTaxPrice: item.notaxSinglePrice,
        }));
        
        if (this.$refs.inventoryTableRef) {
          // 获取当前inventoryTable中已有的数据
          const currentData = this.$refs.inventoryTableRef.form.datasource || [];
          
          // 创建一个映射，记录已存在的数据
          const existingItemsMap = {};
          currentData.forEach(item => {
            if (item.productCode) {
              existingItemsMap[item.productCode] = item;
            }
          });
          
          // 合并数据，保留已编辑的单价等信息
          this.adjustData.forEach(item => {
            if (existingItemsMap[item.productCode]) {
              // 保留已编辑的字段
              const existingItem = existingItemsMap[item.productCode];
              item.priceDifference = existingItem.priceDifference !== undefined ? existingItem.priceDifference : item.priceDifference;
              item.adjustPrice = existingItem.adjustPrice !== undefined ? existingItem.adjustPrice : item.adjustPrice;
              item.quantity = existingItem.quantity !== undefined ? existingItem.quantity : item.quantity;
              item.adjustDiscountPrice = existingItem.adjustDiscountPrice !== undefined ? existingItem.adjustDiscountPrice : item.adjustDiscountPrice;
              item.adjustDiscountAmount = existingItem.adjustDiscountAmount !== undefined ? existingItem.adjustDiscountAmount : item.adjustDiscountAmount;
              item.adjustAmount = existingItem.adjustAmount !== undefined ? existingItem.adjustAmount : item.adjustAmount;
              item.unTaxPrice = existingItem.unTaxPrice !== undefined ? existingItem.unTaxPrice : item.unTaxPrice;
              
              // 移除已处理的项
              delete existingItemsMap[item.productCode];
            }
          });
          this.form.detailList = this.adjustData;
          // 调用putTableValue方法更新表格数据
          this.$refs.inventoryTableRef.putTableValue(this.form);
        }
      },
      // 计算总金额和优惠总金额
      setCountAmount(allPrice, diffPriceTotal) {
        console.log('allPrice~~~', allPrice, diffPriceTotal);
        this.form.adjustAmount = allPrice;
        this.form.adjustDiscountAmount = allPrice;
        this.form.differenceAmount = diffPriceTotal;
      },
      // 优惠后总金额修改产品折让单价
      discountInput() {
        console.log('this.form.adjustDiscountAmount~~~', this.form.adjustDiscountAmount, this.form.adjustAmount);
        this.$refs.inventoryTableRef.discountInputByOrder(this.form.adjustDiscountAmount, this.form.adjustAmount);
      },
      //删除产品
      remove(row) {
        if (this.form.productList.length === 1)
          return this.$message.error('必须要留一个产品');
        let index = this.form.productList.findIndex((n) => n.key == row.key);
        if (index !== -1) {
          this.form.productList.splice(index, 1);
        }
      },
    
      // 处理单价差异变化，更新单价
      handleChangePrice(obj) {
        this.form.differenceAmount = obj.total;
      },
 

      //打开新增编辑弹框
      async open(type, row) {
        console.log(type)
        this.title = type === 'add' ? '新增' : '修改';
        this.isUpdate = type != 'add';
        this.row = row;
        this.visible = true;
        console.log('row~~~~~~~~~~333', row);
        if (row && row?.id && !this.isUpdate) {
          console.log('add!!!')
          await this.getSaleOrderDetail(row?.id);
        } else {
          console.log('update!!!')
          const data = await getInfo(row?.id);
          if (data) {
            // this.$nextTick(() => {
              const tempdata = {
                // ...data,
                totalPrice: row.amount,
                discountTotalPrice: row.discountAmount,
                productList: data.originalList
              }
              this.businessId = data.id;
              this.adjustData = data.detailList;
              this.selectIds = this.adjustData.map(item => item.sourceDetailId);
              this.form = data;
              console.log('tempdata~~~', this.form, data);
              this.$refs.inventoryTableRef && this.$refs.inventoryTableRef.putTableValue(data);
              this.$refs.inventoryTableDetailsRef &&
                this.$refs.inventoryTableDetailsRef.putTableValue(tempdata);
              
            // });
            
          }
        }
        
      },

      //获取销售订单详情
      async getSaleOrderDetail(id) {
        // this.businessId = id;
        this.loading = true;
        const data = await getSaleOrderDetail(id);
        this.loading = false;
        this.orderForm = data;
        
        console.log('data~~~订单详情', data);
        if (data) {
          this.form.sourceNo = data.orderNo;
          this.form.sourceId = data.id;
          // this.form.amount = data.totalAmount;
          // this.form.discountAmount = data.payAmount;
          this.$nextTick(() => {
            this.$refs.inventoryTableDetailsRef &&
              this.$refs.inventoryTableDetailsRef.putTableValue(data);
          });
        }
      },
      getValidate() { 
        let proAll = [
          new Promise((resolve, reject) => {
            this.$refs.form.validate((valid) => {
              if (!valid) {
                reject(false);
              } else {
                resolve(true);
              }
            });
          })
        ];
 
        proAll.push(
          new Promise((resolve, reject) => {
            this.$refs.inventoryTableRef.validateForm((valid) => {
              if (!valid) {
                reject(false);
              } else {
                resolve(true);
              }
            });
          })
        );
        
        return Promise.all(proAll);
      },
      async save(type) {
        try {
          await this.getValidate();
          // 表单验证通过，执行保存操作
          this.loading = true;

          if (!this.isUpdate) {
            delete this.form.id;
          }
          let data = this.$refs.inventoryTableRef.getTableValue();
          // let redressProductList =
          //   (this.$refs.inventoryTableref1 &&
          //     this.$refs.inventoryTableref1.getTableValue()) ||
          //   [];
          console.log('data!!!!!!', data);
          if (
            data.productList.length === 0
          ) {
            return this.$message.error('至少选择一个冲差产品');
          }
          // let orderIds = [...data.productList, ...redressProductList].map(
          //   (item) => item.orderId
          // );
          // let orderNos = [...data.productList, ...redressProductList].map(
          //   (item) => item.orderNo
          // );

          // this.form.repliedFiles = this.form.repliedFiles || [];
          // this.form.replied = this.form.repliedFiles.length > 0 ? 1 : 0;
          // this.form.typeName = this.getDictValue('退货类型', this.form.type);
          let commitData = Object.assign({}, this.form, {
       
            detailList: data.productList,
            originalList: this.orderForm.productList,
          
          });
          // let productListData = [];
          // data.productList.forEach((item) => {
          //   if (!item.totalCount) {
          //     productListData.push(item.productName);
          //   }
          // });
          // console.log(productListData);
          // if (productListData.length) {
          //   return this.$message.error(
          //     productListData.toString() + ' 退货数量不能为空！'
          //   );
          // }
   
          if (this.isUpdate) {
            updateInfo(commitData)
              .then(async (res) => {
                this.loading = false;

                this.$message.success('修改成功');
                if (type === 'sub') {
                  let storemanIds = '';
                  let ids = commitData.detailList.map(
                    (item) => item.warehouseId
                  );
                  let warehouseList = await getWarehouseListByIds(ids || []);
                  storemanIds = warehouseList.map((item) => item.ownerId);
                  await this.adjustSubmit(res, storemanIds.toString());
                  return;
                }
                this.cancel();
                this.$emit('done');
              })
              .catch((e) => {
                //this.loading = false;
              });
          } else {
            addCreate(commitData)
              .then(async (res) => {
                this.loading = false;
                this.$message.success('新增成功');
                if (type === 'sub') {
                  // let storemanIds = '';
                  // let ids = commitData.detailList.map(
                  //   (item) => item.warehouseId
                  // );
                  // let warehouseList = await getWarehouseListByIds(ids || []);
                  // storemanIds = warehouseList.map((item) => item.ownerId);
                  this.adjustSubmit(res);
                  this.$emit('done');
                  return;
                }
                this.cancel();
                this.$emit('done');
              })
              .catch((e) => {
                //this.loading = false;
              });
          }
        } catch (error) {
          console.log(error);
          // 表单验证未通过，不执行保存操作
        }
      },
      async adjustSubmit(res) {
        const data = await getInfo(
          this.businessId || res
        );
        this.processSubmitDialogFlag = true;

        this.$nextTick(() => {
          let params = {
            businessId: this.businessId || res,
            businessKey: 'punch_slip_order_approve',
            formCreateUserId: data.createUserId,
            variables: {
              // returnSourceType: data.returnSourceType,
              // storemanIds: storemanIds.toString(),
              businessCode: data.orderNo,
              businessName: '销售订单冲差',
              businessType: '冲差单'
            }
          };

          this.$refs.processSubmitDialogRef.init(params);
        });
      },
      reload() {
        this.cancel();
        this.$emit('done');
      },
      // 处理对话框关闭事件
      handleClose() {
        this.cancel();
      },
      cancel() {
        this.$nextTick(() => {
          // 关闭后，销毁所有的表单数据
          // this.$refs['otherForm'] && this.$refs['otherForm'].resetFields();
          this.$refs['form'] && this.$refs['form'].resetFields();
          // this.$store.commit('order/clearUserData');
          this.form = copyObj(this.formDef);
          // 通过$emit更新父组件中的addAdjustDialogFlag值，避免直接修改prop
          this.$emit('update:addAdjustDialogFlag', false);
        });
      }
    }
  };
</script>
<style scoped lang="scss">
  .TotalAmount {
    font-size: 16px;
    padding-right: 30px;
  }

  .headbox {
    display: flex;
    justify-content: flex-start;
    align-items: center;

    .amount {
      font-size: 14px;
      font-weight: bold;
      margin-right: 20px;
    }
  }
</style>
