<template>
  <el-dialog v-model="state.dialogVisible" :title="props.title" width="900px" :close-on-click-modal="false"
    :close-on-press-escape="false" draggable destroy-on-close>
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" @submit.prevent>
      <div class="form-section">
        <div class="section-title">基本信息</div>
        <el-row :gutter="25">
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="描述" prop="itemDescription">
              <el-input v-model="form.itemDescription" placeholder="请输入描述" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="型号" prop="model">
              <el-select v-model="form.model" placeholder="请选择型号" style="width: 100%;">
                <el-option v-for="item in state.modelList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="容量(g)" prop="capacity">
              <el-input-number v-model="form.capacity" :min="0" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="皮重(g)" prop="tareWeight">
              <el-input-number v-model="form.tareWeight" :min="0" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="下限体积(g)" prop="lowerLimitVolume">
              <el-input-number v-model="form.lowerLimitVolume" :min="0" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="残余量" prop="residualVolume">
              <el-input-number v-model="form.residualVolume" :min="0" style="width: 100%;" />
            </el-form-item>

          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="图标" prop="materialIcon">
              <el-upload class="h100 personal-user-left-upload" :action="iconAction" :headers="iconHeaders"
                :data="{ autoUpdate: true }" :show-file-list="false" :before-upload="() => {
                    state.token = storesUserInfo.getToken()
                    state.iconLoading = true
                  }
                  " :on-success="iconSuccess" :on-error="iconError">
                <img :src="iconUrl" />
              </el-upload>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="状态" prop="status">
              <el-switch v-model="form.status" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="state.dialogVisible = false" size="default">取 消</el-button>
        <el-button type="primary" @click="onSubmit" size="default" :loading="state.sureLoading">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, computed, reactive, onMounted, getCurrentInstance } from 'vue'
import { BagDto, BagModelEnum } from '/@/api/admin/data-contracts'
import { ItemDefBagApi } from '/@/api/admin/item-def-bag'
import { DictApi } from '/@/api/admin/Dict'
import eventBus from '/@/utils/mitt'
import { useUserInfo } from '/@/stores/userInfo'
import pinia from '/@/stores/index'
import { storeToRefs } from 'pinia'
import { AxiosResponse } from 'axios'


const props = defineProps({
  title: {
    type: String,
    default: ''
  }
})

const { proxy } = getCurrentInstance() as any
const formRef = ref()
const storesUserInfo = useUserInfo(pinia)
const { userInfos } = storeToRefs(storesUserInfo)

const state = reactive({
  dialogVisible: false,
  sureLoading: false,
  modelList: [] as BagModelEnum[],
  iconLoading: false,
  token: storesUserInfo.getToken(),
})

const form = reactive<Partial<BagDto>>({
  id: 0,
  itemDescription: '',
  model: undefined,
  capacity: 0,
  tareWeight: 0,
  lowerLimitVolume: 0,
  residualVolume: 0,
  status: true,
  materialIcon: '',
})

const rules = {
  itemDescription: [{ required: true, message: '请输入描述', trigger: 'blur' }],
  model: [{ required: true, message: '请选择型号', trigger: 'change' }],
  capacity: [{ required: true, message: '请输入容量', trigger: 'blur' }],
  tareWeight: [{ required: true, message: '请输入皮重', trigger: 'blur' }],
  lowerLimitVolume: [{ required: true, message: '请输入下限体积', trigger: 'blur' }],
  residualVolume: [{ required: true, message: '请输入残余量', trigger: 'blur' }],
}

onMounted(async () => {
  try {
    const res = await new DictApi().getList(['bag_model'])
    if (res?.data?.bag_model) {
      state.modelList = res.data.bag_model.map((item: any) => ({
        value: Number(item.value) || 1,
        label: item.name || '',
      }))
    }
  } catch (error) {
    console.error('获取型号列表失败:', error)
  }
})

const open = (row?: Partial<BagDto>) => {
  state.dialogVisible = true
  if (row) {
    Object.assign(form, row)
    if (typeof row.model === 'object' && row.model !== null) {
      form.model = row.model
    }
  } else {
    Object.assign(form, {
      id: 0,
      itemDescription: '',
      model: undefined,
      capacity: 0,
      tareWeight: 0,
      lowerLimitVolume: 0,
      residualVolume: 0,
      status: true,
    })
  }
}

const onSubmit = async () => {
  if (!formRef.value) return
  state.sureLoading = true
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      if (form.id) {
        await new ItemDefBagApi().update(form as BagDto, { loading: true })
      } else {
        await new ItemDefBagApi().add(form as BagDto, { loading: true })
      }
      state.dialogVisible = false
      eventBus.emit('refreshLiquidBag')
    }
  })
  state.sureLoading = false
}

const iconUrl = computed(() => {
  return form.materialIcon || 'https://img2.baidu.com/it/u=1978192862,2048448374&fm=253&fmt=auto&app=138&f=JPEG?w=504&h=500'
})

const iconAction = computed(() => {
  return import.meta.env.VITE_API_URL + '/api/admin/user/avatar-upload'
})

const iconHeaders = computed(() => {
  return { Authorization: 'Bearer ' + state.token }
})

const iconSuccess = (res: AxiosResponse) => {
  state.iconLoading = false
  if (!res?.success) {
    if (res.msg) {
      proxy.$modal.msgError(res.msg)
    }
    return
  }
  form.materialIcon = res.data
}

const iconError = (error: any) => {
  state.iconLoading = false
  console.error('上传失败:', error)
}

defineExpose({
  open
})
</script>

<style scoped lang="scss">
.form-section {
  border: 1px solid #dcdfe6;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  position: relative;
}

.section-title {
  position: absolute;
  top: -10px;
  left: 10px;
  background-color: #fff;
  padding: 0 10px;
  font-size: 16px;
  font-weight: bold;
}

:deep(.el-upload) {
  height: 90px;
  width: 90px;
  img {
    width: 90px;
    height: 90px;
  }
}
</style>