<template>
    <div class="edit-add-detail">
        <div v-loading="detailLoading" class="form-content" element-loading-text="加载中...">
            <div class="page-form">
                <div class="content-area">
                    <el-form
                        ref="addEditFormRef"
                        :model="addEditForm"
                        :rules="addEditFormRules"
                        label-position="left"
                        label-suffix="："
                        size="large"
                    >
                        <el-collapse v-model="activeCollapse">
                            <!-- 准入申请信息 -->
                            <div id="access-application" class="content-section">
                                <el-collapse-item name="access-application">
                                    <template #title>
                                        <div class="section-title">
                                            <el-icon>
                                                <Document />
                                            </el-icon>
                                            <span>推荐供应商</span>
                                        </div>
                                    </template>
                                    <div class="section-content">
                                        <el-descriptions :column="2" border>
                                            <el-descriptions-item :span="2">
                                                <template #label>
                                                    <span class="required-asterisk">*</span>
                                                    供应商名称
                                                </template>
                                                <el-form-item prop="supplierId">
                                                    <el-select
                                                        v-model="addEditForm.supplierId"
                                                        :loading="supplierLoading"
                                                        :remote-method="remoteSearchSupplier"
                                                        clearable
                                                        filterable
                                                        placeholder="请输入"
                                                        remote
                                                        @change="changeEnterpr"
                                                    >
                                                        <el-option
                                                            v-for="item in enterpriseList"
                                                            :key="item.orgId"
                                                            :label="item.companyName"
                                                            :value="item.orgId"
                                                        >
                                                        </el-option>
                                                    </el-select>
                                                </el-form-item>
                                            </el-descriptions-item>
                                            <el-descriptions-item>
                                                <template #label>
                                                    <span class="required-asterisk">*</span>
                                                    推荐人
                                                </template>
                                                <el-form-item prop="referrer">
                                                    <el-input
                                                        v-model="addEditForm.referrer"
                                                        clearable
                                                        placeholder="请输入"
                                                    />
                                                </el-form-item>
                                            </el-descriptions-item>
                                            <el-descriptions-item>
                                                <template #label>
                                                    <span class="required-asterisk">*</span>
                                                    推荐单位
                                                </template>
                                                <el-form-item prop="recommendedDepartment">
                                                    <el-input
                                                        v-model="addEditForm.recommendedDepartment"
                                                        clearable
                                                        placeholder="请输入"
                                                    />
                                                </el-form-item>
                                            </el-descriptions-item>
                                            <el-descriptions-item :span="2">
                                                <template #label>
                                                    <span class="required-asterisk">*</span>
                                                    推荐时间
                                                </template>
                                                <el-form-item prop="applyDate">
                                                    <el-date-picker
                                                        v-model="addEditForm.applyDate"
                                                        placeholder="请选择"
                                                        type="datetime"
                                                        value-format="YYYY-MM-DD HH:mm:ss"
                                                    />
                                                </el-form-item>
                                            </el-descriptions-item>
                                            <el-descriptions-item :span="2">
                                                <template #label>
                                                    <span class="required-asterisk">*</span>
                                                    拟供应物资类型
                                                </template>
                                                <el-form-item prop="gategoryNames">
                                                    <el-input
                                                        v-model="addEditForm.gategoryNames"
                                                        :readonly="true"
                                                        placeholder="请选择"
                                                        @click="materialChange()"
                                                    >
                                                    </el-input>
                                                </el-form-item>
                                            </el-descriptions-item>
                                            <el-descriptions-item :span="2">
                                                <template #label>
                                                    <span class="required-asterisk">*</span>
                                                    供方基本情况调查表内容
                                                </template>
                                                <el-form-item prop="accessConfigurationName">
                                                    <el-input
                                                        v-model="
                                                            addEditForm.accessConfigurationName
                                                        "
                                                        clearable
                                                        disabled
                                                        placeholder="数据根据拟供应物资类型自动获取"
                                                    />
                                                </el-form-item>
                                            </el-descriptions-item>
                                            <el-descriptions-item :span="2">
                                                <template #label>
                                                    <span class="required-asterisk">*</span>
                                                    推荐理由
                                                </template>
                                                <el-form-item prop="drivingReasons">
                                                    <el-checkbox-group
                                                        v-model="addEditForm.drivingReasons"
                                                    >
                                                        <el-checkbox
                                                            v-for="item in getDictionaryByCode(
                                                                'zr-tjly'
                                                            )"
                                                            :key="item.value"
                                                            :label="item.name"
                                                            :value="item.value"
                                                        ></el-checkbox>
                                                    </el-checkbox-group>
                                                </el-form-item>
                                            </el-descriptions-item>
                                            <el-descriptions-item :span="2">
                                                <template #label>
                                                    <span class="required-asterisk">*</span>
                                                    供应商合作意愿
                                                </template>
                                                <el-form-item prop="cooperateWillingness">
                                                    <el-radio-group
                                                        v-model="addEditForm.cooperateWillingness"
                                                    >
                                                        <el-radio
                                                            v-for="item in getDictionaryByCode(
                                                                'zr-gyshzyy'
                                                            )"
                                                            :key="item.value"
                                                            :label="item.name"
                                                            :value="item.value"
                                                        ></el-radio>
                                                    </el-radio-group>
                                                </el-form-item>
                                            </el-descriptions-item>
                                            <el-descriptions-item :span="2">
                                                <template #label>
                                                    <span class="required-asterisk">*</span>
                                                    简要说明
                                                </template>
                                                <el-form-item prop="briefDescription">
                                                    <el-input
                                                        v-model="addEditForm.briefDescription"
                                                        :rows="4"
                                                        clearable
                                                        maxlength="200"
                                                        placeholder="请输入"
                                                        show-word-limit
                                                        type="textarea"
                                                    />
                                                </el-form-item>
                                            </el-descriptions-item>
                                        </el-descriptions>
                                    </div>
                                </el-collapse-item>
                            </div>
                        </el-collapse>
                    </el-form>
                </div>
            </div>
        </div>
        <div class="footer">
            <el-button :loading="submitLoading" type="primary" @click="handleSubmit"
                >提 交
            </el-button>
            <el-button @click="handleCancel"> 取 消</el-button>
        </div>

        <!-- 物资分类 -->
        <materialsDialog
            ref="dialogRef"
            v-model:isShowAdd="materialIsShowDialog"
            :selectedContent="materialSelectedContent"
            title="物资分类"
            @submit="materialSelectedChange"
        ></materialsDialog>
    </div>
