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

            <el-steps :active="2" align-center>
                <el-step title="提交申请" description="Some description" />
                <el-step title="人事行政经理" description="Some description" />
                <el-step title="财务经理" description="Some description" />
                <el-step title="总经理" description="Some description" />
            </el-steps>



            <el-form ref="formRef" :model="formData" label-width="120px" :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="supplier_id" @click="showDialog = true" :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-input v-model="supplier_contract_name" readonly clearable placeholder="请选择供应商" />
                        </el-form-item> </el-col>
                    <el-col :span="8">
                        <el-form-item label="供应商编码" prop="supplier_id" :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-input v-model="supplier_contract_no" disabled clearable placeholder="系统自动填写" />
                        </el-form-item> </el-col>

                    <el-col :span="8">
                        <el-form-item label="合同编号" prop="contract_no">
                            <el-input v-model="formData.contract_no" clearable placeholder="由系统自动生成" />
                        </el-form-item> </el-col>
                    <el-col :span="8">
                        <el-form-item label="合同名称" prop="contract_name" :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-input v-model="formData.contract_name" clearable placeholder="请输入合同名称" />
                        </el-form-item> </el-col>

                    <el-col :span="24">


                        <el-form-item label="采购分类" prop="procurement_type" :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-radio-group v-model="formData.procurement_type" placeholder="请选择采购分类">
                                <el-radio v-for="(item, index) in dictData.procurement_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="asset_apply_no">
                            <el-input v-model="formData.asset_apply_no" clearable placeholder="请输入资产申请单号" />
                        </el-form-item> </el-col>
                    <el-col :span="24">
                        <el-form-item label="付款方式" prop="pay_type" :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-radio-group v-model="formData.pay_type" placeholder="请选择付款方式">
                                <el-radio v-for="(item, index) in dictData.pay_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="start_date" :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-date-picker class="flex-1 !flex" v-model="formData.start_date" clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择签订日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="结束日期" prop="end_date" :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-date-picker class="flex-1 !flex" v-model="formData.end_date" clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择签订日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="签约日期" prop="signing_date">
                            <el-date-picker class="flex-1 !flex" v-model="formData.signing_date" clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择签订日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="合同金额" prop="amount" :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-input v-model="formData.amount" clearable placeholder="请输入合同金额" @input="amountinput" />
                        </el-form-item> </el-col>
                    <el-col :span="8">
                        <el-form-item label="合同金额大写" prop="amount_daxie" :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-input v-model="formData.amount_daxie" disabled clearable placeholder="系统自动填写" />
                        </el-form-item> </el-col>
                    <el-col :span="24">
                        <el-form-item label="合同主要条款" prop="main_content">
                            <el-input v-model="formData.main_content" clearable placeholder="请输入合同主要条款" />
                        </el-form-item> </el-col>
                    <el-col :span="24">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="formData.remark" 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-row>


            </el-form>
        </popup>

        <el-dialog v-model="showDialog" title="选择供应商" width="70%">
            <supplierTable @customEvent="customEvent"></supplierTable>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup name="procurementContractEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { toChinesNum } from "@/utils/util";
import supplierTable from '@/components/supplier/index.vue'
import { apiadministrativeAdd, apiadministrativeEdit, apiadministrativeDetail } from '@/api/administrative'
import { timeFormat } from '@/utils/util'
import type { PropType } from 'vue'
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 showDialog = ref(false)
const showDialog1 = ref(false)
const supplier_contract_name = ref('')
const supplier_contract_no = ref('')
const formDataannex = reactive([])
const tableData = reactive([])
const list1 = reactive([])
const list2 = reactive([])
import { deptAll } from '@/api/org/department'
import { getAll } from '@/api/org/organization'
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 amountinput = (e) => {
    // console.log(e)
    if (e && e > 0) {
        formData.amount_daxie = toChinesNum(e)
    }
}

//获取所有组织
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 popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑行政合同' : '新增行政合同'
})

// 表单数据
const formData = reactive({
    id: '',
    dept_id: '',
    org_id: '',
    supplier_id: 0,
    contract_no: "",
    contract_name: "",
    procurement_type: 0,
    asset_apply_no: "",
    start_date: "",
    end_date: "",
    signing_date: "",
    pay_type: '',
    amount: '',
    amount_daxie: "",
    main_content: "",
    remark: "",
    annex: ""
})
const customEvent = (e: any) => {
    supplier_contract_name.value = e.supplier_name
    formData.supplier_id = e.id
    supplier_contract_no.value = e.supplier_code
    showDialog.value = false;

};

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

})


// 获取详情
const setFormData = async (data: Record<any, any>) => {
    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.dept_id) {
        getlist1(data.org_id)
    }
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
    if (data.amount_daxie) {
        amountinput(data.amount_daxie)
    }
    //@ts-ignore
    formData.signing_date = timeFormat(formData.signing_date, 'yyyy-mm-dd hh:MM:ss')
}

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


// 提交按钮
const handleSubmit = async () => {
    if (formDataannex.length > 0) {
        formData.annex = JSON.stringify(formDataannex.map((item) => item.uri))
    }
    await formRef.value?.validate()
    const data = { ...formData, }
    mode.value == 'edit'
        ? await apiadministrativeEdit(data)
        : await apiadministrativeAdd(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>
