<template>
  <el-dialog :close-on-click-modal="false" append-to-body :title="dialogTitle" :visible.sync="addExplosiveProductsSubsidiaryVisible" width="30%" :before-close="handleBeforeClose">
    <div class="add-explosive-productsSubsidiary-container">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="auto">
        <el-form-item label="配销商品" prop="subsidiaryProductId">
          <el-select
            :disabled="!!this.form.id"
            @change="handleSelectGoods"
            style="width: 100%"
            v-model="form.subsidiaryProductId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入商品名称"
            :remote-method="handleSearchGoods"
            :loading="searchGoodsLoading"
          >
            <el-option v-for="item in goodsList" :key="item.productId" :label="item.productName" :value="item.productId">
              <div class="name">{{ item.productName }} - {{ item.sectionPrice }}</div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="配销商品名称" prop="subsidiaryName">
          <el-input v-model="form.subsidiaryName" placeholder="请填写配销商品名称"></el-input>
        </el-form-item>
        <el-form-item label="配销商品价格" prop="subsidiaryPrice">
          <el-input v-model="form.subsidiaryPrice" prefix="¥" placeholder="请填写配销商品价格"></el-input>
        </el-form-item>
        <el-form-item label="配销产品图片" prop="subsidiaryImage">
          <ImageUpload :limit="1" v-model="form.subsidiaryImage"></ImageUpload>
        </el-form-item>
      </el-form>
    </div>

    <span slot="footer" class="dialog-footer">
      <el-button
        @click="
          reset()
          close()
        "
      >
        取 消
      </el-button>
      <el-button type="primary" :loading="isLoading" @click="handleConfirm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getClassifyGetAll } from '@/api/commodity'
import { addExplosiveProductsSubsidiary, editExplosiveProductsSubsidiary } from '@/api/active/active_hot'
import ImageUpload from '@/components/ImageUpload'

export default {
  components: { ImageUpload },
  data() {
    return {
      isLoading: false,
      dialogTitle: '添加配销产品',
      addExplosiveProductsSubsidiaryVisible: false,
      form: {
        id: void 0,
        explosiveId: void 0,
        subsidiaryName: '',
        subsidiaryPrice: '',
        subsidiaryProductId: '',
        subsidiaryImage: ''
      },
      goodsList: [],
      searchGoodsLoading: false,
      rules: {
        subsidiaryProductId: [{ required: true, message: '请选择商品', trigger: 'blur' }],
        subsidiaryName: [{ required: true, message: '请输入配销产品名称', trigger: 'blur' }],
        subsidiaryImage: [{ required: true, message: '请上传配销产品图片', trigger: 'change' }],
        subsidiaryPrice: [
          { required: true, message: '请输入配销产品价格', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              const priceRegex = /^\d+(\.\d{1,2})?$/
              if (!value) {
                callback(new Error('请输入配销产品价格'))
              } else if (!priceRegex.test(value) || parseFloat(value) <= 0) {
                callback(new Error('请输入有效的价格（正数，最多两位小数）'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },

  methods: {
    handleBeforeClose(done) {
      this.reset()
      done()
    },

    async open({ pid, item }) {
      if (item && typeof item === 'object') {
        this.form.id = item.id
        this.form.subsidiaryPrice = Number(item.subsidiaryPrice) || 0
        this.form.subsidiaryProductId = Number(item.subsidiaryProductId)
        this.form.subsidiaryName = item.subsidiaryName
        this.form.subsidiaryImage = item.subsidiaryImage
        this.dialogTitle = '编辑配销产品'
      } else {
        this.dialogTitle = '添加配销产品'
      }
      this.form.explosiveId = pid
      this.addExplosiveProductsSubsidiaryVisible = true
    },

    // 选择商品
    handleSelectGoods(productId) {
      const currentGoods = this.goodsList.find((item) => item.productId === productId)
      if (currentGoods) {
        this.form.subsidiaryName = currentGoods.productName
        this.form.subsidiaryPrice = Number(currentGoods.price) || 0
        this.form.subsidiaryImage = currentGoods.image
      }
    },

    // 远程搜索
    async handleSearchGoods(query) {
      if (query !== '') {
        this.searchGoodsLoading = true
        try {
          const queryData = { productName: query, page: 1, pageSize: 100 }
          const res = await getClassifyGetAll(queryData)
          this.goodsList = res.data.list
        } catch (error) {
          this.goodsList = []
        } finally {
          this.searchGoodsLoading = false
        }
      } else {
        this.goodsList = []
      }
    },

    // 添加
    async handleConfirm() {
      try {
        this.isLoading = true
        await this.$refs.formRef.validate()
        const api = this.form.id ? editExplosiveProductsSubsidiary : addExplosiveProductsSubsidiary
        const res = await api(this.form)
        if (res.code === '200') {
          this.$message({
            message: this.form.id ? '编辑成功' : '添加成功',
            type: 'success'
          })
          this.reset()
          this.$emit('refresh')
          this.close()
        }
      } finally {
        this.isLoading = false
      }
    },

    reset() {
      this.form = {
        explosiveId: void 0,
        subsidiaryName: '',
        subsidiaryPrice: '',
        subsidiaryProductId: '',
        subsidiaryImage: ''
      }
      this.goodsList = []
    },

    close() {
      this.addExplosiveProductsSubsidiaryVisible = false
    }
  }
}
</script>

<style lang="scss" scoped></style>
