<template>
  <div class="container">
    <!-- 面包屑导航 -->
    <basic-crumb></basic-crumb>

    <!-- 页面标题 -->
    <div class="page-title">审批详情</div>

    <!-- 加载中 -->
    <!-- <el-loading v-if="loading" fullscreen text="加载中..."></el-loading> -->
    <!-- 订单信息卡片 -->
    <div class="boxcard" v-if="!loading && orderData">
      <div class="card-header">订单信息</div>
        <el-row :gutter="40" class="order-info-container">
    <!-- 左侧订单信息：el-col  -->
    <div style="padding:20px;width:100%">
         <el-col :span="12">
      <div class="info-item">
        <span class="label">订单编号:</span>
        <span class="value">{{ orderData.code || "无" }}</span>
      </div>
      <div class="info-item">
        <span class="label">订单名称:</span>
        <span class="value">{{ orderData.name || "无" }}</span>
      </div>
      <div class="info-item">
        <span class="label">客户公司名称:</span>
        <span class="value">
          <span
            @click="openCustomerDetail"
            style="color: #2244f5;cursor: pointer;"
            >{{ orderData.customerName || "-" }}</span
          >
        </span>
      </div>
      <div class="info-item">
        <span class="label">交货时间:</span>
        <span class="value">{{ orderData.deliveryDate || "-" }}</span>
      </div>
      <div class="info-item">
        <span class="label">下单时间:</span>
        <span class="value">{{ orderData.createTime || "-" }}</span>
      </div>
      <div class="info-item">
        <span class="label">提交人:</span>
        <span class="value">{{ orderData.createUserName || "" }}</span>
      </div>
    </el-col>
    <!-- 右侧金额信息：el-col  -->
    <el-col :span="12">
      <div class="info-item">
        <span class="label">公司指导价:</span>
        <span class="value">{{ orderData.standardPrice || "" }}</span>元
      </div>
      <div class="info-item">
        <span class="label">销售价:</span>
        <span class="value">{{ orderData.sellingPrice || "" }}</span>元
      </div>
      <!-- 分成金额 -->
      <div class="info-item formula">
        <span class="label">分成金额:</span>
        <span class="value">
          <span class="value">{{ orderData.splitPrice || "" }}</span>元
        </span>
      </div>
      <div class="info-item">
        <span class="label">申请优惠金额:</span>
        <span class="value">
          <el-input
            v-model="orderData.discountAmount"
            :disabled="isDisabled"
            style="width: 100px"
            placeholder="请输入"
          />元
        </span>
      </div>
      <!-- 提成金额 -->
      <div class="info-item">
        <span class="label">提成金额:</span>
        <span class="value">
          <el-input
            v-model="orderData.commissionPrice"
            :disabled="isDisabled"
            style="width: 150px"
            placeholder="请输入"
          />元
        </span>
      </div>
      <div class="info-item">
        <span class="label">提成比例:</span>
        <span class="value">
          <el-input
            v-model="orderData.commissionRate"
            placeholder="请输入"
            style="width: 150px"
            :disabled="isDisabled"
            @input="calcCommissionPrice"
          />%
        </span>
      </div>
      <div class="info-item" v-if="orderData.monetaryUnit !=='CNY'"> 
        <!-- 中国的话 不存在 -->
        <!-- {{orderData.monetaryUnit}} -->
        <span class="label">优惠汇率:</span>
        <span class="value">
          <el-input
            v-model="orderData.exchangeRate"
            :disabled="isDisabled"
            placeholder="请输入"
            style="width: 150px"
          />
        </span>
      </div>
    </el-col>
    </div>
  </el-row>
      <!-- 其他费用卡片 -->
      <div class="other-fee-card">
        <div class="card-header">其他费用</div>
        <div class="other-fee-container">
          <!-- 费用项列表 -->
          <div
            class="fee-row"
            v-for="(fee, index) in orderData.extraChargeList"
            :key="index"
          >
            <div class="fee-item">
              <span class="label">费用类别</span>
              <el-input
                v-model="fee.type"
                placeholder="请输入费用的类目名称"
                style="width: 250px"
                :disabled="isDisabled"
              />
            </div>
            <div class="fee-item">
              <span class="label">费用金额</span>
              <el-input
                v-model="fee.price"
                placeholder="请输入费用金额"
                style="width: 250px"
                type="number"
                :disabled="isDisabled"
              />
            </div>
            <!-- 按钮组（仅最后一行显示） -->
            <div
              class="btn-group" 
            >
            <template v-if="index === orderData.extraChargeList.length - 1 && !isDisabled">
            <el-button
                type="success"
                icon="el-icon-plus"
                circle
                @click="addFeeItem"
              />
              <el-button
                type="danger"
                icon="el-icon-minus"
                circle
                @click="removeFeeItem"
                :disabled="orderData.extraChargeList.length <= 1"
              />
            </template>
            
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 项目信息卡片 -->
    <div
      class="systemBox"
      v-if="
        !loading &&
        orderData &&
        orderData.projectList &&
        orderData.projectList.length > 0
      "
    >
      <div class="card-header">项目信息</div>
      <div class="system-info-container">
        <!-- 项目列表 -->
        <div
          class="system-item"
          v-for="(project, index) in orderData.projectList"
          :key="index"
          :class="{ expanded: expandProjectIndex === index }"
        >
          <div class="system-header" @click="toggleProject(index)">
            <div>
              <!-- {{project}} -->
              <!-- <span class="system-code">{{ project.code }}</span> -->
              <span class="system-name">{{ project.name }}</span>
              
              <span class="system-name">{{ project.unit }}</span>
              
              <span></span>
            </div>
           <div>
              <el-link type="primary" style="margin-left: 10px">
              {{ expandProjectIndex === index ? "收起" : "展开" }}
            </el-link>
           </div>
          </div>

          <!-- 产品表格（展开时显示） -->
          <div v-if="expandProjectIndex === index">
            <el-table
              :data="project.productList"
              style="width: 100%; margin-top: 10px"
              border
              max-height="430px"
              size="small"
               :header-cell-style="{ 'text-align': 'center' }" 
                 :cell-style="{ 'text-align': 'center' }"       
            >
              <el-table-column prop="code" label="产品编号" width="170" />
              <el-table-column prop="name" label="产品名称" width="170"/>
              <el-table-column prop="spec" label="产品规格" width="170" />
              <el-table-column prop="num" label="产品数量" width="170" />
              <el-table-column prop="unit" label="单位" width="80"/>
              <el-table-column prop="standardPrice" label="公司指导价" width="210"/>
              <el-table-column prop="sellingPrice" label="销售价" width="210"/>
              <el-table-column prop="splitPrice" label="分成金额" width="210"/>
            </el-table>
            <div class="rowTotal">
              <div class="rowleft">
                合计条数:{{project.productList.length}}
              </div>
              <div class="rowright">
                <div class="item">
                公司指导价合计： {{project.standardPrice}}
              </div>
              <div  class="item">
                销售价合计： {{project.sellingPrice}}
              </div>
              <div class="item">
                分成金额合计： {{project.splitPrice}}
              </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 审批操作栏 -->
    <div class="approval-action-bar" v-if="!loading && orderData">
      <div v-if="isDisabled"  class="approval-action-box">
          <span style="color:#ffff">审批意见： </span> 
           <el-input
          v-model="orderData.approveRemarks"
          disabled
          style="width: 70vw; margin-right: 20px"
      />
      </div>
      <template v-if="!isDisabled">
          <el-input
          style=""
        v-model="orderData.approveRemarks"
        placeholder="请输入审批意见"
        style="width: 70vw; margin-right: 20px"
      />
      <el-button
        type="danger"
        style="margin-right: 10px"
        @click="handleApproval('reject')"
        v-if="!isDisabled"
        >拒绝</el-button
      >
      <el-button type="success" @click="handleApproval('resolve')"  v-if="!isDisabled">通过</el-button>
      </template>

    </div>
    <!-- 客户详情弹窗 -->

