<template>
  <view class="order-detail-container">
    <!-- 顶部导航栏 -->
    <u-navbar :autoBack="true" :placeholder="true" v-hideNav>
      <template slot="center">
        <view class="navbar-center">
          <text class="navbar-item" @click="handleBrandClick">{{ topInfo.brand }}</text>
          <text class="navbar-divider">|</text>
          <text class="navbar-item" @click="handleModelClick">{{ topInfo.model }}</text>
          <text class="navbar-divider">|</text>
          <text class="navbar-item price" @click="handlePriceClick">¥{{ topInfo.price }}</text>
        </view>
      </template>
      <template slot="right">
        <view class="navbar-right" @click="handleAddClick">
          <image src="/static/icons/plus.png" mode="scaleToFill" class="add-icon" />
          <text class="add-text">加一单</text>
        </view>
      </template>
    </u-navbar>

    <!-- 收单列表切换 -->
    <u-tabs 
      keyName="brand" 
      :list="receiptList" 
      @click="handleReceiptClick"
      class="receipt-tabs"
    />

    <!-- 订单详情视图 -->
    <OrderDetailView 
      :order-detail="orderDetail" 
      :top-info="topInfo" 
      :order-id="orderId"
      :current-receipt="currentReceipt" 
    />

    <!-- 加一单模态窗 -->
    <u-modal 
      :show="addOneModalVisible" 
      title="加一单" 
      showCancelButton 
      @cancel="handleAddOneCancel"
      @confirm="handleAddOneConfirm"
    >
      <view class="add-one-modal-content">
        <view class="add-one-form-item">
          <text class="form-label">品牌<text class="required">*</text></text>
          <u-button 
            type="primary" 
            plain 
            @click="showBrandSelector = true"
            class="brand-select-btn"
          >
            {{ currentAddBrand.dictLabel || '点击请选择品牌' }}
          </u-button>
        </view>
        <view class="add-one-form-item">
          <text class="form-label">型号</text>
          <u-input 
            v-model="currentAddModel" 
            placeholder="请输入型号" 
            class="form-input"
          />
        </view>
        <view class="add-one-form-item">
          <text class="form-label">价格</text>
          <u-input 
            v-model="currentAddPrice" 
            placeholder="请输入价格" 
            type="number"
            class="form-input"
          />
        </view>
      </view>
    </u-modal>

    <!-- 品牌选择器 -->
    <u-picker 
      :show="showBrandSelector" 
      :columns="brandColumns" 
      keyName="dictLabel"
      @confirm="handleBrandConfirm" 
      @cancel="showBrandSelector = false" 
    />

    <!-- 编辑品牌选择器 -->
    <u-picker 
      :show="editBrandSelectorVisible" 
      :columns="brandColumns" 
      keyName="dictLabel"
      @confirm="handleEditBrandConfirm" 
      @cancel="editBrandSelectorVisible = false" 
    />

    <!-- 修改型号/价格弹窗 -->
    <CustomModal 
      :visible="modalVisible" 
      :title="modalConfig.title" 
      :value="modalConfig.value"
      :placeholder="modalConfig.placeholder" 
      @cancel="handleModalCancel" 
      @confirm="handleModalConfirm" 
    />
  </view>
</template>

<script>
import OrderDetailView from './components/OrderDetailView.vue'
import CustomModal from './components/CustomModal.vue'

