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

        <popup ref="popupRef" :title="popupTitle" :async="true" width="80%" @confirm="handleSubmit" @close="handleClose">
            <el-steps :active="active" align-center style="margin-bottom: 20px;">
                <el-step title="提交申请" description="Some description" />
                <el-step title="领导审核" description="Some description" />

            </el-steps>
            <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-form ref="formRef" :model="formData" label-width="auto" :rules="formRules">
                <el-row :gutter="10">


                    <el-col :span="8">
                        <el-form-item label="资产序列号" prop="contract_id">
                            <el-input v-model="project_name" clearable readonly placeholder="点击选择[空闲]状态的资产" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="资产编号" prop="contract_id">
                            <el-input v-model="project_name" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="资产名称" prop="contract_id">
                            <el-input v-model="project_name" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="规格型号" prop="contract_id">
                            <el-input v-model="project_name" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="资产类别" prop="contract_id">
                            <el-input v-model="project_name" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="计量单位" prop="contract_id">
                            <el-input v-model="project_name" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="生产厂家" prop="contract_id">
                            <el-input v-model="project_name" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="资产来源" prop="contract_id">
                            <el-input v-model="project_name" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="预计使用寿命" prop="contract_id">
                            <el-input v-model="project_name" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="存放地址" prop="contract_id">
                            <el-input v-model="project_name" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="出厂日期" prop="invoicing_date"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">

                            <el-date-picker class="flex-1 !flex" v-model="formData.invoicing_date" clearable type="date"
                                value-format="YYYY-MM-DD" placeholder="选择出厂日期">
                            </el-date-picker>

                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="购入日期" prop="invoicing_date"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">

                            <el-date-picker class="flex-1 !flex" v-model="formData.invoicing_date" clearable type="date"
                                value-format="YYYY-MM-DD" placeholder="选择购入日期">
                            </el-date-picker>

                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="处置日期" prop="invoicing_date"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">

                            <el-date-picker class="flex-1 !flex" v-model="formData.invoicing_date" clearable type="date"
                                value-format="YYYY-MM-DD" placeholder="选择处置日期">
                            </el-date-picker>

                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="处置方式" prop="remark">
                            <el-input v-model="formData.remark" type="textarea" clearable placeholder="请输入处置方式" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="处置金额" prop="remark">
                            <el-input v-model="formData.remark" type="textarea" clearable placeholder="请输入处置金额" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="处置原因" prop="remark">
                            <el-input v-model="formData.remark" type="textarea" clearable placeholder="请输入处置原因" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="24">
                        <!-- <el-form-item label="附件" prop="annex">
                            <el-input v-model="formData.annex" clearable placeholder="请输入附件" />
                        </el-form-item> -->
                        <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-dialog v-model="showDialog1" title="选择项目" width="70%">
                    <projectDialog @customEvent="customEvent1" contract_type="2"></projectDialog>
                </el-dialog>
            </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 { toChinesNum } from "@/utils/util";
import projectDialog from '@/components/project/index.vue'
import { apiinvoiceapplyAdd, apiinvoiceapplyEdit, apiinvoiceapplyDetail } from '@/api/InvoicingRequests'
import { getAllProjectTypes } from '@/api/projecttype'
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 active = ref(0)
const formDataannex = reactive([])
const contract_name = ref('')
const project_name = ref('')
const project_code = ref('')
const project_amount = ref('')
const contract_no = ref('')
const custom_name = ref('')
const list1 = reactive([])
const list2 = reactive([])
import { deptAll } from '@/api/org/department'
import { getAll } from '@/api/org/organization'
const next = () => {
    if (active.value++ > 3) active.value = 0
}
// 上传文件
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 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 delFileFn = (index: number) => {
    formDataannex.splice(index, 1)
}
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 customEvent = (e: any) => {
    formData.customer_id = e.id;
    custom_name.value = e.name;
    showDialog.value = false;
};
const customEvent1 = (e: any) => {
    formData.contract_id = e.id;
    project_name.value = e.project_name;
    project_code.value = e.project_code;
    contract_name.value = e.contract_name;
    contract_no.value = e.contract_code
    project_amount.value = e.amount

    showDialog1.value = false;
};
// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑资产处置表' : '新增资产处置表'
})

// 表单数据
const formData = reactive({
    id: '',
    customer_id: '',
    contract_id: '',
    approve_id: '',
    invoicing_date: "",
    period: "",
    accumulate_amount: '',
    accumulated_payments_received: '',
    tax_rate: "",
    invoice_type: '',
    invoicing_amount: '',
    invoicing_amount_daxie: "",
    tax: '',
    amount_including_tax: '',
    content: "",
    invoice_no: "",
    remark: "",
    annex: [],
    invoicing_company_name: "",
    taxpayer_identification_number: "",
    deposit_bank: "",
    bank_accnout: "",
    address_phone: "",
    receiving_address: "",
    contacts: "",
    phone: "",
    mailing_time: "",
    mailing_type: "",
    mailing_no: ""
})


// 表单验证
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 (formData.invoicing_amount) {
        toChinesNum(formData.invoicing_amount)
    }
    custom_name.value = data.custom.name
    project_name.value = data.contract_name;
    project_code.value = data.contract_code
    project_amount.value = data.contract.amount
    contract_name.value = data.contract.contract_name;
    contract_no.value = data.contract.contract_code


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


// 提交按钮
const handleSubmit = async () => {
    if (formDataannex.length > 0) {
        formData.annex = formDataannex.map((item: any) => item.uri)
    }

    console.log(formRef.value?.validate(), '22222222')
    await formRef.value?.validate()


    const data = { ...formData }
    mode.value == 'edit'
        ? await apiinvoiceapplyEdit(data)
        : await apiinvoiceapplyAdd(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>