<el-dialog
  title="客户详情"
  :visible.sync="customerDialogVisible"
  width="450px"
  append-to-body
  :modal="false"
   class="customer-dialog"
>
  <div class="customer-detail">
    <div class="detail-item">
      <span class="detail-label">客户公司名称:</span>
      <span class="detail-value">{{ customerDetail.companyName || "-" }}</span>
    </div>
    <div class="detail-item">
      <span class="detail-label">国家:</span>
      <span class="detail-value">{{ customerDetail.countryValue || "-" }}</span>
    </div>
    <div class="detail-item">
      <span class="detail-label">客户联系人1:</span>
  
      <span class="detail-value">{{ customerDetail.contactMain ? customerDetail.contactMain.name : "-" }}</span>
    </div>
    <div class="detail-item">
      <span class="detail-label">联系人手机号:</span>
      <span class="detail-value">{{ customerDetail.contactMain ? customerDetail.contactMain.phone : "-" }}</span>
    </div>
    <div class="detail-item">
      <span class="detail-label">联系人邮箱:</span>
      <span class="detail-value">{{ customerDetail.contactMain ? customerDetail.contactMain.email : "-" }}</span>
    </div>
    <div class="detail-item">
      <span class="detail-label">联系人Whatsapp:</span>
      <span class="detail-value">{{ customerDetail.contactMain ? customerDetail.contactMain.imWhatsApp : "-" }}</span>
    </div>
    <div class="detail-item">
      <span class="detail-label">通讯地址1:</span>
      <span class="detail-value">{{ customerDetail.address1 || "-" }}</span>
    </div>
    <div class="detail-item">
      <span class="detail-label">通讯地址2:</span>
      <span class="detail-value">{{ customerDetail.address2 || "-" }}</span>
    </div>
    <div class="detail-item">
      <span class="detail-label">客户来源:</span>
      <span class="detail-value">{{ customerDetail.fromType || "-" }}</span>
    </div>
    <div class="detail-item">
      <span class="detail-label">备注:</span>
      <span class="detail-value">{{ customerDetail.remark || "-" }}</span>
    </div>
  </div>
