<template>
  <view class="container" style="paddingBottom:1rpx;">
    <u-navbar
      leftIconSize="40rpx"
      leftIconColor="#333333"
      title="物价记录"
    >
    </u-navbar>
    <view class="section">
      <view class="section-title">{{ title }}</view>
      <view class="form-view">
        <u--form labelPosition="left" :model="form" :rules="rules" ref="uForm" label-width="180rpx"
          :labelStyle="{ color: '#333333', fontSize: '30rpx', marginRight: '24rpx' }">
          <u-form-item label="商品类别" prop="categoryName" required @click="handleCategory">
            <view class="input-with-arrow">
              <u--input v-model="form.categoryName" readonly disabledColor="#ffffff" placeholder="请选择商品类别"
              inputAlign="left" :customStyle="inputBaseStyle"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
          <u-form-item label="商品名称" prop="productName" required @click="handleProductName">
            <view class="input-with-arrow">
              <u--input v-model="form.productName" readonly disabledColor="#ffffff" placeholder="请选择商品名称"
              inputAlign="left" :customStyle="inputBaseStyle"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
          <u-form-item label="子类别" prop="kind" required >
            <u--input v-model="form.kind"  placeholder="请填写子类别"
              inputAlign="left" :customStyle="inputBaseStyle"></u--input>
          </u-form-item>
          <u-form-item label="价格" prop="price" required >
            <u--input v-model="form.price" type="number" placeholder="请填写价格"
              inputAlign="left" :customStyle="inputBaseStyle"></u--input>
          </u-form-item>
          <u-form-item label="单位" prop="unitName" required @click="handleUnit">
            <view class="input-with-arrow">
              <u--input v-model="form.unitName" readonly disabledColor="#ffffff" placeholder="请选择单位"
              inputAlign="left" :customStyle="inputBaseStyle"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item> 
          <u-form-item label="记录时间" prop="recordTime" required @click="selectDate()">
            <view class="input-with-arrow">
              <u--input v-model="form.recordTime" readonly disabledColor="#ffffff" placeholder="请选择记录时间" inputAlign="left" :customStyle="inputBaseStyle"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
          <u-form-item label="地点" prop="address"  >
            <u--input v-model="form.address"  placeholder="请填写地点"
              inputAlign="left" :customStyle="inputBaseStyle"></u--input>
          </u-form-item>
          <u-form-item label="商家" prop="merchant"  >
            <u--input v-model="form.merchant"  placeholder="请填写商家"
              inputAlign="left" :customStyle="inputBaseStyle"></u--input>
          </u-form-item>
          <u-form-item label="备注" prop="remark"  labelPosition="top">
            <u--textarea v-model="form.remark" placeholder="请填写备注" autoHeight inputAlign="left" count
              maxlength="20000" style="border: 2rpx solid #dcdfe6 !important; height: 160rpx;"></u--textarea>
          </u-form-item>
        </u--form>
        <view class="form-btn">
          <u-button type="primary" text="提交" @click="submit"></u-button>
        </view>
      </view>
    </view>
    <u-toast ref="uToast"></u-toast>
    <u-picker 
      itemHeight="88" 
      :show="showCategory" 
      :columns="categoryTypeList" 
      keyName="dictLabel" 
      @cancel="handleCategoryCancel"
      @confirm="handleCategoryConfirm"
      :closeOnClickOverlay="true"
      :defaultIndex="[0]"
      cancelColor="#666666"
      confirmColor="#667eea"
      title="选择商品类别"
      ></u-picker>
    <u-picker 
      itemHeight="88" 
      :show="showProductName" 
      :columns="productNameList" 
      keyName="name" 
      @cancel="handleProductNameCancel"
      @confirm="handleProductNameConfirm"
      :closeOnClickOverlay="true"
      :defaultIndex="[0]"
      cancelColor="#666666"
      confirmColor="#667eea"
      title="选择商品名称"
      ></u-picker>
    <u-picker 
      itemHeight="88" 
      :show="showUnit" 
      :columns="unitList" 
      keyName="dictLabel" 
      @cancel="handleUnitCancel"
      @confirm="handleUnitConfirm"
      :closeOnClickOverlay="true"
      :defaultIndex="[0]"
      cancelColor="#666666"
      confirmColor="#667eea"
      title="选择单位"
      ></u-picker>
      <u-datetime-picker
    :show="datePickShow"
    mode="datetime"
    ref="recordTimeRef" 
    @cancel="datePickShow=false"
    @confirm="datePickConfirm"
    itemHeight="88"
  ></u-datetime-picker>
  </view>
