<template>
  <view class="page-four-container">
    <!-- 入库信息卡片 -->
    <view class="card-wrap">
      <u--form labelPosition="top" :model="warehouseInfo" ref="form" class="address-section">
        <view class="address-header">
          <u-icon name="car-fill" size="36rpx" color="#108cff" class="location-icon" />
          <text class="address-title">入库信息</text>
        </view>

        <!-- 编码、快递单号、物流图片 -->


        <!-- 收单物品、收单类型 -->
        <u-row class="info-row" justify="space-between">
          <u-col span="5.8">
            <u-form-item label="收单物品" prop="item">
              <u--input v-model="warehouseInfo.item" placeholder="请输入收单物品" class="info-input" />
            </u-form-item>
          </u-col>
          <u-col span="5.8">
            <view @tap="selectCustomerServiceName">
              <u-form-item label="收单类型" prop="customerServiceNameLabel">
                <view class="click-wrapper info-input">
                  {{ warehouseInfo.customerServiceNameLabel || '点击选择收单类型' }}
                </view>
              </u-form-item>
              <u-picker :show="showCustomerServicePicker" :columns="customerServiceColumns" confirm keyName="label"
                @confirm="handleConfirmCustomerService" @cancel="showCustomerServicePicker = false" />
            </view>
          </u-col>
        </u-row>

        <!-- 类别、是否需要查码 -->
        <u-row class="info-row" justify="space-between">
          <u-col span="5.8">
            <view @tap="selectCategory">
              <u-form-item label="类别" prop="category">
                <view class="click-wrapper info-input">
                  {{ warehouseInfo.categoryLabel || '点击选择类别' }}
                </view>
              </u-form-item>
              <u-picker :show="showCategoryPicker" :columns="categoryColumns" confirm keyName="label"
                @confirm="handleConfirmCategory" @cancel="showCategoryPicker = false" />
            </view>
          </u-col>
          <u-col span="5.8">
            <view @tap="selectNeedCheckCode">
              <u-form-item label="是否需要查码" prop="needCheckCode">
                <view class="click-wrapper info-input">
                  {{ warehouseInfo.needCheckCodeLabel || '点击选择是否需要查码' }}
                </view>
              </u-form-item>
              <u-picker :show="showNeedCheckCodePicker" :columns="needCheckCodeColumns" confirm keyName="label"
                @confirm="handleConfirmNeedCheckCode" @cancel="showNeedCheckCodePicker = false" />
            </view>
          </u-col>
        </u-row>


        <u-row class="info-row" justify="space-between">
          <u-col span="4.5">
            <u-form-item label="编码" prop="codeStorage">
              <u--input v-model="warehouseInfo.codeStorage" placeholder="请输入编码" class="info-input"
                :disabled="warehouseInfo.needCheckCode === '2'" />
            </u-form-item>
          </u-col>
          <u-col span="4.5">
            <u-form-item label="快递单号" prop="expressOrderNo">
              <u--input v-model="warehouseInfo.expressOrderNo" placeholder="请输入快递单号" class="info-input" />
            </u-form-item>
          </u-col>
          <u-col span="2">
            <u-form-item label="物流图片" prop="uploadedImage">
              <view class="image-uploader" @click="selectImage">
                <u-icon v-if="!warehouseInfo.uploadedImage" name="camera-fill" size="48rpx" color="#909399"
                  class="camera-icon" />
                <image v-else :src="warehouseInfo.uploadedImage" mode="aspectFill" class="image-preview" />
              </view>
            </u-form-item>
          </u-col>
        </u-row>

        <!-- 表款、查码费 -->
        <u-row class="info-row" justify="space-between">
          <u-col span="5.8">
            <u-form-item label="表款">
              <u--input v-model="warehouseInfo.watchPrice" placeholder="请输入表款" class="info-input" type="number" />
            </u-form-item>
          </u-col>
          <u-col span="5.8">
            <u-form-item label="查码费">
              <u--input v-model="warehouseInfo.checkCodeFee" placeholder="请输入查码费" class="info-input" type="number"
                :disabled="warehouseInfo.needCheckCode === '2'" />
            </u-form-item>
          </u-col>
        </u-row>

        <!-- 好处费、运费 -->
        <u-row class="info-row" justify="space-between">
          <u-col span="5.8">
            <u-form-item label="好处费">
              <u--input v-model="warehouseInfo.benefitFee" placeholder="请输入好处费" class="info-input" type="number" />
            </u-form-item>
          </u-col>
          <u-col span="5.8">
            <u-form-item label="运费">
              <u--input v-model="warehouseInfo.freight" placeholder="请输入运费" class="info-input" type="number" />
            </u-form-item>
          </u-col>
        </u-row>

        <!-- 维修金额、分单比例 -->
        <u-row class="info-row" justify="space-between">
          <u-col span="5.8">
            <u-form-item label="维修金额">
              <u--input v-model="warehouseInfo.repairAmount" placeholder="请输入维修金额" class="info-input" type="number" />
            </u-form-item>
          </u-col>
          <u-col span="5.8">
            <u-form-item label="分单比例（0~100）">
              <u--input v-model="warehouseInfo.splitRatio" placeholder="请输入分单比例(0~100)" class="info-input"
                type="number" />
            </u-form-item>
          </u-col>
        </u-row>

        <!-- 成本合计、业绩、毛业绩 -->
        <u-row class="info-row" justify="space-between">
          <u-col span="3.8">
            <u-form-item label="成本合计">
              <u--input :disabled="true" :value="computedTotalCost" placeholder="成本合计自动计算" class="info-input"
                type="number" />
            </u-form-item>
          </u-col>
          <u-col span="3.8">
            <u-form-item label="业绩">
              <u--input :disabled="true" :value="computedPerformance" placeholder="业绩自动计算" class="info-input"
                type="number" />
            </u-form-item>
          </u-col>
          <u-col span="3.8">
            <u-form-item label="毛业绩">
              <u--input :disabled="true" :value="computedGrossPerformance" placeholder="毛业绩自动计算" class="info-input"
                type="number" />
            </u-form-item>
          </u-col>
        </u-row>

        <!-- 是否入库 -->
        <!-- <u-row class="info-row">
          <u-col span="12">
            <view @tap="selectIsWarehouse">
              <u-form-item label="是否入库" prop="isWarehouse">
                <view class="click-wrapper info-input">
                  {{ isWarehouseLabel || '点击选择是否入库' }}
                </view>
              </u-form-item>
              <u-picker :show="showIsWarehousePicker" :columns="isWarehouseColumns" confirm keyName="label"
                @confirm="handleConfirmIsWarehouse" @cancel="showIsWarehousePicker = false" />
            </view>
          </u-col>
        </u-row> -->

        <!-- 收单备注 -->
        <u-row class="info-row">
          <u-col span="12">
            <u-form-item label="收单备注">
              <u--textarea v-model="warehouseInfo.remarks" placeholder="请输入收单备注" class="info-textarea"
                confirmType="done" rows="4" />
            </u-form-item>
          </u-col>
        </u-row>
      </u--form>
    </view>

    <!-- 分成信息卡片 -->
    <view class="card-wrap">
      <view class="address-section">
        <view class="address-header add-button-container">
          <text class="address-title">分成信息</text>

          <view class="add-button" @click="addSplit">
            <u-icon name="plus" size="24rpx" color="#108cff" />
            <text>添加</text>
          </view>
        </view>

        <!-- 分成信息表格 -->
        <view class="split-table">
          <u-row class="split-table-header">
            <u-col span="4"><text class="header-text">关联</text></u-col>
            <u-col span="2"><text class="header-text">分成人</text></u-col>
            <u-col span="2"><text class="header-text">比例</text></u-col>
            <u-col span="1"><text class="header-text">类型</text></u-col>
            <u-col span="1"><text class="header-text">公司</text></u-col>
            <u-col span="2" class="action-column"><text class="header-text">操作</text></u-col>
          </u-row>
          <u-row v-for="(item, index) in profitSharingList" :key="item.uuid" class="split-table-row">
            <u-col span="4">
              <view class="table-cell">
                <u-button @click="handleSelectOrg(item)" :text="item.orgName || '选择组织'" plain />
              </view>
            </u-col>
            <u-col span="2">
              <view class="table-cell">
                <u-button @click="handleSelectPerson(item)" :text="item.userName || '选择人员'" plain />
              </view>
            </u-col>
            <u-col span="2">
              <view class="table-cell">
                <u--input v-model="item.commissionRate" type="number" class="percentage-input"
                  @input="handlePercentageInput(item)" min="0" max="100" precision="0" />
              </view>
            </u-col>
            <u-col span="1">
              <view class="table-cell">
                <view :class="['account-type', item.accountType == '1' ? 'frontend' : 'backend']"
                  @click="toggleAccountType(item)">
                  {{ item.accountType == '1' ? '前' : '后' }}
                </view>
              </view>
            </u-col>
            <u-col span="1">
              <view class="table-cell">
                <view class="radio-wrapper" @click="toggleBelongToCompany(item)">
                  <view :class="['radio-circle', item.isCompanyPerformance == '1' ? 'active' : '']">
                    <u-icon v-if="item.isCompanyPerformance == '1'" name="checkmark" size="20rpx" color="#fff" />
                  </view>
                </view>
              </view>
            </u-col>
            <u-col span="2" class="action-column">
              <view class="table-cell">
                <u-button type="error" plain shape="circle" size="mini" @click="deleteRow(item.id, item.uuid)"
                  class="delete-btn">
                  <u-icon name="trash" size="20rpx" color="#ff6b6b" />
                </u-button>
              </view>
            </u-col>
          </u-row>
        </view>
      </view>
    </view>

    <!-- 确认收单、确认入库按钮 -->
    <view class="confirm-button-container">
      <u-row gutter="24">
        <u-col span="6">
          <u-button class="next-btn" type="success" @click="confirmReceiveOrder">
            <u-icon name="checkmark-circle-fill" size="28rpx" color="#fff" />
            <text style="margin-left: 8rpx;">确认收单</text>
          </u-button>
        </u-col>
        <u-col span="6">
          <u-button class="next-btn" type="success" @click="confirmWarehouseEntry">
            <u-icon name="checkmark-circle-fill" size="28rpx" color="#fff" />
            <text style="margin-left: 8rpx;">确认入库</text>
          </u-button>
        </u-col>
      </u-row>
    </view>

    <!-- 组织选择器 -->
    <u-picker :show="showOrgPicker" title="请选择组织" :columns="columnsOrgList" keyName="label" @confirm="handleOrgConfirm"
      @cancel="showOrgPicker = false" />

    <!-- 人员选择器 -->
    <u-picker :show="showPersonPicker" title="请选择分成人" :columns="columnsPersonList" keyName="label"
      @confirm="handleConfirmPerson" @cancel="handleCancelPerson" />

    <u-toast ref="uToast" />
  </view>