</el-dialog>
  </div>
</template>
<script>
import basicCrumb from "@/components/basic-crumb/main";
import {
  fetchOrderDetail,
  submit,
  getExchangeRateList
} from "@/api/approval/approvalDetails.js";
import { searchData } from "@/api/customer/customer.js";

export default {
  components: {
    basicCrumb,
  },
  data() {
    return {
      customerDialogVisible: false,
      customerDetail: {},
      loading: false, // 加载状态
      orderData: {}, //
      expandProjectIndex: -1,
      // approveRemarks: "", // 审批意见
      orderId: "",
      isDisabled:""

    };
  },
  mounted() {
    const orderId = this.$route.query.orderId ||this.$route.query.id;
    this.isDisabled = this.$route.query.mode == 'view' 
    // 如果有orderId，调用接口获取订单详情
    if (orderId) {
      this.getOrderDetail(orderId);
      this.orderId = orderId;
    }
      
  },
  methods: {
    async getOrderDetail(orderId) {
      try {
        // 显示加载状态
        this.loading = true;
        // 调用后端订单详情接口
        const res = await fetchOrderDetail({ id: orderId });
        // 接口请求成功
        if (res.data.code === 200) {
          this.orderData = res.data.data; // 赋值订单数据
          if(this.$route.query.mode !== 'view' && this.orderData.targetCurrency !== 'CNY'){
           this.getExchangeRateList()
          }
          if (
            !this.orderData.extraChargeList ||
            this.orderData.extraChargeList.length === 0
          ) {
            this.orderData.extraChargeList = [{ type: "", price: "" }];
          }
           this.calcCommissionPrice();
        } else {
          this.$message.error("获取订单详情失败");
        }
      } catch (error) {
        console.error("获取订单详情异常:", error);
      } finally {
        // 无论成功失败，都关闭加载状态
        this.loading = false;
      }
    },
      // 获取汇率列表
    getExchangeRateList() {
      getExchangeRateList({
        baseCurrency: "CNY", // 基础货币
        targetCurrency: this.orderData.monetaryUnit, // 目标货币
        current: 1,
        size: 1000,
      })
        .then((res) => {
          if (res.data.code === 200) {
            const tableData = res.data.data.records || [];
              this.orderData.exchangeRate =  tableData[0].rate
            // this.total = res.data.data.total || 0;
          }
        })
        .catch(() => {});
    },
    // 新增：计算提成金额核心方法（提成比例变化时触发）
calcCommissionPrice() {
  // 1. 获取原始值，去除空格，处理空值
  const standardPrice = Number(this.orderData.standardPrice || 0); // 公司指导价
  let commissionRate = this.orderData.commissionRate ? this.orderData.commissionRate.toString().trim() : ''; // 提成比例（可能是字符串）
  
  // 2. 非数字/空值，提成金额置空，直接返回
  if (!/^\d+(\.\d+)?$/.test(commissionRate)) {
    this.orderData.commissionPrice = '';
    return;
  }

  // 3. 百分比转小数（如输入10 → 0.1），执行计算 提成金额 = 公司指导价 × 提成比例(小数)
  const rate = Number(commissionRate) / 100;
  let commissionPrice = standardPrice * rate;

  // 4. 保留2位小数，避免多位小数
  commissionPrice = commissionPrice.toFixed(2);
  // 去除末尾的.00，
  this.orderData.commissionPrice = commissionPrice.endsWith('.00') ? commissionPrice.split('.')[0] : commissionPrice;
},
    getContactValue(key) {
      // 多层判断：先判断contacts是否存在且是数组，再判断第一个元素是否存在，最后取对应属性
      if (
        this.customerDetail.contacts &&
        Array.isArray(this.customerDetail.contacts) &&
        this.customerDetail.contacts[0]
      ) {
        return this.customerDetail.contacts[0][key] || "-";
      }
      return "-";
    },
    /**
     * 打开客户详情弹窗并加载客户数据
     */
    async openCustomerDetail() {
      try {
        // 显示加载状态
        this.loading = true;
        const res = await searchData({
         companyName:this.orderData.customerName,
          current: 1,
          size: 1000,
        });
        console.log("res11111111",res)
       // 接口请求成功
        if (res.data.code === 200) {
          const data = res.data.data.records || []
          this.customerDetail = data[0]
          this.customerDialogVisible = true; // 显示客户详情弹窗
        } else {
          this.$message.error("获取客户详情失败"); // 提示错误信息
        }
      } catch (error) {
        // 捕获异常并打印日志
        console.error("获取客户详情异常:", error);
        this.$message.error("网络异常，请稍后重试"); // 提示网络异常
      } finally {
        // 加载状态
        this.loading = false;
      }
    },

    // 展开/收起项目信息
    toggleProject(index) {
      // 如果点击的是当前展开的项目，收起（设为-1）；否则展开（设为对应索引）
      this.expandProjectIndex = this.expandProjectIndex === index ? -1 : index;
    },
    /**
     * 方法：计算前端分页数据
     * @param {Object} system - 项目对象
     */
    calcPageData(system) {
      const { productList, currentPage, pageSize } = system;
      // 计算起始索引和结束索引
      const startIndex = (currentPage - 1) * pageSize;
      const endIndex = startIndex + pageSize;
      // 截取当前页数据（前端分页核心逻辑）
      system.pageProductList = productList.slice(startIndex, endIndex);
    },

    /**
     * 添加其他费用项
     * @returns {void}
     */
    addFeeItem() {
      // 向其他费用数组中添加新的空费用项
      this.orderData.extraChargeList.push({ type: "", price: "" });
    },

    /**
     * 移除最后一个其他费用项
     * @returns {void}
     */
    removeFeeItem() {
      // 至少保留一个费用项
      if (this.orderData.extraChargeList.length <= 1) return;
      // 删除最后一个费用项
      this.orderData.extraChargeList.pop();
    },

    // 审批通过操作
    async handleApproval(mode) {
      // if (!this.approveRemarks) {
      //   return this.$message.warning("请输入审批意见");
      // }
      if (mode === 'reject' && !this.orderData.approveRemarks.trim()) {
    return this.$message.warning("请输入审批意见");
  }
      //  3-通过 4-驳回
      let status = 3;
      if (mode == "reject") {
        status = 4;
      }
      try {
        const requestData = {
          id: this.orderData.id,
          commissionRate: this.orderData.commissionRate,
          exchangeRate: this.orderData.exchangeRate,
          commissionPrice: this.orderData.commissionPrice,
          status: status,
          approveRemarks:this.orderData.approveRemarks,
          extraChargeList: this.orderData.extraChargeList
            .filter((item) => item.type && item.price) // 只传有值的费用项
            .map((item) => ({
              type: item.type,
              price: item.price,
            })),
          discountAmount:this.orderData.discountAmount,
        };
      console.log("requestData1111",requestData)
        // 调用后端接口
        const res = await submit(requestData);
        console.log("res提交", res);
        if (res.data.code === 200) {
          if (mode == 'resolve') {
            this.$message.success("订单提交审批成功！");
          } else {
            this.$message.success("订单驳回成功！");
          }

          this.$router.push({
            path:"/approval/approvalRecord",
            query:{
              
            }
          });
        } else {
          this.$message.error();
        }
      } catch (error) {
        this.$message.error("网络异常，请稍后重试");
      }
    },
  },
};
</script>