</template>

<script setup>
import {getProductPriceRecord, addProductPriceRecord, updateProductPriceRecord } from '@/api/invest/productPriceRecord'
import { getDicts } from '@/api/system/dict/data.js'
import { listProductInfor } from '@/api/invest/productInfor'
const { proxy } = getCurrentInstance()
import dayjs from 'dayjs'
import {onLoad,onReady} from "@dcloudio/uni-app";
  // 计算属性与监听属性是在vue中而非uniap中 需要注意！！！
import {reactive ,toRefs,ref,computed ,getCurrentInstance }from "vue";
const datePickShow = ref(false)

const showCategory = ref(false)
const showProductName = ref(false)
const showUnit = ref(false)

const title = ref("物价记录")
const categoryTypeList = ref([])
const productNameList = ref([])

const flag = ref('add')
const unitList = ref([])
const inputBaseStyle = {
  background: '#ffffff',
  border: '2rpx solid #dcdfe6',
  borderRadius: '8rpx',
  padding: '0 24rpx',
  height: '68rpx',
  width: '100%',
  boxSizing: 'border-box'
}

const data = reactive({
form: {
  id: null,
    productId: null,
    price: null,
    recordTime: null,
    remark: null,
    createTime: null,
    createBy: null,
    updateTime: null,
    updatedBy: null,
    address: null,
    delFlag: null,
    merchant: null,
    fields: null,
    unit: null,
    kind: null,
    category: null
},
queryProductParams: {
  pageNum: 1,
  pageSize: 1000
},
rules: {
  categoryName: [{ required: true, message: '商品类别不能为空', trigger:['change', 'blur'] }],
  productName: [{ required: true, message: '商品名称不能为空', trigger: ['change', 'blur'] }],
  price: [{type: 'number', required: true, message: '价格不能为空', trigger: ['change', 'blur'] }],
  unitName: [{ required: true, message: '单位不能为空', trigger:['change', 'blur'] }],
  kind: [{ required: true, message: '子类别不能为空', trigger: ['change', 'blur'] }],
  recordTime: [{ required: true, message: '记录时间不能为空', trigger: ['change', 'blur'] }]
}
})
const { form, queryProductParams, rules} = toRefs(data)


onLoad((option) => {
     form.value.id = option.id
     flag.value = option.flag
     if(flag.value==null){
      if(form.value.id!=null){
      title.value="物价记录-修改"
     }else{
      title.value="物价记录-新增"
     }
     }else{
      title.value="物价记录-复制"
     }
   
})
onReady(() => {
  form.value.recordTime = dayjs(new Date().getTime()).format("YYYY-MM-DD HH:mm:ss")
  getData()
})
function  getData() {
 
      // 类型
      getDicts('product_category').then(res => {
      categoryTypeList.value =[res.data] 
    })
     // 类型
     getDicts('product_unit').then(res => {
      unitList.value =[res.data] 
    })

  
    if(form.value.id!=null){
      getProductPriceRecord(form.value.id).then(res => {
        form.value = res.data
        queryProductParams.value.category = form.value.category
       if(queryProductParams.value.category!=null){
      listProductInfor(queryProductParams.value).then((response) => {
        productNameList.value = [response.rows] 
       })   } 
        
       // 记账类型
       getDicts('product_category').then(result => {
        form.value.categoryName=dictStr(form.value.category, result.data)
       })
              // 交易类型
              getDicts('product_unit').then(result => {
        form.value.unitName=dictStr(form.value.unit, result.data)
       })
       if(flag.value!=null){
        form.value.recordTime = dayjs(new Date().getTime()).format("YYYY-MM-DD HH:mm:ss")
       }

      })
    }else {
      listProductInfor(queryProductParams.value).then((response) => {
  productNameList.value = [response.rows] 
})
    }
}
function dictStr(val, arr) {
    let str = ''
    arr.map(item => {
      if (item.dictValue === val) {
        str = item.dictLabel
      }
    })
    return str
  }

