<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="120px" :rules="formRules" inline>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="项目编码" prop="project_id">
                            <el-input v-model="project_code" clearable placeholder="请输入项目编码" @click="showDialog = true"
                                :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]" />
                        </el-form-item> </el-col>
                    <el-col :span="8">
                        <el-form-item label="项目名称" prop="project_id">
                            <el-input v-model="project_name" clearable placeholder="请输入项目名称" />
                        </el-form-item> </el-col>



                    <el-col :span="8">
                        <el-form-item label="年份" prop="insurance_date">
                            <el-date-picker class="flex-1 !flex" v-model="formData.insurance_date" clearable type="year"
                                value-format="YYYY" placeholder="选择年份">
                            </el-date-picker>
                        </el-form-item> </el-col>
                    <el-col :span="8">
                        <el-form-item label="月份" prop="insurance_date">
                            <el-date-picker class="flex-1 !flex" v-model="formData.insurance_date" clearable type="month"
                                value-format="MM" placeholder="选择月份">
                            </el-date-picker>
                        </el-form-item> </el-col>
                    <el-col :span="8">
                        <el-form-item label="产值合计" prop="insurance">
                            <el-input v-model="formData.insurance" clearable type="number" @input="amountinput"
                                placeholder="请输入产值合计" />
                        </el-form-item> </el-col>
                    <el-col :span="8">
                        <el-form-item label="回款计划比例（%）" prop="amount_daxie">
                            <el-input v-model="formData.amount_daxie" clearable disabled placeholder="请输入回款计划比例（%）" />
                        </el-form-item> </el-col>
                    <el-col :span="8">
                        <el-form-item label="计划回款日期" prop="insurance_date">
                            <el-date-picker class="flex-1 !flex" v-model="formData.insurance_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="insurance_date">
                            <el-switch v-model="value3" inline-prompt active-text="是" inactive-text="否" />
                        </el-form-item> </el-col>

                    <el-col :span="8">
                        <el-form-item label="回款负责人" prop="handler">
                            <el-input v-model="formData.handler" clearable placeholder="请输入回款负责人" />
                        </el-form-item> </el-col>
                    <el-col :span="8">
                        <el-form-item label="备注" prop="handler">
                            <el-input v-model="formData.handler" 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>
                <div style="margin-bottom: 30px;">产值明细</div>

                <div style="margin-bottom: 30px;">
                    <el-table :data="formData.pay_plan">
                        <el-table-column label="序号">
                            <template #default="{ row }">

                                <el-button @click="handleAdd(row)" size="small">+</el-button>
                                <el-button @click="handleDelete(row)" size="small">-</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column label="合同编号" prop="name1">
                            <template #default="{ row }">
                                <el-select v-model="row.period" clearable placeholder="请选择期次">
                                    <el-option v-for="(item, index) in dictData.pay_period " :key="index" :label="item.name"
                                        :value="item.id" />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column label="分部工程" prop="pay_date">
                            <template #default="{ row }">
                                <el-date-picker v-model="row.pay_date" clearable value-format="YYYY-MM-DD "
                                    placeholder="选择签订日期">
                                </el-date-picker>
                            </template></el-table-column>
                        <el-table-column label="子分部工程" prop="pay_amount">
                            <template #default="{ row }"> <el-input v-model="row.pay_amount" />
                            </template></el-table-column>

                        <el-table-column label="总收入" prop="pay_amount">
                            <template #default="{ row }"> <el-input v-model="row.pay_amount" />
                            </template></el-table-column>

                        <el-table-column label="分项工程" prop="pay_amount">
                            <template #default="{ row }"> <el-input v-model="row.pay_amount" />
                            </template></el-table-column>

                        <el-table-column label="子目名称" prop="pay_amount">
                            <template #default="{ row }"> <el-input v-model="row.pay_amount" />
                            </template></el-table-column>

                        <el-table-column label="单位" prop="pay_amount">
                            <template #default="{ row }"> <el-input v-model="row.pay_amount" />
                            </template></el-table-column>

                        <el-table-column label="合同量" prop="pay_amount">
                            <template #default="{ row }"> <el-input v-model="row.pay_amount" />
                            </template></el-table-column>


                        <el-table-column label="已完工量" prop="pay_amount">
                            <template #default="{ row }"> <el-input v-model="row.pay_amount" />
                            </template></el-table-column>


                        <el-table-column label="本月完工量" prop="pay_amount">
                            <template #default="{ row }"> <el-input v-model="row.pay_amount" />
                            </template></el-table-column>


                        <el-table-column label="本月产值" prop="pay_amount">
                            <template #default="{ row }"> <el-input v-model="row.pay_amount" />
                            </template></el-table-column>


                        <el-table-column label="进度(%)" prop="pay_amount">
                            <template #default="{ row }"> <el-input v-model="row.pay_amount" />
                            </template></el-table-column>



                        <el-table-column label="备注" prop="remark">
                            <template #default="{ row }">
                                <el-input v-model="row.remark" />
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </el-form>
        </popup>
        <el-dialog v-model="showDialog" title="选择项目" width="70%">
            <projectDialog @customEvent="customEvent"></projectDialog>
        </el-dialog>
        <div v-if="showDialog1">
            <el-dialog v-model="showDialog1" title="选择项目人员" width="70%">
                <customDialog @customEvent="customEvent1" :project_id="formData.project_id"></customDialog>
            </el-dialog>
        </div>

    </div>
</template>

<script lang="ts" setup name="procurementContractEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import projectDialog from '@/components/project/index.vue'
import { toChinesNum } from "@/utils/util";
import { insurancemanagementAdd, insurancemanagementEdit, insurancemanagementDetail } from '@/api/project_insurance_management'
import customDialog from '@/components/project_personnel/index.vue'
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 project_name = ref('')
const project_code = ref('')
const person_name = ref('')
const idcard = ref('')

import configs from "@/config"
import useUserStore from "@/stores/modules/user";
const base_url = configs.baseUrl + configs.urlPrefix
const userStore = useUserStore();
const formDataannex = reactive([])
import feedback from '@/utils/feedback'
const userInfo = userStore.userInfo
//获取值
const customEvent = (e) => {
    formData.project_id = e.id
    project_name.value = e.name
    project_code.value = e.project_code
    showDialog.value = false

}
const customEvent1 = (e) => {
    formData.project_person_id = e.id
    idcard.value = e.idcard
    person_name.value = e.name
    showDialog1.value = false

}

const handleAdd = (row: any) => {
    // 在 row 后面插入一行数据
    const index = formData.pay_plan.indexOf(row);
    formData.pay_plan.splice(index + 1, 0, {});
};

const handleDelete = (row: any) => {
    // 删除 row
    const index = formData.pay_plan.indexOf(row);
    formData.pay_plan.splice(index, 1);
};
// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑保险管理' : '新增保险管理'
})
// 上传文件
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)
}
// 表单数据
const formData = reactive({
    id: '',
    project_id: '',
    project_person_id: '',
    insurance_date: '',
    due_date: '',
    type: '',
    insurance_no: '',
    insurance: '',
    insured_amount: '',
    insurance_company: '',
    insurance_detail: '',
    invoice_no: '',
    handler: '',
    amount_daxie: '',
    annex: [],
})


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

})

//监听金额大写输入
const amountinput = (e) => {
    // console.log(e)
    if (e && e > 0) {
        formData.amount_daxie = toChinesNum(e)
    }
}


// 获取详情
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)


    }
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
    project_name.value = data.project_name
    project_code.value = data.project_code
    idcard.value = data.person_idcard
    person_name.value = data.person_name

}

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


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

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

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


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