<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="140px" :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="custom_id" @click="showDialog = true"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="custom_name" readonly clearable placeholder="请选择客户" :disabled="project" />
                        </el-form-item> </el-col>

                    <el-col :span="8">
                        <el-form-item label="项目名称" prop="project_id" @click="tanchuan"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="project_name" readonly clearable placeholder="请选择项目" :disabled="project" />
                        </el-form-item></el-col>
                    <el-col :span="8">
                        <el-form-item label="项目编码">
                            <el-input v-model="project_code" clearable disabled placeholder="系统自动填写" />
                        </el-form-item></el-col>
                    <el-col :span="8">
                        <el-form-item label="投标编号" prop="buy_bidding_document_id" @click="showDialog1 = true">
                            <el-input v-model="bidding_code" readonly clearable placeholder="请选择投标编号" />
                        </el-form-item></el-col>
                    <el-col :span="8">
                        <el-form-item label="合同名称" prop="contract_name"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="formData.contract_name" clearable placeholder="请输入合同名称" />
                        </el-form-item></el-col>
                    <el-col :span="8">
                        <el-form-item label="合同类型" prop="contract_type"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-select class="flex-1" v-model="formData.contract_type" clearable placeholder="请选择合同类型">
                                <el-option v-for="(item, index) in dictData.contract_type" :key="index" :label="item.name"
                                    :value="parseInt(item.value)" />
                            </el-select>
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="合同计价方式" prop="contract_pricing_method"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-select class="flex-1" v-model="formData.contract_pricing_method" clearable
                                placeholder="请选择合同计价方式">
                                <el-option v-for="(item, index) in dictData.contract_pricing_method" :key="index"
                                    :label="item.name" :value="parseInt(item.value)" />
                            </el-select>
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="甲方" prop="party_a"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="formData.party_a" clearable placeholder="请输入甲方" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="甲方通讯地址" prop="party_a_contact_address">
                            <el-input v-model="formData.party_a_contact_address" clearable placeholder="请输入甲方通讯地址" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="甲方主要负责人" prop="party_a_diretor">
                            <el-input v-model="formData.party_a_diretor" clearable placeholder="请输入甲方主要负责人" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="甲方电话" prop="party_a_phone"
                            :rules="[{ validator: checkPhone, trigger: 'blur' }]">
                            <el-input v-model="formData.party_a_phone" clearable placeholder="请输入甲方电话" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="甲方手机" prop="party_a_mobile">
                            <el-input v-model="formData.party_a_mobile" clearable placeholder="请输入甲方手机" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="甲方邮箱" prop="party_a_email"
                            :rules="[{ validator: userEmail, trigger: 'blur' }]">
                            <el-input v-model="formData.party_a_email" clearable placeholder="请输入甲方邮箱" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="乙方" prop="party_b"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="formData.party_b" clearable placeholder="请输入乙方" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="乙方通讯地址" prop="party_b_contact_address">
                            <el-input v-model="formData.party_b_contact_address" clearable placeholder="请输入乙方通讯地址" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="乙方主要负责人" prop="party_b_diretor">
                            <el-input v-model="formData.party_b_diretor" clearable placeholder="请输入乙方主要负责人" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="乙方电话" prop="party_b_phone"
                            :rules="[{ validator: checkPhone, trigger: 'blur' }]">
                            <el-input v-model="formData.party_b_phone" clearable placeholder="请输入乙方电话" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="乙方手机" prop="party_b_mobile">
                            <el-input v-model="formData.party_b_mobile" clearable placeholder="请输入乙方手机" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="乙方邮箱" prop="party_b_email"
                            :rules="[{ validator: userEmail, trigger: 'blur' }]">
                            <el-input v-model="formData.party_b_email" clearable placeholder="请输入乙方邮箱" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="金额" prop="amount"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <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">
                            <el-input v-model="amount_daxie" disabled clearable placeholder="系统自动填写" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="业务负责人" prop="business_director" @click="userclick"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-input v-model="business_director_name" readonly clearable placeholder="请输入业务负责人" />
                        </el-form-item></el-col>
                    <el-col :span="24">

                        <el-form-item label="合同状态" prop="contract_status"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-radio-group v-model="formData.contract_status" placeholder="请选择合同状态">
                                <el-radio v-for="(item, index) in dictData.contract_status" :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="expire"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-date-picker class="flex-1 !flex" v-model="formData.expire" 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="contract_date"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-date-picker class="flex-1 !flex" v-model="formData.contract_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="main_content">
                            <el-input v-model="formData.main_content" clearable placeholder="请输入主要条款" />
                        </el-form-item></el-col><el-col :span="8">
                        <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>
                <div style="margin-bottom: 30px;">回款计划</div>
                <div style="margin-bottom: 30px;">
                    <el-table :data="paymentList">
                        <el-table-column label="序号">
                            <template #default="{ row }">
                                <el-button @click="handleAdd(row)">+</el-button>
                                <el-button @click="handleDelete(row)">-</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.value" />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column label="计划回款日期" prop="return_date">
                            <template #default="{ row }">
                                <el-date-picker v-model="row.return_date" clearable type="date" value-format="YYYY-MM-DD"
                                    placeholder="选择签订日期">
                                </el-date-picker>
                            </template></el-table-column>
                        <el-table-column label="金额" prop="amount">
                            <template #default="{ row }"> <el-input v-model="row.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>
            <el-dialog v-model="showDialog" title="选择客户" width="70%">
                <customDialog @customEvent="customEvent"></customDialog>
            </el-dialog>
            <div v-if="showDialog1">
                <el-dialog v-model="showDialog1" title="选择标书" width="70%">
                    <biddocumentTable @customEvent="customEvent1" :project_id="project_id"></biddocumentTable>
                </el-dialog>
            </div>
            <div v-if="showDialog2">
                <el-dialog v-model="showDialog2" title="选择项目" width="70%">
                    <projectTable @customEvent="customEvent2" :custom_id="formData.custom_id"></projectTable>
                </el-dialog>
            </div>
            <personnelselector ref="personnel" @confirm="submituser" type="1"></personnelselector>
            <!-- <reviewprocess /> -->
        </popup>

    </div>