function handleCategory() {
      if (categoryTypeList.value[0].length === 0) {
        proxy.$refs['uToast'].show({
          message: '商品类别为空  ', type: 'warning'
        })
      } else {
        showCategory.value = true
      }
   }
function   handleCategoryConfirm(e) {
      form.value.categoryName = e.value[0].dictLabel
      form.value.category = e.value[0].dictValue
      queryProductParams.value.category = form.value.category
      form.value.productId = null
      form.value.productName = null
      form.value.kind = null
      form.value.unit = null
      form.value.unitName = null
      form.value.price = null
      listProductInfor(queryProductParams.value).then((response) => {
        productNameList.value = [response.rows] 
       })

     
      showCategory.value = false
      
}
function handleCategoryCancel() {
     showCategory.value = false
    }
    function handleProductName() {
      if (productNameList.value[0].length === 0) {
        proxy.$refs['uToast'].show({
          message: '商品名称为空  ', type: 'warning'
        })
      } else {
        showProductName.value = true
      }
   }
function   handleProductNameConfirm(e) {
      form.value.productName = e.value[0].name
      form.value.kind = e.value[0].name
      form.value.productId = e.value[0].id
      form.value.unit = e.value[0].unit
       // 单位
       getDicts('product_unit').then(result => {
          form.value.unitName=dictStr( form.value.unit, result.data)
         })
      showProductName.value = false
}
function handleProductNameCancel() {
     showProductName.value = false
}


function handleUnit() {
      if (unitList.value[0].length === 0) {
        proxy.$refs['uToast'].show({
          message: '单位为空  ', type: 'warning'
        })
      } else {
        showUnit.value = true
      }
   }
function   handleUnitConfirm(e) {
      form.value.unitName = e.value[0].dictLabel
      form.value.unit = e.value[0].dictValue
      showUnit.value = false
}
function handleUnitCancel() {
     showUnit.value = false
    }
function  selectDate() {
      datePickShow.value = true
      proxy.$refs['recordTimeRef'].innerValue = new Date().getTime()
  }
function datePickConfirm(e) {
      form.value.recordTime = dayjs(e.value).format("YYYY-MM-DD HH:mm:ss")
      datePickShow.value = false
  }
function submit() {
      proxy.$refs['uForm'].validate().then(() => {
        if (form.value.id != null) {
          if(flag.value==null){
            updateProductPriceRecord(form.value).then(res => {
            proxy.$refs['uToast'].show({
            message: '修改成功', complete() {
              uni.navigateTo({ url: `/pages/work/product/productPriceRecord/list` })
            }
          })
        })
          }else {
            form.value.id == null
            addProductPriceRecord(form.value).then(res => {
            proxy.$refs['uToast'].show({
            message: '新增成功', complete() {
              uni.navigateTo({ url: `/pages/work/product/productPriceRecord/list` })
            }
          })
        })
          }
        }else {
          addProductPriceRecord(form.value).then(res => {
            proxy.$refs['uToast'].show({
            message: '新增成功', complete() {
              uni.navigateTo({ url: `/pages/work/product/productPriceRecord/list` })
            }
          })
        })
        }
      })
    }
</script>

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

.section {
  margin: 24rpx;
  padding: 0;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
  overflow: hidden;

  .section-title {
    padding: 16rpx 24rpx;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #ffffff;
    line-height: 1.2;
    font-size: 28rpx;
    font-weight: 600;
    display: flex;
    align-items: center;
    
    &::before {
      content: '';
      width: 6rpx;
      height: 28rpx;
      background: #ffffff;
      border-radius: 3rpx;
      margin-right: 12rpx;
    }
  }

  .form-view {
    padding: 24rpx;

        .input-with-arrow {
      position: relative;
      width: 100%;

      .arrow-icon {
        position: absolute;
        right: 20rpx;
        top: 50%;
        transform: translateY(-50%);
        color: #c0c4cc;
        font-size: 20rpx;
        pointer-events: none;
        z-index: 10;
      }
    }

    .form-btn {
      padding-top: 16rpx;
    }
  }
}
</style>

<style lang="scss">
.form-btn .u-button {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
  border: none !important;
  border-radius: 24rpx !important;
  height: 80rpx !important;
  box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.4) !important;
}

.form-btn .u-button__text {
  font-size: 30rpx !important;
  font-weight: 500 !important;
  letter-spacing: 2rpx !important;
}
</style>