export default {
  name: 'OrderDetailIndex',
  components: {
    OrderDetailView,
    CustomModal
  },
  data() {
    return {
      // 顶部信息
      topInfo: {
        brand: '',
        model: '',
        price: ''
      },
      // 路由参数
      orderId: '',
      clueId: '',
      item: '',
      type: '',
      // 订单详情
      orderDetail: {},
      // 收单列表
      receiptList: [],
      // 当前选中的收单
      currentReceipt: {},
      // 模态窗状态
      addOneModalVisible: false,
      showBrandSelector: false,
      editBrandSelectorVisible: false,
      modalVisible: false,
      // 品牌选择相关
      brandColumns: [[]],
      currentAddBrand: {},
      currentAddModel: '',
      currentAddPrice: '',
      // 模态窗配置
      modalConfig: {
        title: '',
        value: '',
        placeholder: ''
      },
      currentEditField: ''
    }
  },
  onLoad(options) {
    this.initParams(options)
    this.loadOrderDetail()
    this.loadReceiptList()
  },
  onPullDownRefresh() {
    // 下拉刷新时重新加载所有数据
    Promise.all([
      this.loadOrderDetail(),
      this.loadReceiptList()
    ]).finally(() => {
      uni.stopPullDownRefresh()
      uni.$u.toast('刷新成功')
    })
  },
  methods: {
    /**
     * 初始化参数
     */
    initParams(options) {
      const { item, orderId, type, clueId } = options
      this.item = item || ''
      this.orderId = orderId || ''
      this.type = type || ''
      this.clueId = clueId || ''
    },

    /**
     * 加载订单详情
     */
    async loadOrderDetail() {
      try {
        const res = await uni.$u.api.getClueSendFormVoByOrderId({
          id: this.orderId
        })
        if (res.code === 200) {
          this.orderDetail = res.data || {}
        }
      } catch (error) {
        console.error('加载订单详情失败:', error)
        uni.$u.toast('加载订单详情失败')
      }
    },

    /**
     * 加载收单列表
     */
    async loadReceiptList() {
      try {
        const res = await uni.$u.api.clueReceiptFormListByOrderId(this.orderId)
        if (res.code === 200) {
          this.receiptList = res.data || []
          // 默认选择第一个收单
          if (this.receiptList.length > 0) {
            this.handleReceiptClick(this.receiptList[0])
          }
        }
      } catch (error) {
        console.error('加载收单列表失败:', error)
        uni.$u.toast('加载收单列表失败')
      }
    },

    /**
     * 点击收单项
     */
    handleReceiptClick(item) {
      this.currentReceipt = item
      this.topInfo.brand = item.brand || '暂无'
      this.topInfo.model = item.model || '暂无'
      this.topInfo.price = item.sellingPrice || '暂无'
    },

    /**
     * 点击品牌
     */
    handleBrandClick() {
      this.editBrandSelectorVisible = true
      this.loadBrandList()
    },

    /**
     * 点击型号
     */
    handleModelClick() {
      this.modalConfig = {
        title: '修改型号',
        value: this.currentReceipt.model || '',
        placeholder: '请输入型号'
      }
      this.currentEditField = 'model'
      this.modalVisible = true
    },

    /**
     * 点击价格
     */
    handlePriceClick() {
      this.modalConfig = {
        title: '修改价格',
        value: this.currentReceipt.sellingPrice?.toString() || '',
        placeholder: '请输入价格'
      }
      this.currentEditField = 'price'
      this.modalVisible = true
    },

    /**
     * 点击加一单
     */
    handleAddClick() {
      this.addOneModalVisible = true
      this.loadBrandList()
    },

    /**
     * 加载品牌列表
     */
    async loadBrandList() {
      try {
        const res = await this.$getDicts('crm_form_brand')
        this.brandColumns = [res]
      } catch (error) {
        console.error('加载品牌列表失败:', error)
      }
    },

    /**
     * 确认修改模态窗
     */
    async handleModalConfirm(value) {
      try {
        if (this.currentEditField === 'model') {
          await uni.$u.api.updateReceiptForm({
            model: value,
            id: this.currentReceipt.id
          })
        } else if (this.currentEditField === 'price') {
          await uni.$u.api.updateReceiptForm({
            sellingPrice: value,
            id: this.currentReceipt.id
          })
        }
        uni.$u.toast('修改成功')
        this.loadReceiptList()
      } catch (error) {
        console.error('修改失败:', error)
        uni.$u.toast('修改失败')
      } finally {
        this.modalVisible = false
      }
    },

    /**
     * 取消修改模态窗
     */
    handleModalCancel() {
      this.modalVisible = false
    },

    /**
     * 确认编辑品牌
     */
    async handleEditBrandConfirm(data) {
      try {
        await uni.$u.api.updateReceiptForm({
          brand: data.value[0].dictValue,
          id: this.currentReceipt.id
        })
        uni.$u.toast('修改成功')
        this.loadReceiptList()
      } catch (error) {
        console.error('修改品牌失败:', error)
        uni.$u.toast('修改失败')
      } finally {
        this.editBrandSelectorVisible = false
      }
    },

    /**
     * 确认选择品牌（加一单）
     */
    handleBrandConfirm(data) {
      this.currentAddBrand = data.value[0]
      this.showBrandSelector = false
    },

    /**
     * 确认加一单
     */
    async handleAddOneConfirm() {
      // 验证品牌是否已选择（必选）
      if (!this.currentAddBrand.dictValue) {
        uni.$u.toast('请选择品牌')
        return
      }
      
      try {
        await uni.$u.api.addReceiptForm({
          brand: this.currentAddBrand.dictValue,
          model: this.currentAddModel || '',
          sellingPrice: this.currentAddPrice || '',
          sendFormId: this.orderId,
          clueId: this.clueId
        })
        uni.$u.toast('添加成功')
        this.loadReceiptList()
      } catch (error) {
        console.error('添加失败:', error)
        uni.$u.toast('添加失败')
      } finally {
        this.addOneModalVisible = false
        this.currentAddBrand = {}
        this.currentAddModel = ''
        this.currentAddPrice = ''
      }
    },

    /**
     * 取消加一单
     */
    handleAddOneCancel() {
      this.addOneModalVisible = false
      this.currentAddBrand = {}
      this.currentAddModel = ''
      this.currentAddPrice = ''
    }
  }
}
</script>

<style scoped lang="scss">
.order-detail-container {
  min-height: 100vh;
  background-color: #f9fafb;
}

.navbar-center {
  display: flex;
  align-items: center;
  background-color: #fff;
  border-radius: 40rpx;
  padding: 10rpx 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.navbar-item {
  font-weight: bold;
  color: #333;
  font-size: 28rpx;
  
  &.price {
    color: blueviolet;
  }
}

.navbar-divider {
  margin: 0 15rpx;
  color: #ddd;
  font-size: 28rpx;
}

.navbar-right {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 20rpx;
  color: blueviolet;
}

.add-icon {
  width: 30rpx;
  height: 30rpx;
}

.add-text {
  margin-top: 4rpx;
}

.receipt-tabs {
  background-color: #fff;
}

.add-one-modal-content {
  padding: 20rpx 0;
}

.add-one-form-item {
  margin-bottom: 30rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 15rpx;
  font-weight: 500;
}

.required {
  color: #f56c6c;
  margin-left: 4rpx;
}

.brand-select-btn {
  width: 100%;
}

.form-input {
  width: 100%;
  border: 2rpx solid #e0e0e0;
  border-radius: 10rpx;
  padding: 20rpx;
  font-size: 28rpx;
}
</style>