</template>

<script lang="ts" setup>
import moment from 'moment'
import { getDictionaryByCode } from '@/utils/dictionary'
import type { FormInstance, FormRules } from 'element-plus'
import { CircleCheck, Document } from '@element-plus/icons-vue'
import {
    dataSubmit,
    dataDetail,
    getSupplier,
    getOwnerEnterprise,
    getBasicInfoList
} from '@/api/supplierMonitor/QualificationAudit/SupplyInfo'
import materialsDialog from '@/views/SupplierMonitor/QualificationAudit/SupplyInfo/materialsDialog.vue'

interface AddEditForm {
    [key: string]: string | number | undefined | null | any
}

const route = useRoute()
const router = useRouter()
const activeCollapse = ref(['access-application'])

const detailLoading = ref(false) // 详情加载状态

// 表单相关
const addEditFormRef = ref<FormInstance>()
const addEditFormRules = reactive<FormRules>({
    supplierId: [{ required: true, message: '请选择供应商', trigger: 'blur' }],
    referrer: [{ required: true, message: '请输入推荐人', trigger: 'blur' }],
    recommendedDepartment: [{ required: true, message: '请输入推荐单位', trigger: 'blur' }],
    applyDate: [{ required: true, message: '请选择推荐时间', trigger: 'change' }],
    gategoryNames: [{ required: true, message: '请选择拟供应物资', trigger: 'change' }],
    drivingReasons: [{ required: true, message: '请选择推荐理由', trigger: 'change' }],
    cooperateWillingness: [{ required: true, message: '请选择供应商合作意愿', trigger: 'change' }]
})
const addEditForm = reactive<AddEditForm>({
    applyDate: moment().format('YYYY-MM-DD HH:mm:ss'),
    drivingReasons: [],
    materialCategory2List: [],
    information: { enterprise: {} }
})

