<template>
  <div class="edit-popup">
    <popup
        ref="popupRef"
        :title="popupTitle"
        :async="true"
        width="550px"
        @confirm="handleSubmit"
        @close="handleClose"
    >
      <el-form ref="formRef" :model="formData" label-width="90px" :rules="formRules">
        <el-form-item label="养殖基地" prop="farm_id">
          <el-select
              v-model="formData.farm_id"
              remote
              filterable
              :remote-method="queryFarm"
              :loading="loading"
          >
            <el-option
                v-for="(item, index) in optionsData.farmList"
                :key="index"
                :label="item.farminfo"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="栏舍名称" prop="fence_house_name">
          <el-input v-model="formData.fence_house_name" clearable placeholder="请输入栏舍名称" />
        </el-form-item>
        <el-form-item label="动物名称" prop="animal_name">
          <el-input v-model="formData.animal_name" clearable placeholder="请输入栏舍名称" />
        </el-form-item>
        <el-form-item label="动物类型" prop="animal_type">
          <el-select class="flex-1" v-model="formData.animal_type" clearable placeholder="请选择动物类型">
            <el-option
                v-for="(item, index) in dictData.animal_type"
                :key="index"
                :label="item.name"
                :value="parseInt(item.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="栏舍类型" prop="fence_house_type">
          <el-select class="flex-1" v-model="formData.fence_house_type" clearable placeholder="请选择栏舍类型">
            <el-option
                v-for="(item, index) in dictData.fence_house_type"
                :key="index"
                :label="item.name"
                :value="parseInt(item.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="容量" prop="capacity">
          <el-input v-model="formData.capacity" clearable placeholder="请输入容量" />
        </el-form-item>
        <el-form-item label="负责人" prop="master">
          <el-input v-model="formData.master" clearable placeholder="请输入负责人" />
        </el-form-item>
        <el-form-item label="负责人电话" prop="master_phone">
          <el-input v-model="formData.master_phone" clearable placeholder="请输入负责人电话" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select class="flex-1" v-model="formData.status" clearable placeholder="请选择状态">
            <el-option
                v-for="(item, index) in dictData.system_disable"
                :key="index"
                :label="item.name"
                :value="parseInt(item.value)"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="图片" prop="pic">
          <el-upload
              class="avatar-uploader"
              :accept="acceptFileTypes"
              v-model="formData.pic"
              :data="{ cid: 1 }"
              :headers="{ Token: userStore.token }"
              :action="action"
              :show-file-list="false"
              :on-success="handleAvatarSuccessAvatar"
          >
            <img
                v-if="formData.pic"
                :src="formData.pic"
                class="avatar"
            />
            <div v-else class="avatar-uploader-icon">
              <el-icon>
                <Plus />
              </el-icon>
            </div>
          </el-upload>
        </el-form-item>

      </el-form>
    </popup>
  </div>
</template>

<script lang="ts" setup name="fenceHouseEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import {apiFenceHouseAdd, apiFenceHouseEdit, apiFenceHouseDetail, apiFenceHouseLists, apiFarmLists} from '@/api/fence_house'
import { timeFormat } from '@/utils/util'
import type { PropType } from 'vue'
import {useDictOptions} from "@/hooks/useDictOptions"
import {ref} from "vue"
import config from "@/config";
import useUserStore from "@/stores/modules/user";
import {ElMessage, type UploadProps} from "element-plus";

defineProps({
  dictData: {
    type: Object as PropType<Record<string, any[]>>,
    default: () => ({})
  }
})

const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')

const acceptFileTypes = ref(".png, .jpg, .jpeg, image/png, image/jpeg")
const action = ref(`${config.baseUrl}${config.urlPrefix}/upload/image`)
const userStore = useUserStore()
const handleAvatarSuccessAvatar: UploadProps["onSuccess"] = (
    response,
    uploadFile
) => {
  if (response.code == 0) {
    ElMessage.error(response.msg);
    return;
  }
  formData.pic.push(response.data.uri);
}

// 弹窗标题
const popupTitle = computed(() => {
  return mode.value == 'edit' ? '编辑栏舍管理' : '新增栏舍管理'
})

// 表单数据
const formData = reactive({
  id: '',
  farm_id: '',
  animal_name: '',
  fence_house_name: '',
  animal_type: '',
  fence_house_type: '',
  capacity: '',
  master: '',
  master_phone: '',
  status: '',
  qr_code: '',
  pic: [],

})


// 表单验证
const formRules = reactive<any>({

})

const { optionsData } = useDictOptions<{
  farmList: any[]
}>({
  farmList: {
    api: apiFarmLists,
  }
})


const loading = ref(false)

const queryFarm= async (query: string) => {
  loading.value = true
  const farmList = await apiFarmLists({
    farm_name: query ?? ''
  })
  optionsData.farmList = farmList
  loading.value = false
}


// 获取详情
const setFormData = async (data: Record<any, any>) => {
  for (const key in formData) {
    if (data[key] != null && data[key] != undefined) {
      //@ts-ignore
      formData[key] = data[key]
    }
  }


}

const getDetail = async (row: Record<string, any>) => {
  const data = await apiFenceHouseDetail({
    id: row.id
  })
  setFormData(data)
}


// 提交按钮
const handleSubmit = async () => {
  await formRef.value?.validate()
  const data = { ...formData,  }
  mode.value == 'edit'
      ? await apiFenceHouseEdit(data)
      : await apiFenceHouseAdd(data)
  popupRef.value?.close()
  emit('success')
}

//打开弹窗
const open = (type = 'add') => {
  mode.value = type
  popupRef.value?.open()
}

// 关闭回调
const handleClose = () => {
  emit('close')
}



defineExpose({
  open,
  setFormData,
  getDetail
})
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  width: 200px;
  height: 130px;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>