<style scoped lang="scss">
.container {
  background-color: #ffffff;
  min-height: 100vh;
  box-sizing: border-box;
   margin-top: 8px;
  padding: 20px !important;
  position: relative;
  .page-title {
    font-size: 1.5vw;
    color: #151515;
    text-align: center;
    margin-bottom: 20px;
  }

  .boxcard {
    border: 1px solid #bbbbbb;
    margin: 20px;
    padding: 30px;
    border-radius: 20px;
    box-shadow: 0 2px 2px 0 #bbbbbb;
  }

  // 其他费用卡片样式
  .other-fee-card {
    border: 1px solid #bbbbbb;
    margin-top: 30px;
    padding: 20px;
    border-radius: 20px;
    box-shadow: 0 2px 2px 0 #bbbbbb;
  }

  .card-header {
    font-size: 1.2em;
    margin-bottom: 20px;
    font-weight: 500;
  }

  .order-info-container {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;

    .info-left,
    .info-right {
      width: 48%;
    }

    .info-item {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      line-height: 32px;
      // font-size: 1.2em;

      .label {
        width: 130px !important;
        text-align: left;
        // margin-right: 15px;
        color: #606266;
      }

      .value {
        color: #303133;
      }
    }
     ::v-deep .el-input {
      display: inline-flex;
      align-items: center;
      // 让输入框高度和line-height:32px匹配
      .el-input__inner {
        height: 32px !important;
        line-height: 32px !important;
        padding: 0 15px !important; // 重置内边距，避免过宽
        box-sizing: border-box;
      }
    }

    .formula {
      color: #909399;
    }
  }
  .systemBox {
    padding: 0 30px;
    margin-bottom: 150px;
  }

  // 其他费用容器样式
  .other-fee-container {
    width: 100%;

    // 每行费用项
    .fee-row {
      display: flex;
      align-items: center;
      margin-bottom: 15px;
      gap: 20px; // 费用项之间的间距
    }

    // 单个费用项（类别/金额）
    .fee-item {
      display: flex;
      align-items: center;
      width: 44%;
      .label {
        width: 80px;
        text-align: left;
        // margin-right: 10px;
        // color: #606266;
        font-size: 1em;
      }
    }

    // 按钮组
    .btn-group {
      width: 12%;
      display: flex;
      gap: 10px; // 按钮之间的间距
      margin-left: 20px;
    }
  }

  .system-info-container {
    .system-item {
      border: 1px solid #e6e6e6;
      border-radius: 15px;
      padding: 15px;
      margin-bottom: 15px;
      cursor: pointer;

      .system-header {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .system-code {
          margin-right: 8px;
          color: #606266;
        }

        .system-name {
          margin-right: 8px;
          font-weight: 500;
        }

        .system-count {
          margin-right: 20px;
          color: #606266;
        }

        .system-price {
          margin-left: auto;
          color: #303133;
          font-weight: 500;
        }
      }

      &.expanded {
        .system-header {
          margin-bottom: 10px;
        }
      }
    }

    .table-pagination {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      margin-top: 10px;
      font-size: 13px;
      color: #606266;
    }
  }

  .approval-action-bar {
    position: relative; 
    bottom: 0; // 贴紧页面底部
    left: 0; // 贴紧左侧
   right: 0; // 贴紧右侧
    z-index: 99; // 
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 30px;
    height: 60px;
    background-color: #1e3a8a;
    .approval-action-box{
      width: 100%;
      height: 60px;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    ::v-deep .el-input__inner {
      background-color: #1e3a8a;
      color: #ffffff;
      border-color: #ffffff;
      border-radius: 30px;
    }
  }

  // .customer-detail {
  //   color: #2244f5;
  //   font-size: 20px !important;
  // }


  .rowTotal{
    display: flex;
    justify-content: space-between;
    color: #606266;
    .rowright{
      display: flex;
      width:80%;
      justify-content: flex-end;
      .item{
        // width: 200px;
        margin: 0 20px;
      }
    }
  }
}
</style>

<style lang="scss">
.customer-dialog{
   .el-dialog__body{
     padding: 0 30px !important;
   } 
}
/* 专门处理弹窗 */
.customer-dialog .customer-detail {
  padding: 10px 20px;
  font-size: 14px;
  // color: #2244f5 !important;
}

.customer-dialog .detail-item {
  display: flex;
  align-items: flex-start;
  // padding: 10px 0;

}

.customer-dialog .detail-label {
  width: 110px;
  font-weight: 500;
  color: #606266;
  text-align: left;
  padding-right: 15px;
}

.customer-dialog .detail-value {
  flex: 1;
  // color: #2244f5 !important;
  // word-wrap: break-word;
  // word-break: break-all;
}
</style>