// 数据获取
const getDetail = async (id: string) => {
    // 获取详情逻辑
    detailLoading.value = true
    const { ...rest } = (await dataDetail(id)) as AddEditForm
    Object.assign(addEditForm, {
        ...rest
    })
    addEditForm.drivingReasons = addEditForm.drivingReasons.split(',')
    addEditForm.gategoryNames = addEditForm.materialCategory2List
        .map((item: any) => item.categoryName)
        .join(',')
    materialSelectedContent.value = addEditForm.materialCategory2List.map((item: any) => {
        return {
            ...item,
            id: item.categoryId
        }
    })
    if (addEditForm.supplierName) {
        remoteSearchSupplier(addEditForm.supplierName)
    }

    detailLoading.value = false
}

const submitLoading = ref<Boolean>(false)
const handleSubmit = async () => {
    addEditFormRef.value?.validate(async (valid: boolean, object: any) => {
        if (valid) {
            try {
                submitLoading.value = true
                let param = JSON.parse(JSON.stringify(addEditForm))
                param.drivingReasons = param.drivingReasons.join(',')
                param.createMethod = '3'
                const { state } = await dataSubmit(param)
                if (state) {
                    ElMessage.success('邀请成功')
                    handleCancel()
                }
            } finally {
                submitLoading.value = false
            }
        } else {
            ElMessage.warning(
                `有${Object.keys(object || {}).length}个字段未通过校验，请正确填写表单内容。`
            )
        }
    })
}

const handleCancel = () => {
    router.push({ name: 'SupplyInfo' })
}

// 供应物资选择
const materialIsShowDialog = ref(false)
const materialSelectedContent = ref([])
const materialChange = () => {
    materialIsShowDialog.value = true
}

const materialSelectedChange = (data: any) => {
    materialSelectedContent.value = data
    if (data.length > 0) {
        addEditForm.materialCategory2List = data.map(({ id, catName, ...rest }) => ({
            ...rest,
            catName: catName,
            categoryName: catName,
            categoryId: id
        }))
        addEditForm.gategoryNames = data.map((item: any) => item.catName).join(',')
        getBasicInfoListChange(data[0].id)
    } else {
        addEditForm.materialCategory2List = []
        addEditForm.gategoryNames = ''
    }
}

//获取供方基本情况调查表内容
const getBasicInfoListChange = async (id: string) => {
    const data = await getBasicInfoList(id)
    addEditForm.accessConfigurationName = data.name
    addEditForm.accessConfigurationId = data.id
}

//获取企业信息
const getEnterpriseList = async () => {
    const data = await getOwnerEnterprise()
    //推荐单位回显
    addEditForm.recommendedDepartment = data.companyName
}

//获取供应商信息
const enterpriseList = ref([])
const supplierLoading = ref(false)
const changeEnterpr = (value: any) => {
    enterpriseList.value.forEach((item: any) => {
        if (item.orgId === value) {
            addEditForm.supplierCode = item.companyCode
            addEditForm.supplierName = item.companyName
        }
    })
}
const remoteSearchSupplier = async (query: string) => {
    if (query) {
        supplierLoading.value = true
        try {
            const params = {
                pageBean: { page: 1, pageSize: -1 },
                querys: [
                    {
                        group: 'main',
                        operation: 'LIKE',
                        property: 'companyName',
                        relation: 'AND',
                        value: query
                    }
                ]
            }
            const { rows = [] } = await getSupplier(params)
            enterpriseList.value = rows
        } finally {
            supplierLoading.value = false
        }
    } else {
        enterpriseList.value = []
    }
}

onMounted(() => {
    const storedData = localStorage.getItem('user')
    if (storedData) {
        addEditForm.referrer = JSON.parse(storedData).userInfo.username
    }

    // 如果是编辑模式，获取详情数据
    if (route.query.id && typeof route.query.id === 'string') {
        getDetail(route.query.id)
    } else {
        getEnterpriseList()
    }
})

onUnmounted(() => {})
</script>

<style lang="scss" scoped>
.content-area {
    width: 100%;
    height: 100%;
}
</style>
