<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-form-item label="项目名称" prop="project_id" @click="showDialog = true"
                    :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                    <el-input v-model="project_name" clearable placeholder="请输入项目id" />
                </el-form-item>
                <el-form-item label="项目编码">
                    <el-input v-model="project_code" clearable disabled placeholder="系统自动填写" />
                </el-form-item>
                <el-form-item label="合同名称" prop="contract_id" @click="showDialog1 = true">
                    <el-input v-model="formData.contract_name" clearable readonly placeholder="系统自动填写" />
                </el-form-item>
                <el-form-item label="合同编号" prop="contract_code">
                    <el-input v-model="formData.contract_code" clearable disabled placeholder="系统自动填写" />
                </el-form-item>
                <!-- <el-form-item label="客户名称" prop="custom_name">
                    <el-input v-model="formData.custom_name" clearable disabled placeholder="系统自动填写" />
                </el-form-item> -->
                <el-form-item label="结算金额" prop="settlement_amount">
                    <el-input v-model="formData.settlement_amount" clearable placeholder="请输入结算金额" @input="amountinput" />
                </el-form-item>
                <el-form-item label="结算金额大写" prop="settlement_amount_uppercase">
                    <el-input v-model="formData.settlement_amount_uppercase" readonly disabled placeholder="系统自动填写" />
                </el-form-item>
                <el-form-item label="结算差异" prop="remaining_amount">
                    <el-input v-model="formData.remaining_amount" readonly disabled placeholder="系统自动计算" />
                </el-form-item>
                <el-form-item label="结算日期" prop="settlement_date">
                    <el-date-picker class="flex-1 !flex" v-model="formData.settlement_date" clearable type="date"
                        value-format="YYYY-MM-DD" placeholder="选择结算日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="formData.remark" type="textarea" 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-form>
        </popup>
        <el-dialog v-model="showDialog" title="选择项目" width="70%">
            <projectTable @customEvent="customEvent"></projectTable>
        </el-dialog>
        <div v-if="showDialog1">
            <el-dialog v-model="showDialog1" title="选择合同" width="70%">
                <contractTable @customEvent="customEvent1" :project_id="formData.project_id"></contractTable>
            </el-dialog>
        </div>

    </div>
</template>

<script lang="ts" setup name="customerDemandEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { deptAll } from '@/api/org/department'
import { getAll } from '@/api/org/organization'
import projectTable from "@/components/project/index.vue"
import contractTable from "@/components/contract/index.vue"
import { apiprojectsettlementAdd, apiprojectsettlementEdit, apiprojectsettlementDetail } from '@/api/project_settlement'
import { timeFormat, toChinesNum } 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 orglist = reactive([])
const jobs = reactive([])
const project_name = ref('')
const project_code = ref('')
const custom_name
    = ref('')
const formDataannex = reactive([])
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) {
        ElMessage.error(response.msg);
        return;
    }
    formDataannex.push(
        { uri: response.data.uri, name: response.data.name }

    );
};
// 删除上传的文件
const delFileFn = (index: number) => {
    formDataannex.splice(index, 1)
}
// dialog
const showDialog = ref(false)
const showDialog1 = ref(false)
const customEvent = (e: any) => {
    formData.project_id = e.id;
    project_name.value = e.name;
    project_code
        .value = e.project_code;
    custom_name
        .value = e.custom_name;
    showDialog.value = false;
};
const customEvent1 = (e: any) => {
    formData.contract_id = e.id
    formData.contract_name = e.contract_name
    formData.contract_code = e.contract_code
    showDialog1.value = false
    // formData.custom_name=e

    // formData.project_id = e.id;
    // project_name.value = e.name;
    // project_code
    //     .value = e.project_code;
    // custom_name
    //     .value = e.custom_name;
    // showDialog.value = false;
};

const getlista = () => {
    getAll().then((res) => {
        // orglist = res.data

        Object.assign(orglist, res)

    })
}

const area_change = (e: any) => {
    formData.org_id = e
    let data = { 'org_id': e }
    // console.log(data)
    deptAll(data).then((res) => {

        Object.assign(jobs, res)

    })
}
// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑甲方结算' : '新增甲方结算'
})

// 表单数据
const formData = reactive({
    id: '',
    org_id: '',
    dept_id: '',
    project_id: '',
    contract_id: '',
    settlement_amount: '',
    settlement_amount_uppercase: '',
    remaining_amount: '',
    settlement_date: '',
    remark: '',
    annex: [],
})
const checkPhone = (rule: any, value: any, callback: (arg0: Error) => any) => {
    const phoneReg = /^1[3|4|5|7|8][0-9]{9}$/
    // if (!value) {
    //     return callback(new Error('电话号码不能为空'))
    // }
    if (value) {
        setTimeout(() => {
            if (phoneReg.test(value)) {
                callback()
            } else {
                callback(new Error('电话号码格式不正确'))
            }

        }, 100)
    }

}
//监听输入
const amountinput = (e) => {
    // console.log(e)
    if (e && e > 0) {

        formData.remaining_amount = e
        formData.settlement_amount_uppercase = toChinesNum(e)
    }
}
// 表单验证
const formRules = reactive<any>({

})


// 获取详情
const setFormData = async (data: Record<any, any>) => {
    deptAll({ 'org_id': data.org_id }).then((res) => {
        Object.assign(jobs, res)
    })
    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)
    }
    project_name.value = data.project_name
    custom_name.value = data.custom_name
    project_code.value = data.project_code
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }

    //@ts-ignore
    formData.recording_time = timeFormat(formData.recording_time, 'YYYY-MM-DD ')
}

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


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

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

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


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