<template>
  <el-dialog 
    :title="$t('chooseSingleResource.title')"
    :visible.sync="visible"
    width="60%"
    @close="closeDialog"
  >
    <el-form label-width="120px">
      <el-form-item :label="$t('chooseSingleResource.goodsType')">
        <el-select 
          v-model="form.rsId"
          placeholder="请选择"
          style="width:100%"
          @change="listSonResourceStoreType"
        >
          <el-option
            v-for="item in resourceStoreTypes"
            :key="item.rstId"
            :label="item.name"
            :value="item.rstId"
          />
        </el-select>
      </el-form-item>

      <template v-if="form.isCustom">
        <el-form-item :label="$t('chooseSingleResource.goodsName')">
          <el-input
            v-model="form.customGoodsName"
            :placeholder="$t('chooseSingleResource.goodsNamePlaceholder')"
          />
        </el-form-item>
      </template>
      
      <template v-else>
        <el-form-item :label="$t('chooseSingleResource.secondaryCategory')">
          <el-select 
            v-model="form.rstId"
            placeholder="请选择"
            style="width:100%"
            @change="choseGoods"
          >
            <el-option
              v-for="item in sonResourceStoreTypes"
              :key="item.rstId"
              :label="item.name"
              :value="item.rstId"
            />
          </el-select>
        </el-form-item>

        <el-form-item v-if="form.rstId" :label="$t('chooseSingleResource.goods')">
          <el-select 
            v-model="form.resId"
            placeholder="请选择"
            style="width:100%"
            @change="chosePrice"
          >
            <el-option
              v-for="item in resourceStores"
              :key="item.resId"
              :label="item.resName"
              :value="item.resId"
            />
          </el-select>
        </el-form-item>
      </template>

      <template v-if="form.resId || form.isCustom">
        <el-form-item :label="$t('chooseSingleResource.quantity')">
          <el-input-number
            v-model="form.useNumber"
            :min="1"
            label="数量"
          />
        </el-form-item>
      </template>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">{{ $t('chooseSingleResource.cancel') }}</el-button>
      <el-button type="primary" @click="confirmSelection">{{ $t('chooseSingleResource.confirm') }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { listResourceStoreTypes, listUserStorehouses } from '@/api/work/repairForceFinishManageApi'

export default {
  name: 'ChooseSingleResource',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    maintenanceType: {
      type: String,
      default: ''
    },
    repairId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      form: {
        maintenanceType: '',
        resourceStoreTypes: [],
        sonResourceStoreTypes: [],
        rstId: '',
        rsId: '',
        resId: '',
        repairId: '',
        selectedGoodsInfo: {},
        resourceStores: [],
        isCustom: false,
        customGoodsName: '',
        price: '',
        outLowPrice: '',
        outHighPrice: '',
        useNumber: 1,
        sign: ''
      }
    }
  },
  watch: {
    maintenanceType(newVal) {
      this.form.maintenanceType = newVal
    },
    repairId(newVal) {
      this.form.repairId = newVal
    }
  },
  mounted() {
    this.listResourceStoreType()
  },
  methods: {
    open(param) {
      this.form = {
        ...this.form,
        maintenanceType: param.maintenanceType,
        repairId: param.repairId || '',
        sign: param.sign || ''
      }
      this.listResourceStoreType()
    },
    closeDialog() {
      this.$emit('update:visible', false)
    },
    async listResourceStoreType() {
      try {
        const data = await listResourceStoreTypes('0')
        this.form.resourceStoreTypes = [...data, { rstId: 'custom', name: '自定义' }]
      } catch (error) {
        console.error('获取资源类型失败:', error)
        this.$message.error('获取资源类型失败')
      }
    },
    async listSonResourceStoreType() {
      if (this.form.rsId === 'custom') {
        this.form.isCustom = true
        return
      }
      
      this.form.isCustom = false
      try {
        const data = await listResourceStoreTypes(this.form.rsId)
        this.form.sonResourceStoreTypes = data
      } catch (error) {
        console.error('获取子资源类型失败:', error)
        this.$message.error('获取子资源类型失败')
      }
    },
    async choseGoods() {
      if (!this.form.rstId) return
      
      try {
        const params = {
          repairId: this.form.repairId,
          rstId: this.form.rstId,
          sign: this.form.sign
        }
        const data = await listUserStorehouses(params)
        this.form.resourceStores = data
      } catch (error) {
        console.error('获取商品失败:', error)
        this.$message.error('获取商品失败')
      }
    },
    chosePrice() {
      const selected = this.form.resourceStores.find(item => item.resId === this.form.resId)
      if (selected) {
        this.form.selectedGoodsInfo = selected
        if (selected.outLowPrice === selected.outHighPrice) {
          this.form.price = selected.outLowPrice
        } else {
          this.form.price = ''
        }
        this.form.outLowPrice = selected.outLowPrice
        this.form.outHighPrice = selected.outHighPrice
      }
    },
    confirmSelection() {
      if (this.validateForm()) {
        this.$emit('confirm', {
          ...this.form.selectedGoodsInfo,
          price: this.form.price,
          useNumber: this.form.useNumber,
          isCustom: this.form.isCustom,
          customGoodsName: this.form.customGoodsName
        })
        this.closeDialog()
      }
    },
    validateForm() {
      if (this.form.isCustom) {
        if (!this.form.customGoodsName) {
          this.$message.warning('请填写商品名')
          return false
        }
        if (this.form.maintenanceType === '1001' && !this.form.price) {
          this.$message.warning('请填写价格')
          return false
        }
      } else {
        if (!this.form.rsId) {
          this.$message.warning('请选择商品类型')
          return false
        }
        if (!this.form.rstId) {
          this.$message.warning('请选择二级分类')
          return false
        }
        if (!this.form.resId) {
          this.$message.warning('请选择商品')
          return false
        }
      }
      return true
    }
  }
}
</script>