</template>

<script>
import imageUpload from '../utils/imageUpload.js'
import dayjs from 'dayjs'

export default {
  name: 'PageFour',
  props: {
    orderDetail: {
      type: Object,
      default: () => ({})
    },
    currentReceipt: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      warehouseInfo: {
        codeStorage: '',
        expressOrderNo: '',
        uploadedImage: '',
        item: '',
        checkCodeFee: '',
        watchPrice: '',
        benefitFee: '',
        freight: '',
        repairAmount: '',
        grossPerformance: '',
        performance: '',
        splitRatio: '',
        remarks: '',
        customerServiceNameLabel: '',
        customerServiceName: '',
        categoryLabel: '',
        category: '',
        needCheckCodeLabel: '',
        needCheckCode: ''
      },
      profitSharingList: [],
      showOrgPicker: false,
      showPersonPicker: false,
      columnsOrgList: [],
      columnsPersonList: [],
      showCustomerServicePicker: false,
      customerServiceColumns: [[
        { label: '收单类', value: '1' },
        { label: '维修类', value: '2' },
        { label: '销售类', value: '3' }
      ]],
      showCategoryPicker: false,
      categoryColumns: [[
        { label: '腕表', value: '1' },
        { label: '包包', value: '2' },
        { label: '首饰', value: '4' },
        { label: '其他', value: '3' }
      ]],
      showNeedCheckCodePicker: false,
      needCheckCodeColumns: [[
        { label: '是', value: '1' },
        { label: '否', value: '2' }
      ]],
      currentEditItem: '',


      isWarehouse: '2',
      isWarehouseLabel: '不入库',
      showIsWarehousePicker: false,
      isWarehouseColumns: [[
        { label: '确认入库', value: '1' },
        { label: '不入库', value: '2' }
      ]],
      brandList: []
    }
  },
  computed: {
    computedTotalCost() {
      const freight = Number(this.warehouseInfo.freight) || 0
      const benefitFee = Number(this.warehouseInfo.benefitFee) || 0
      const checkCodeFee = Number(this.warehouseInfo.checkCodeFee) || 0
      const watchPrice = Number(this.warehouseInfo.watchPrice) || 0
      const repairAmount = Number(this.warehouseInfo.repairAmount) || 0
      return freight + benefitFee + checkCodeFee + watchPrice + repairAmount
    },
    computedPerformance() {
      const sellingPrice = Number(this.currentReceipt.sellingPrice) || 0
      return sellingPrice - this.computedTotalCost
    },
    computedGrossPerformance() {
      const performance = this.computedPerformance || 0
      const splitRatio = Number(this.warehouseInfo.splitRatio) / 100 || 0
      return (performance * splitRatio).toFixed(2)
    }
  },
  watch: {
    currentReceipt: {
      handler(newVal) {
        if (newVal) {
          this.initWarehouseInfo(newVal)
          this.loadShareList()
        }
      },
      immediate: true,
      deep: true
    }
  },
  mounted() {
    this.loadCommissionUserList()
    this.loadBrandList()
  },
  methods: {
    /**
     * 加载品牌列表
     */
    async loadBrandList() {
      try {
        const res = await this.$getDicts('crm_form_brand')
        this.brandList = res
      } catch (error) {
        console.error('加载品牌列表失败:', error)
      }
    },

    /**
     * 初始化入库信息
     */
    initWarehouseInfo(data) {
      const receiptRemark = data.receiptRemark || ''
      const remarkParts = receiptRemark.split(';')

      // 设置默认值：收单类型默认为"收单类"，类别默认为"腕表"，是否需要查码默认为"是"
      const defaultCustomerServiceName = data.customerServiceName || '1'
      const defaultCategory = data.category || '1'
      const defaultNeedCheckCode = data.needCheckCode || '1'

      this.warehouseInfo = {
        codeStorage: data.code || '',
        expressOrderNo: data.expressOrderNo || '',
        uploadedImage: remarkParts[1] || '',
        item: data.item || '',
        checkCodeFee: data.checkCodeFee || '',
        watchPrice: data.tableFee || '',
        benefitFee: data.benefitFee || '',
        freight: data.freight || '',
        repairAmount: data.repairAmount || '',
        grossPerformance: data.grossPerformance || '',
        performance: data.performance || '',
        splitRatio: data.splitRatio || '',
        remarks: remarkParts[0] || '',
        customerServiceName: defaultCustomerServiceName,
        customerServiceNameLabel: this.getLabelByValue(
          this.customerServiceColumns[0],
          defaultCustomerServiceName
        ),
        category: defaultCategory,
        categoryLabel: this.getLabelByValue(
          this.categoryColumns[0],
          defaultCategory
        ),
        needCheckCode: defaultNeedCheckCode,
        needCheckCodeLabel: this.getLabelByValue(
          this.needCheckCodeColumns[0],
          defaultNeedCheckCode
        )
      }
    },

    /**
     * 根据值获取标签
     */
    getLabelByValue(columns, value) {
      const item = columns.find(col => col.value == value)
      return item ? item.label : ''
    },

    /**
     * 选择物流图片
     */
    async selectImage() {
      try {
        const tempFilePaths = await imageUpload.chooseImage(1)
        if (!tempFilePaths || tempFilePaths.length === 0) {
          uni.$u.toast('未获取到图片路径，请重试')
          return
        }
        const tempFilePath = tempFilePaths[0]
        const rep = await uni.$u.api.uploadFile(tempFilePath)
        if (rep.code == 200) {
          this.warehouseInfo.uploadedImage = rep.data.url
        }
      } catch (error) {
        console.error('上传图片失败:', error)
      }
    },

    /**
     * 加载分成人名单
     */
    async loadCommissionUserList() {
      try {
        const res = await uni.$u.api.getCustomerManagerAllList()
        this.columnsOrgList = [res.data[0].children]
      } catch (error) {
        console.error('加载分成人名单失败:', error)
      }
    },

    /**
     * 加载分成列表
     */
    async loadShareList() {
      if (!this.currentReceipt.sendFormId) return

      try {
        const { rows } = await uni.$u.api.selectCommissionList({
          pageSize: 9999,
          pageNum: 1
        }, { sendFormId: this.currentReceipt.sendFormId })

        const newRows = rows
          .filter(item => item.receiptFormId == this.currentReceipt.id)
          .map(item => ({
            ...item,
            uuid: Math.random()
          }))
        this.profitSharingList = newRows
      } catch (error) {
        console.error('加载分成列表失败:', error)
      }
    },

    /**
     * 添加分成行
     */
    addSplit() {
      this.profitSharingList.push({
        deptId: '',
        accountType: '1',
        userId: '',
        commissionRate: 0,
        isCompanyPerformance: '2',
        orgName: '',
        userName: '',
        id: '',
        uuid: Math.random()
      })
      this.calculateTotalPercentage()
    },

    /**
     * 重新计算分成比例
     */
    calculateTotalPercentage() {
      const frontItems = this.profitSharingList.filter(item => item.accountType == '1')
      const backItems = this.profitSharingList.filter(item => item.accountType == '2')
      const totalFrontItems = frontItems.length || 1
      const totalBackItems = backItems.length || 1

      this.profitSharingList.forEach(item => {
        if (item.accountType == '1') {
          item.commissionRate = Math.floor(100 / totalFrontItems)
        }
        if (item.accountType == '2') {
          item.commissionRate = Math.floor(100 / totalBackItems)
        }
      })
    },

    /**
     * 切换账户类型
     */
    toggleAccountType(item) {
      item.accountType = item.accountType == '1' ? '2' : '1'
      this.calculateTotalPercentage()
    },

    /**
     * 处理百分比输入
     */
    handlePercentageInput(item) {
      let value = Number(item.commissionRate)
      if (isNaN(value)) value = 0
      if (value < 0) value = 0
      if (value > 100) value = 100
      item.commissionRate = Math.floor(value)
    },

    /**
     * 切换归属公司
     */
    toggleBelongToCompany(item) {
      item.isCompanyPerformance = item.isCompanyPerformance == '1' ? '2' : '1'
    },

    /**
     * 选择组织
     */
    handleSelectOrg(item) {
      this.currentEditItem = item.uuid
      this.showPersonPicker = true
      this.columnsPersonList = this.columnsOrgList
    },

    /**
     * 选择人员
     */
    handleSelectPerson(item) {
      this.currentEditItem = item.uuid
      const deptId = item.deptId
      const org = this.findOrg(this.columnsOrgList[0], deptId)
      if (org) {
        this.columnsPersonList = [org.children]
      }
      this.showPersonPicker = true
    },

    /**
     * 递归查找组织
     */
    findOrg(orgList, deptId) {
      for (const org of orgList) {
        if (org.id == deptId) {
          return org
        }
        if (org.children && org.children.length > 0) {
          const found = this.findOrg(org.children, deptId)
          if (found) return found
        }
      }
      return null
    },

    /**
     * 确认选择组织
     */
    handleOrgConfirm({ value }) {
      this.profitSharingList.forEach(item => {
        if (item.uuid == this.currentEditItem) {
          item.orgName = value[0].label
          item.deptId = value[0].id
          item.userId = ''
          item.userName = ''
        }
      })
      this.showOrgPicker = false
    },

    /**
     * 确认选择人员
     */
    handleConfirmPerson({ value }) {
      if (value[0].isUser) {
        this.profitSharingList.forEach(item => {
          if (item.uuid == this.currentEditItem) {
            item.userName = value[0].label
            item.userId = value[0].id
          }
        })
        this.columnsPersonList = []
        this.showPersonPicker = false
      } else {
        this.profitSharingList.forEach(item => {
          if (item.uuid == this.currentEditItem) {
            item.orgName = value[0].label
            item.deptId = value[0].id
          }
        })
        this.columnsPersonList = [value[0].children]
      }
    },

    /**
     * 取消选择人员
     */
    handleCancelPerson() {
      this.columnsPersonList = []
      this.showPersonPicker = false
    },

    /**
     * 删除分成行
     */
    async deleteRow(id, uuid) {
      uni.showModal({
        title: '确认删除',
        content: '是否确认删除当前行分成比例？',
        success: async (res) => {
          if (res.confirm) {
            if (!id) {
              this.profitSharingList = this.profitSharingList.filter(item => item.uuid != uuid)
              this.calculateTotalPercentage()
              return
            }
            try {
              await uni.$u.api.deleteClueCommissionForm(id)
              uni.$u.toast('删除成功')
              this.loadShareList()
            } catch (error) {
              uni.$u.toast('删除失败')
            }
          }
        }
      })
    },

    /**
     * 选择收单类型
     */
    selectCustomerServiceName() {
      this.showCustomerServicePicker = true
    },

    /**
     * 确认收单类型
     */
    handleConfirmCustomerService({ value }) {
      this.warehouseInfo.customerServiceNameLabel = value[0].label
      this.warehouseInfo.customerServiceName = value[0].value
      this.showCustomerServicePicker = false
    },

    /**
     * 选择类别
     */
    selectCategory() {
      this.showCategoryPicker = true
    },

    /**
     * 确认类别
     */
    handleConfirmCategory({ value }) {
      this.warehouseInfo.categoryLabel = value[0].label
      this.warehouseInfo.category = value[0].value
      this.showCategoryPicker = false
    },

    /**
     * 选择是否需要查码
     */
    selectNeedCheckCode() {
      this.showNeedCheckCodePicker = true
    },

    /**
     * 确认是否需要查码
     */
    handleConfirmNeedCheckCode({ value }) {
      this.warehouseInfo.needCheckCodeLabel = value[0].label
      this.warehouseInfo.needCheckCode = value[0].value
      // 如果选择"否"，清空编码和查码费
      if (value[0].value === '2') {
        this.warehouseInfo.codeStorage = ''
        this.warehouseInfo.checkCodeFee = ''
      }
      this.showNeedCheckCodePicker = false
    },

    /**
     * 确认收单
     */
    async confirmReceiveOrder() {
      uni.showModal({
        title: '确认收单',
        content: `是否确认收单该订单：${this.orderDetail.item}？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              // 修改订单状态
              await uni.$u.api.oderForm({
                status: '3',
                id: this.orderDetail.id
              })

              // 更新收单表单
              await uni.$u.api.updateReceiptForm({
                id: this.currentReceipt.id,
                code: this.warehouseInfo.codeStorage || '',
                expressOrderNo: this.warehouseInfo.expressOrderNo || '',
                item: this.warehouseInfo.item || '',
                checkCodeFee: this.warehouseInfo.checkCodeFee || '',
                tableFee: this.warehouseInfo.watchPrice || '',
                benefitFee: this.warehouseInfo.benefitFee || '',
                freight: this.warehouseInfo.freight || '',
                repairAmount: this.warehouseInfo.repairAmount || '',
                grossPerformance: this.computedGrossPerformance || '',
                performance: this.computedPerformance || '',
                splitRatio: this.warehouseInfo.splitRatio || '',
                receiptRemark: `${this.warehouseInfo.remarks || ''};${this.warehouseInfo.uploadedImage || ''}`,
                customerServiceName: this.warehouseInfo.customerServiceName || '',
                category: this.warehouseInfo.category || '',
                needCheckCode: this.warehouseInfo.needCheckCode || '',
                totalCost: this.computedTotalCost || ''
              })

              // 上传分成数据
              await this.addShare()

              // //新增仓库或者编辑仓库
              // //等于1的时候放入仓库表
              // if (this.isWarehouse == '1') {
              //   // 获取品牌ID
              //   const brandObj = this.brandList.find(item => item.dictLabel === this.currentReceipt.brand)
              //   const brandId = brandObj ? brandObj.dictValue : ''

              //   //建立入库data
              //   // 获取 PageThree 的高清实物图的 fileUrl 数组
              //   // 直接使用 imageUpload 获取图片列表，与 PageThree 保持一致
              //   let goodPicFileUrls = []
              //   if (this.currentReceipt.id && this.orderDetail.itemBrand) {
              //     try {
              //       const list = await imageUpload.getFileList(
              //         '2',
              //         '3',
              //         this.currentReceipt.id,
              //         this.orderDetail.itemBrand,
              //         this.currentReceipt.clueId
              //       )
              //       // 获取前6个图片的 fileUrl（与 PageThree 的 displayImages 保持一致）
              //       // goodPicFileUrls = (list || []).slice(0, 6).map(item => item.fileUrl).filter(url => url)
              //       goodPicFileUrls = (list || []).map(item => item.fileUrl).filter(url => url)
              //     } catch (error) {
              //       console.error('获取高清实物图失败:', error)
              //     }
              //   }
                
              //   const warehouseData = {
              //     goodPicFileList: goodPicFileUrls,//商品图片 page3的高清实物图的url数组
              //     type: this.warehouseInfo.category || '',//商品分类 
              //     dictLabel: this.currentReceipt.brand || '',//品牌名称 
              //     dictValue: brandId || '',//品牌id 
              //     indentifyCode:this.warehouseInfo.codeStorage|| '',//独立编码
              //     costPrice: this.computedTotalCost || '',//总成本价
              //     recycleTime: dayjs().format('YYYY-MM-DD'),//回收时间 必填
              //     stockStatus:0,//库存状态，0待入库，1已入库，因为是我们是预入库，所以是0
              //     origin:this.orderDetail.website//来源
              //   }
              //   if (!this.currentReceipt.warehouseId) {
              //     //当没有仓库id的时候调用新增仓库接口
              //     await uni.$u.api.wareHouseAdd(warehouseData)
              //   } else {
              //     //当有仓库id的时候调用编辑仓库接口
              //     warehouseData.id = this.currentReceipt.warehouseId
              //     await uni.$u.api.wareHouseUpdate(warehouseData)
              //   }
              // } else if (this.isWarehouse == '2') {
              //   //等于2的时候不放入仓库表
              // }

              this.$refs.uToast.show({
                type: 'success',
                message: '收单成功',
                complete: () => {
                  uni.navigateBack({
                    delta: 1
                  })
                }
              })
            } catch (error) {
              console.error('收单失败:', error)
              uni.$u.toast('收单失败')
            }
          }
        }
      })
    },


    //确认入库
     confirmWarehouseEntry() {
      //点击了入库按钮
      //首先判断该大单的status是否为3，3代表已收单，如果为3，则提示已收单，不能入库
      console.log('xxxxx',this.orderDetail)
      if (this.orderDetail.status != '3') {
        uni.$u.toast('该订单未收单，不能入库')
        return
      }

      uni.showModal({
        title: '确认入库',
        content: `是否确认入库该订单：${this.orderDetail.item}-${this.currentReceipt.brand}？`,
        success: async (res) => {
          if (res.confirm) {
            //点击了确认入库，执行入库方法
            try {
              // 获取品牌ID
              const brandObj = this.brandList.find(item => item.dictLabel === this.currentReceipt.brand)
                const brandId = brandObj ? brandObj.dictValue : ''

                //建立入库data
                // 获取 PageThree 的高清实物图的 fileUrl 数组
                // 直接使用 imageUpload 获取图片列表，与 PageThree 保持一致
                let goodPicFileUrls = []
                if (this.currentReceipt.id && this.orderDetail.itemBrand) {
                  try {
                    const list = await imageUpload.getFileList(
                      '2',
                      '3',
                      this.currentReceipt.id,
                      this.orderDetail.itemBrand,
                      this.currentReceipt.clueId
                    )
                    // 获取前6个图片的 fileUrl（与 PageThree 的 displayImages 保持一致）
                    // goodPicFileUrls = (list || []).slice(0, 6).map(item => item.fileUrl).filter(url => url)
                    goodPicFileUrls = (list || []).map(item => item.fileUrl).filter(url => url)
                  } catch (error) {
                    console.error('获取高清实物图失败:', error)
                  }
                }
                
                const warehouseData = {
                  goodPicFileList: goodPicFileUrls,//商品图片 page3的高清实物图的url数组
                  type: this.warehouseInfo.category || '',//商品分类 
                  dictLabel: this.currentReceipt.brand || '',//品牌名称 
                  dictValue: brandId || '',//品牌id 
                  indentifyCode:this.warehouseInfo.codeStorage|| '',//独立编码
                  costPrice: this.computedTotalCost || '',//总成本价
                  recycleTime: dayjs().format('YYYY-MM-DD'),//回收时间 必填
                  stockStatus:0,//库存状态，0待入库，1已入库，因为是我们是预入库，所以是0
                  origin:this.orderDetail.website,//来源
                  actualPrice:this.currentReceipt.sellingPrice|| '',//实价，也就是顶部的第三个价格sellingPrice
                }
                if (!this.currentReceipt.warehouseId) {
                  //当没有仓库id的时候调用新增仓库接口
                  await uni.$u.api.wareHouseAdd(warehouseData)
                } else {
                  // //当有仓库id的时候调用编辑仓库接口
                  // warehouseData.id = this.currentReceipt.warehouseId
                  // await uni.$u.api.wareHouseUpdate(warehouseData)
                }

                this.$refs.uToast.show({
                type: 'success',
                message: '入库成功',
                complete: () => {
                  uni.navigateBack({
                    delta: 1
                  })
                }
              })
            } catch (error) {
              console.error('入库失败:', error)
              uni.$u.toast('入库失败')
            }
          }
        }
      })
    },

    /**
     * 上传分成
     */
    async addShare() {
      for (const item of this.profitSharingList) {
        const data = {
          id: item.id || '',
          accountType: item.accountType == '1' ? 1 : 2,
          clueId: this.currentReceipt.clueId,
          commissionRate: item.commissionRate,
          isCompanyPerformance: item.isCompanyPerformance == '1' ? 1 : 2,
          sendFormId: this.currentReceipt.sendFormId,
          userId: item.userId,
          userName: item.userName,
          receiptFormId: this.currentReceipt.id
        }
        if (item.id) {
          await uni.$u.api.clueCommissionUpdate(data)
        } else {
          await uni.$u.api.clueCommissionAdd(data)
        }
      }
    },
    selectIsWarehouse() {
      this.showIsWarehousePicker = true
    },
    handleConfirmIsWarehouse({ value }) {
      this.isWarehouse = value[0].value
      this.isWarehouseLabel = value[0].label
      this.showIsWarehousePicker = false
    },
  }
}
</script>

<style scoped lang="scss">
@import '../styles/common.scss';

.page-four-container {
  @extend .page-container;
  padding-bottom: 100rpx;
}

.address-section {
  padding: 20rpx;

  // 防止 label 换行
  ::v-deep .u-form-item__body__left__content__label {
    white-space: nowrap !important;
    overflow: visible;
  }
}

.info-row {
  margin-bottom: 20rpx;
}

.info-input {
  height: 65rpx;
  border-radius: 8rpx;
  border: 1rpx solid #e5e7eb;
  padding: 20rpx 16rpx;
  width: 100%;
  box-sizing: border-box;
}

.info-textarea {
  width: 100%;
  box-sizing: border-box;

  ::v-deep .u-textarea {
    min-height: 200rpx;
    border-radius: 8rpx;
    border: 1rpx solid #e5e7eb;
    padding: 20rpx 16rpx;
    line-height: 1.5;
  }

  ::v-deep textarea {
    min-height: 200rpx;
    border-radius: 8rpx;
    width: 100%;
    box-sizing: border-box;
    line-height: 1.5;
    font-size: 28rpx;
  }
}

.click-wrapper {
  width: 100%;
  cursor: pointer;
  display: flex;
  align-items: center;
}

.image-uploader {
  width: 100%;
  height: 65rpx;
  border: 2rpx dashed #409eff;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  background-color: #ecf5ff;
}

.image-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 10rpx;
}

.split-table {
  width: 100%;
  margin-top: 20rpx;
}

.split-table-header {
  background-color: #f5f7fa;
  padding: 15rpx 0;
  border-bottom: 1rpx solid #e4e7ed;
}

.split-table-row {
  padding: 15rpx 0;
  border-bottom: 1rpx solid #e4e7ed;
  align-items: center;
}

.header-text {
  @include font-styles($size: tiny, $weight: regular, $color: tertiary);
  text-align: center;
  display: block;
}

.table-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 10rpx;
}

.percentage-input {
  text-align: center;
  background-color: #f9f9f9;
  padding: 0rpx !important;
}

.account-type {
  padding: 4rpx 16rpx;
  border-radius: 12rpx;
  font-size: 24rpx;
  font-weight: 500;
  color: #fff;
  text-align: center;
  cursor: pointer;

  &.frontend {
    background-color: #409eff;
  }

  &.backend {
    background-color: #909399;
  }
}

.radio-wrapper {
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.radio-circle {
  width: 32rpx;
  height: 32rpx;
  border-radius: 50%;
  border: 2rpx solid #dcdfe6;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;

  &.active {
    border-color: #67c23a;
    background-color: #67c23a;
  }
}

.confirm-button-container {
  padding: 40rpx 0;
  margin-top: 20rpx;
}

.confirm-button-container .next-btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  border-radius: 11px;
}

.add-button-container {
  justify-content: space-between;
}
</style>
