<template>
    <div class="edit-popup">

        <popup ref="popupRef" :title="popupTitle" :async="true" width="80%" @confirm="handleSubmit" @close="handleClose">


            <el-form ref="formRef" :model="formData" label-width="auto" :rules="formRules">
                <el-row :gutter="10">
                    <el-col :span="8">
                        <el-form-item label="材料大类" prop="first_level"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-select class="flex-1" v-model="formData.first_level" clearable placeholder="请选择材料大类"
                                @change="firstChange">
                                <el-option v-for="(item, index) in firstList" :key="index" :label="item.name"
                                    :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="材料中类" prop="second_level">


                            <el-select class="flex-1" v-model="formData.second_level" clearable placeholder="请选择材料中类"
                                @change="secondChange">
                                <el-option v-for="(item, index) in  secondList" :key="index" :label="item.name"
                                    :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="材料小类" prop="three_level">
                            <!-- <el-input v-model="formData.three_level" clearable placeholder="材料小类" /> -->
                            <el-select class="flex-1" v-model="formData.three_level" clearable placeholder="请选择材料小类">
                                <el-option v-for="(item, index) in  threedList" :key="index" :label="item.name"
                                    :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="材料编码" prop="code"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="formData.code" clearable placeholder="请输入材料编码" />
                        </el-form-item>
                    </el-col>


                    <el-col :span="8">
                        <el-form-item label="品牌" prop="brand">
                            <el-input v-model="formData.brand" clearable placeholder="请输入品牌" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="材料名称" prop="name"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="formData.name" clearable placeholder="请输入材料名称" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="规格型号" prop="specs"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="formData.specs" clearable placeholder="请输入规格型号" />
                        </el-form-item>
                    </el-col>


                    <el-col :span="8">
                        <el-form-item label="单位" prop="unit"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="formData.unit" clearable placeholder="请输入单位" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="安全库存量" prop="inventory">
                            <el-input v-model="formData.inventory" clearable placeholder="请输入安全库存量" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="24">
                        <el-form-item label="参数说明" prop="parameter_description">
                            <el-input v-model="formData.parameter_description" type="textarea" clearable
                                placeholder="请输入参数说明" />
                        </el-form-item>
                    </el-col>


                    <el-col :span="24">

                        <el-form-item label="附件" prop="field127">
                            <el-upload
                                accept="doc, docx, xls, xlsx, ppt, pptx, pdf, txt, zip, rar, tar, jpg, png, gif, jpeg, webp, wmv, avi, mpg, mpeg, 3gp, mov, mp4, flv, f4v, rmvb, mkv"
                                class="upload-demo" :show-file-list="false" aria-hidden="true"
                                :headers="{ Token: userStore.token }" :action="base_url + '/upload/file'"
                                :on-success="handleAvatarSuccess_four" ref="upload">
                                <el-button type="primary">
                                    上传
                                </el-button>
                            </el-upload>

                            <div>
                                <div v-for="(item, index) in formDataannex" style="margin-left: 5px;display: block;">
                                    <a style="margin-left: 10px; color: #4a5dff; align-self: flex-start" :href="item.uri"
                                        target="_blank">{{ item.name }}</a>
                                    <span style="cursor: pointer;margin-left: 5px;" @click="delFileFn(index)">x</span>
                                </div>
                            </div>

                        </el-form-item>
                    </el-col>


                    <el-col :span="8">
                        <el-form-item label="销售指导价" prop="sales_price">
                            <el-input v-model="formData.sales_price" clearable placeholder="请输入销售指导价" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="预算成本价" prop="cost_price">
                            <el-input v-model="formData.cost_price" clearable placeholder="请输入预算成本价" />
                        </el-form-item>
                    </el-col>



                </el-row>


            </el-form>
        </popup>

    </div>
</template>

<script lang="ts" setup name="projectEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { materialAdd, materialEdit, materialDetail } from '@/api/material_list'
import { apimaterialLists, apimaterialDatas } from '@/api/material_classify'
import { timeFormat } from '@/utils/util'
import { isEmail, isIdCard, isPhone } from '@/utils/validate'
import type { PropType } from 'vue'
import configs from "@/config"
import useUserStore from "@/stores/modules/user";
const base_url = configs.baseUrl + configs.urlPrefix
const userStore = useUserStore();
const formDataannex = reactive([])
const firstList = ref([])
const secondList = ref([])
const threedList = ref([])
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 handleAvatarSuccess_four = (
    response,
    uploadFile
) => {
    if (response.code == 0) {
        ElMessage.error(response.msg);
        return;
    }
    formDataannex.push(
        { uri: response.data.uri, name: response.data.name }


    );
};
//点击获取下级分类
const firstChange = (e: any) => {
    // console.log(e)
    apimaterialDatas({ page_no: 1, page_size: 9999, pid: e }).then((res) => {
        secondList.value = res
    })
}
const secondChange = (e: any) => {
    apimaterialDatas({ page_no: 1, page_size: 9999, pid: e }).then((res) => {
        threedList.value = res
    })
}
// 删除上传的文件
const delFileFn = (index: number) => {
    formDataannex.splice(index, 1)
}
// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑自购材料表' : '新增自购材料表'
})

// 表单数据
const formData = reactive({
    id: '',
    first_level: '',
    second_level: '',
    three_level: '',
    code: '',
    brand: '',
    name: '',
    specs: '',
    unit: '',
    parameter_description: '',
    inventory: '',
    sales_price: '',
    cost_price: '',
    annex: [],
})

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

})


// 获取详情
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]
        }
    }
    if (data.annex && data.annex.length > 0) {

        const arry1 = data.annex.map((item: any, index: any) => {
            return {
                name: `文件${index + 1}`,
                uri: item
            };
        });
        Object.assign(formDataannex, arry1)

    }

    if (data.first_level) {
        firstChange(data.first_level)
    }

    if (data.second_level) {
        setTimeout(() => {
            secondChange(data.second_level)
        }, 1000)
    }

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


// 提交按钮
const handleSubmit = async () => {

    formData.annex = formDataannex.map((item: any) => item.uri)

    await formRef.value?.validate()


    const data = { ...formData }
    mode.value == 'edit'
        ? await materialEdit(data)
        : await materialAdd(data)
    popupRef.value?.close()
    emit('success')
}

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


}

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

//获取材料分类
const materialLists = () => {
    apimaterialLists({ page_no: 1, page_size: 9999 }).then((res) => {
        firstList.value = res.lists
    })
}

materialLists()
defineExpose({
    open,
    setFormData,
    getDetail
})
</script>
