<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="name">
                <el-input v-model="formData.name" clearable placeholder="请输入产品名称" />
            </el-form-item>
            <el-form-item label="产品编号" prop="code">
                <el-input v-model="formData.code" clearable disabled placeholder="请输入产品编号" />
            </el-form-item>
          <el-form-item label="产品介绍" prop="desc">
            <el-input v-model="formData.desc" />
          </el-form-item>
          <el-form-item label="产品图" prop="image">
              <el-upload
                  class="avatar-uploader"
                  :accept="acceptFileTypes"
                  v-model="formData.image"
                  :data="{ cid: 1 }"
                  :headers="{ Token: userStore.token }"
                  :action="action"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccessAvatar"
              >
                <img
                    v-if="formData.image"
                    :src="formData.image"
                    class="avatar"
                />
                <div v-else class="avatar-uploader-icon">
                  <el-icon>
                    <Plus />
                  </el-icon>
                </div>
              </el-upload>

          </el-form-item>

            <el-form-item v-if="formData.root == 1" label="所属用户" prop="user_id">
    <el-select
        v-model="formData.user_id"
        remote
        filterable
        placeholder="请输入用户信息"
        :remote-method="queryUser"
        @change="selectedUser"
        :loading="loading"
        clearable
      >
      <el-option
        v-for="(item, index) in optionsData.user"
        :key="index"
        :label="item.userinfo"
        :value="item.id"
    />
      </el-select>
</el-form-item>

            <el-form-item label="所属栏舍" prop="fence_house_id">
                <el-select
                    v-model="formData.fence_house_id"
                    remote
                    filterable
                    placeholder="请选择"
                    :remote-method="queryFenceHouse"
                    :loading="loading"
                    clearable
                >
                <el-option
                    v-for="(item, index) in optionsData.fenceHouse"
                    :key="index"
                    :label="item.fencehouseinfo"
                    :value="item.id"
                />
                </el-select>
            </el-form-item>
            </el-form>
        </popup>
    </div>
</template>

<script lang="ts" setup name="productEdit">
import { useDictOptions } from '@/hooks/useDictOptions'
import {  type FormInstance,
  type UploadProps,
  ElMessage,
   } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiProductAdd, apiProductEdit, apiProductDetail, getUserList, getUserInfo, apiLandLists } from '@/api/product'
import { timeFormat } from '@/utils/util'
import useUserStore from "@/stores/modules/user";
import type { PropType } from 'vue'
import {ref} from "vue";
import config from "@/config";
import {apiFenceHouseLists} from "@/api/monitor_threshold";
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.image = response.data.uri;
};
// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑产品' : '新增产品'
})
const fence_house_name = ref('')
// 表单数据
const formData = reactive({
    id: '',
    user_id: '',
    root: 0,
    fence_house_id: '',
    code: '',
    name: '',
    desc: '',
    image: '',
    status: '',
})


// 表单验证
const formRules = reactive<any>({
    code: [{
        required: true,
        message: '请输入产品编号',
        trigger: ['blur']
    }],
    name: [{
        required: true,
        message: '请输入产品名称',
        trigger: ['blur']
    }]
})


// 获取详情
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]
        }
    }
    //@ts-ignore
    formData.create_time = timeFormat(formData.create_time,'yyyy-mm-dd hh:MM:ss') 
}

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

const { optionsData } = useDictOptions<{
    user: any[]
    fenceHouse: any[]
}>({
    user: {
        api: getUserList
    },
  fenceHouse: {
        api: apiFenceHouseLists
    }
})

const loading = ref(false)

const queryUser = async (query: string) => {
    loading.value = true
    const userList = await getUserList({
        keyword: query ?? ''
    })
    optionsData.user = userList
    loading.value = false
}

const selectedUser = (value: any) => {
    optionsData.fenceHouse = []
    formData.fence_house_id = ''
    queryFenceHouse({user_id: value})
}
const queryFenceHouse = async (query: any) => {
  // string类型表示手动查询筛选条件
  if(typeof query == 'string') {
    query = {fence_house_name: query}
  }
  loading.value = true
  const fenceHouseList = await apiFenceHouseLists(query)
  optionsData.fenceHouse = fenceHouseList
  loading.value = false
}

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

const generateUuid = () => {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        const r = (Math.random() * 16) | 0
        const v = c == 'x' ? r : (r & 0x3) | 0x8
        return v.toString(16)
    })
}

//打开弹窗
const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
    formData.code = generateUuid() 
    getUserInfo()
        .then((res: any) => {
            const root = res.user.root ?? 0
            formData.root = root
            if (type == 'edit') {
              queryFenceHouse({user_id: formData.user_id})
            }
        })
        .catch((err: any) => {
            console.log('err', err)
        })
}

// 关闭回调
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>