<template>
  <el-dialog :close-on-click-modal="false" :title="dialogTitle" :visible.sync="hotGoodsAddVisible" width="30%" :before-close="handleBeforeClose">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
      <el-form-item label="爆品分类" prop="categoryId">
        <el-select v-model="form.categoryId" placeholder="请选择爆品分类">
          <el-option v-for="item in categoryList" :key="item.id" :label="item.categoryName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="产品" prop="productId">
        <el-select
          :disabled="!!this.form.id"
          @change="handleSelectGoods"
          style="width: 100%"
          v-model="form.productId"
          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="productName">
        <el-input v-model="form.productName" placeholder="请填写爆品名称"></el-input>
      </el-form-item>

      <el-form-item label="爆品价格" prop="productPrice">
        <el-input v-model="form.productPrice" prefix="¥" placeholder="请输入爆品价格"></el-input>
      </el-form-item>

      <el-form-item label="活动区域" prop="regionalCodes">
        <el-cascader
          style="width: 100%"
          v-model="regionArrDialog"
          :props="regionProps"
          size="large"
          placeholder="请选择区域"
          @change="form.regionalCodes = [...new Set(regionArrDialog.map((i) => i[i.length - 1]))].join(',')"
        ></el-cascader>
        <div v-if="String(form.regionalCodes)">已选ID：{{ form.regionalCodes }}</div>
      </el-form-item>

      <el-form-item label="是否上架" prop="isPut">
        <el-select style="width: 100%" v-model="form.isPut" placeholder="请选择">
          <el-option label="上架" :value="1"></el-option>
          <el-option label="下架" :value="0"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="爆品主图链接" prop="productImage">
        <ImageUpload :limit="1" v-model="form.productImage"></ImageUpload>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="hotGoodsAddVisible = false">取 消</el-button>
      <el-button type="primary" :loading="isLoading" @click="handleConfirm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import ImageUpload from '@/components/ImageUpload'
import { getClassifyGetAll } from '@/api/commodity'
import { addHotGoods, editHotGoods } from '@/api/active/active_hot'
import { getExplosiveProductCategory } from '@/api/explosiveProduct/category'
import { getProvinceList, getChildAreaList } from '@/api/address'

export default {
  components: { ImageUpload },
  data() {
    return {
      categoryList: [],
      goodsList: [],
      hotGoodsAddVisible: false,
      searchGoodsLoading: false,
      dialogTitle: '新增爆品商品',
      isLoading: false,
      form: {
        id: void 0,
        productId: '',
        productName: '',
        productImage: '',
        productPrice: '',
        isPut: 1,
        categoryId: '',
        regionalCodes: ''
      },
      regionProps: {
        checkStrictly: true,
        multiple: true,
        lazy: true,
        label: 'name',
        value: 'id',
        lazyLoad(node, resolve) {
          const { level, value } = node
          if (level === 0) {
            resolve([{ id: 0, parentId: 0, name: '全中国', shortName: '全国', longitude: '108.55', latitude: '34.32', level: 1, sort: 1, status: true }])
          } else if (level === 1) {
            getProvinceList().then((res) => {
              resolve(res.data)
            })
          } else if (level != 0 && level != 1) {
            getChildAreaList(value).then((res) => {
              resolve(
                res.data.map((item) => {
                  item.leaf = level === 4
                  return item
                })
              )
            })
          }
        }
      },
      regionArrDialog: [],
      rules: {
        categoryId: [{ required: true, message: '请选择爆品分类', trigger: 'blur' }],
        productId: [{ required: true, message: '请选择商品', trigger: 'blur' }],
        productName: [{ required: true, message: '请输入爆品名称', trigger: 'blur' }],
        productImage: [{ required: true, message: '请输入爆品主图链接', trigger: 'blur' }],
        productPrice: [
          { 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'
          }
        ],
        regionalCodes: [{ required: true, message: '请选择地址', trigger: 'change' }],
        isPut: [{ required: true, message: '请选择是否上架', trigger: 'change' }]
      }
    }
  },

  watch: {
    hotGoodsAddVisible(visible) {
      if (!visible) {
        this.reset()
      }
    }
  },

  methods: {
    open(row) {
      if (row && typeof row === 'object') {
        this.form.id = row.id
        this.form.productId = row.productId
        this.form.productName = row.productName
        this.form.productImage = row.productImage
        this.form.productPrice = row.productPrice
        this.form.isPut = row.isPut
        this.form.regionalCodes = row.regionalCodesSource || ''
        this.form.categoryId = row.categoryId || ''
        this.dialogTitle = '编辑爆款产品'
      } else {
        this.dialogTitle = '新增爆品商品'
      }
      this.getCategory()
      this.hotGoodsAddVisible = true
    },

    async getCategory() {
      const res = await getExplosiveProductCategory({ page: 1, pageSize: 10000 })
      if (res.code === '200') {
        this.categoryList = res.data.list
      }
    },

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

    async handleSearchGoods(query) {
      if (query !== '') {
        this.searchGoodsLoading = true
        try {
          const queryData = {
            productName: query,
            page: 1,
            pageSize: 20
          }

          const res = await getClassifyGetAll(queryData)
          this.goodsList = res.data.list
        } catch (error) {
          this.goodsList = []
        } finally {
          this.searchGoodsLoading = false
        }
      } else {
        this.goodsList = []
      }
    },

    // 添加商品
    handleSelectGoods(productId) {
      const currentGoods = this.goodsList.find((item) => item.productId === productId)
      if (currentGoods) {
        this.form.productId = productId
        this.form.productName = currentGoods.productName
        this.form.productImage = currentGoods.image
        this.form.productPrice = Number(currentGoods.price) || 0
      }
    },

    // 重置数据
    reset() {
      this.form = {
        productId: '',
        productName: '',
        productImage: '',
        productPrice: '',
        isPut: 1,
        categoryId: '',
        regionalCodes: ''
      }
      this.goodsList = []
    },

    close() {
      this.hotGoodsAddVisible = false
    },

    async handleConfirm() {
      try {
        this.isLoading = true
        await this.$refs.formRef.validate()
        const api = this.form.id ? editHotGoods : addHotGoods
        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
      }
    }
  }
}
</script>

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