<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="160px" :rules="formRules">
                <div style="display: flex; flex-direction: row-reverse; justify-content: flex-start;margin-bottom: 30px;">
                    <el-select class="w-[180px]" v-model="formData.dept_id" clearable placeholder="请选择部门">
                        <el-option v-for="(item, index) in list2" :key="index" :label="item.name" :value="item.id" />
                    </el-select>
                    <el-select class="w-[180px]" v-model="formData.org_id" clearable placeholder="请选择组织" @change="deptrmt">
                        <el-option v-for="(item, index) in list1" :key="index" :label="item.name" :value="item.id" />
                    </el-select>
                </div>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="合同编号" prop="subcontracting_contract_id" @click="showDialog = true"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-input v-model="contract_no" clearable placeholder="请输入合同编号" />
                        </el-form-item> </el-col>

                    <el-col :span="8">
                        <el-form-item label="供应商名称" prop="subcontracting_contract_id">
                            <el-input v-model="supplier_name" clearable disabled placeholder="系统自动填写" />
                        </el-form-item> </el-col>
                    <el-col :span="8">
                        <el-form-item label="供应商编码" prop="subcontracting_contract_id">
                            <el-input v-model="supplier_code" clearable disabled placeholder="系统自动填写" />
                        </el-form-item> </el-col>

                    <el-col :span="8">
                        <el-form-item label="项目名称" prop="subcontracting_contract_id"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-input v-model="project_name" clearable disabled placeholder="系统自动填写" />
                        </el-form-item> </el-col>
                    <el-col :span="8">
                        <el-form-item label="项目编码" prop="subcontracting_contract_id"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-input v-model="project_code" clearable disabled placeholder="系统自动填写" />
                        </el-form-item> </el-col>
                    <el-col :span="8">
                        <el-form-item label="洽商编号" prop="negotiation_no">
                            <el-input v-model="formData.negotiation_no" clearable disabled placeholder="系统自动生成" />
                        </el-form-item> </el-col>
                    <el-col :span="8">
                        <el-form-item label="洽商单名称" prop="negotiation_name">
                            <el-input v-model="formData.negotiation_name" clearable placeholder="请输入洽商单名称" />
                        </el-form-item> </el-col>


                    <el-col :span="8">
                        <el-form-item label="签订日期" prop="sign_date">
                            <el-date-picker class="flex-1 !flex" v-model="formData.sign_date" clearable
                                value-format="YYYY-MM-DD" placeholder="选择签订日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="洽商金额" prop="negotiation_amount"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-input v-model="formData.negotiation_amount" clearable placeholder="请输入合同金额" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="洽商内容" prop="negotiation_content">
                            <el-input v-model="formData.negotiation_content" clearable placeholder="请输入洽商内容" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="具体说明" prop="negotiation_detail">
                            <el-input v-model="formData.negotiation_detail" clearable placeholder="请输入具体说明" />
                        </el-form-item>
                    </el-col>


                    <el-col :span="24">
                        <el-form-item label="洽商类别" prop="negotiation_type">
                            <el-radio-group v-model="formData.negotiation_type" placeholder="请选择付款方式">
                                <el-radio v-for="(item, index) in dictData.negotiation_type" :key="index"
                                    :label="parseInt(item.value)">
                                    {{ item.name }}
                                </el-radio>
                            </el-radio-group>
                        </el-form-item> </el-col>


                    <el-col :span="8">
                        <el-form-item label="洽商质保金额" prop="warranty_amount">
                            <el-input v-model="formData.warranty_amount" clearable placeholder="请输入不含税金额" />
                        </el-form-item> </el-col>
                    <el-col :span="8">
                        <el-form-item label="洽商质保到期时间" prop="warranty_expire_date">
                            <el-date-picker class="flex-1 !flex" v-model="formData.warranty_expire_date" clearable
                                value-format="YYYY-MM-DD" placeholder="选择洽商质保到期时间">
                            </el-date-picker>
                        </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" :key="index"
                                    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="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_five" ref="upload">
                                <el-button type="primary">
                                    上传
                                </el-button>
                            </el-upload>

                            <div>
                                <div v-for="(item, index) in formDataannex1" :key="index"
                                    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="delFileFn1(index)">x</span>
                                </div>
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <el-dialog v-model="showDialog" title="选择分包合同" width="70%">
                <procurementTable @customEvent="customEvent" :project_id="project?.id || ''"></procurementTable>
            </el-dialog>
        </popup>


    </div>
</template>