</template>

<script lang="ts" setup name="contractEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import biddocumentTable from "@/components/biddocument/index.vue"
import projectTable from "@/components/project/index.vue"
import personnelselector from '@/components/personnelselector/index.vue'
import { apiContractAdd, apiContractEdit, apiContractDetail } from '@/api/contract'
import { apireturnedLists } from "@/api/remittance.ts"
import { useDictData } from '@/hooks/useDictOptions'

let props = defineProps({
    project: Object
})
const { dictData } = useDictData('contract_type,contract_pricing_method,contract_status,pay_period')

const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const formDataannex = reactive([])
import configs from "@/config"
const base_url = configs.baseUrl + configs.urlPrefix
import useUserStore from "@/stores/modules/user";
import { toChinesNum } from "@/utils/util";
const showDialog = ref(false)
const showDialog1 = ref(false)
const showDialog2 = ref(false)
const custom_name = ref('')
const project_name = ref('')
const project_code = ref('')
const bidding_code = ref('')
const amount_daxie = ref('')
const project_id = ref('')
const business_director_name = ref('')
const list1 = reactive([])
const list2 = reactive([])
const paymentList = reactive([{}])
const personnel = ref<any>()
import { deptAll } from '@/api/org/department'
import { getAll } from '@/api/org/organization'
import feedback from '@/utils/feedback'
const userStore = useUserStore();
//验证
const checkPhone = (rule: any, value: any, callback: (arg0: Error) => any) => {

    if (value && !/^1\d{10}$/.test(value)) {
        callback(new Error('请输入正确的手机号码'));
    } else {
        callback()
    }

}
const userEmail = (rule: any, value: string, callback: (arg0: Error | undefined) => void) => {
    const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
    if (value && !mailReg.test(value)) {
        callback(new Error('请输入正确的邮箱格式'))
    } else {
        callback()
    }

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

const handleDelete = (row: any) => {
    // 删除 row
    const index = paymentList.indexOf(row);
    paymentList.splice(index, 1);
};
// 上传文件
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: '',
    dept_id: '',
    org_id: '',
    approve_id: 1,
    custom_id: '',
    buy_bidding_document_id: '',
    contract_name: '',
    contract_code: '',
    contract_type: '',
    contract_pricing_method: '',
    party_a: '',
    party_a_contact_address: '',
    party_a_diretor: '',
    party_a_phone: '',
    party_a_mobile: '',
    party_a_email: '',
    project_id: "",
    party_b: '',
    party_b_contact_address: '',
    party_b_diretor: '',
    party_b_phone: '',
    party_b_mobile: '',
    party_b_email: '',
    amount: '',
    returned_money: [],
    business_director: '',
    contract_status: '',
    expire: '',
    contract_date: '',
    main_content: '',
    remark: '',
    annex: [],
})

//打开弹窗

const userclick = () => {
    personnel.value.open()

}
//确认
const submituser = (e: any) => {
    formData.business_director = e.id;
    business_director_name.value = e.name;
}
//获取值打开弹窗
const tanchuan = () => {
    if (formData.custom_id) {
        showDialog2.value = true
    } else {
        feedback.msgError('请先选择客户')
    }
}


//获取值
const customEvent = (e: any) => {
    formData.custom_id = e.id;
    custom_name.value = e.name;
    bidding_code.value = ''
    project_name.value = ''
    project_code.value = ''
    showDialog.value = false;
};
const customEvent1 = (e: any) => {
    formData.buy_bidding_document_id = e.id;
    bidding_code.value = e.bid_document_no
    showDialog1.value = false;
};

const customEvent2 = (e: any) => {
    project_id.value = e.id;
    formData.project_id = e.id;
    project_name.value = e.name;
    project_code.value = e.project_code;
    bidding_code.value = '';
    showDialog2.value = false;
};


if (props.project) {
    formData.custom_id = props.project.custom_id;
    custom_name.value = props.project.custom_name;
    project_id.value = props.project.id;
    formData.project_id = props.project.id;
    project_name.value = props.project.name;
    project_code.value = props.project.project_code;
}



//监听输入 金额大写
const amountinput = (e) => {
    // console.log(e)
    if (e && e > 0) {
        amount_daxie.value = 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 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) {
        amountinput(data.amount)
    }
    custom_name.value = data.custom_name
    project_name.value = data.project_name
    project_code.value = data.project_code
    bidding_code.value = data.bid_document_no
    business_director_name.value = data.business_director_name
    let res = await apireturnedLists({ contract_id: data.id })
    paymentList.splice(0, 9999)
    res.lists.forEach((item: any) => {
        paymentList.push(item)
    })


}

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


// 提交按钮
const handleSubmit = async () => {
    if (formDataannex.length > 0) {
        formData.annex = formDataannex.map((item) => item.uri)
    }
    if (paymentList.length > 0) {
        formData.returned_money = paymentList.map((item) => ({
            'id': item.id,
            'period': item.period,
            'remark': item.remark,
            'amount': item.amount,
            'return_date': item.return_date,
        }))
    }
    await formRef.value?.validate()
    const data = { ...formData, }
    mode.value == 'edit'
        ? await apiContractEdit(data)
        : await apiContractAdd(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>