<script lang="ts" setup name="procurementContractEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { useDictData } from '@/hooks/useDictOptions'
import procurementTable from '@/components/procurement/index.vue'
import { apinegotiationAdd, apinegotiationEdit, apinegotiationDetail } from '@/api/subcontractor'
import { timeFormat } from '@/utils/util'
import type { PropType } from 'vue'
const { dictData } = useDictData('negotiation_type')
let props = defineProps({
    project: Object
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const showDialog = ref(false)
const list1 = reactive([])
const list2 = reactive([])
import { deptAll } from '@/api/org/department'
import { getAll } from '@/api/org/organization'
const project_name = ref('')
const project_code = ref('')
const formDataannex = reactive([])
const formDataannex1 = reactive([])
const supplier_name = ref('')
const supplier_code = ref('')
const contract_no = ref('')
const tableData = reactive([])
const tableData1 = reactive([])
import feedback from '@/utils/feedback'
import configs from "@/config"
const base_url = configs.baseUrl + configs.urlPrefix
import useUserStore from "@/stores/modules/user";
const userStore = useUserStore();
// 上传文件
const handleAvatarSuccess_four = (
    response,
    uploadFile
) => {
    if (response.code == 0) {
        feedback.msgError(response.msg);
        return;
    }
    formDataannex.push(
        { uri: response.data.uri, name: response.data.name }

    );
};
// 删除上传的文件
const delFileFn = (index: number) => {
    formDataannex.splice(index, 1)
}
// 上传文件
const handleAvatarSuccess_five = (
    response,
    uploadFile
) => {
    if (response.code == 0) {
        feedback.msgError(response.msg);
        return;
    }
    formDataannex1.push(
        { uri: response.data.uri, name: response.data.name }

    );
};
// 删除上传的文件
const delFileFn1 = (index: number) => {
    formDataannex1.splice(index, 1)
}


// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑分包洽商' : '新增分包洽商'
})
//获取所有组织
const getlist = () => {
    getAll().then((res) => {
        Object.assign(list1, res)
        if (res.length > 0 && !formData.org_id) {
            formData.org_id = res[0].id
            deptAll({ 'org_id': res[0].id }).then((res) => {
                if (res.length > 0) {
                    Object.assign(list2, res)
                    formData.dept_id = res[0].id
                }

            })
        }
    })
}
//获取部门
const deptrmt = (e: any) => {
    formData.dept_id = ''
    getlist1(e)

}
//获取所有部门
const getlist1 = (id: any) => {
    deptAll({ 'org_id': id }).then((res) => {
        list2.splice(0, list2.length, ...res)
    })
}
// 表单数据
const formData = reactive({
    id: '',
    dept_id: '',
    org_id: '',
    subcontracting_contract_id: '1',
    negotiation_name: '',
    negotiation_no: '',
    negotiation_amount: '',
    negotiation_type: '',
    signing_date: '',
    warranty_amount: '',
    Warranty_expire_date: '',
    negotiation_content: '',
    negotiation_quotation: [],
    negotiation_basis: [],
    negotiation_content: "",
    negotiation_detail: "",
    "sign_date": "string",

})
const customEvent = (e: any) => {
    contract_no.value = e.contract_no;
    supplier_name.value = e.supplier_name;
    supplier_code.value = e.supplier_code;
    formData.signing_date = e.signing_date;
    project_name.value = e.project_name;
    formData.subcontracting_contract_id = e.id;
    project_code.value = e.project_code
    showDialog.value = false;

};
if (props.project) {
    project_name.value = props.project.name
    project_code.value = props.project.project_code

}

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

})


// 获取详情
const setFormData = async (data: Record<any, any>) => {
    if (data.negotiation_quotation.length > 0) {

        const arry1 = data.negotiation_quotation.map((item: any, index: any) => {
            return {
                name: `文件${index + 1}`,
                uri: item
            };
        });
        Object.assign(formDataannex, arry1)
    }
    if (data.dept_id) {
        getlist1(data.org_id)
    }
    if (data.negotiation_basis.length > 0) {

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

    }
    project_name.value = data.project_name
    project_code.value = data.project_code
    contract_no.value = data.contract_no
    supplier_name.value = data.supplier_name
    supplier_code.value = data.supplier_code

    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }

    console.log(formData, "formdata")
    //@ts-ignore
    // formData.signing_date = timeFormat(formData.signing_date, 'YYYY-MM-DD ')
}

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


// 提交按钮
const handleSubmit = async () => {
    if (formDataannex.length > 0) {
        formData.negotiation_quotation = formDataannex.map((item) => item.uri)
    }
    if (formDataannex1.length > 0) {
        formData.negotiation_basis = formDataannex1.map((item) => item.uri)
    }
    await formRef.value?.validate()
    const data = { ...formData, }
    mode.value == 'edit'
        ? await apinegotiationEdit(data)
        : await apinegotiationAdd(data)
    popupRef.value?.close()
    emit('success')
}

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

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



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