<template>
    <div class="edit-popup">
        <popup ref="popupRef" :title="popupTitle" :async="true" width="80vw" @confirm="handleSubmit" @close="handleClose">
            <el-form ref="formRef" :model="formData" label-width="120px" :rules="formRules">
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="单据编号">
                            <el-input v-model="formData.code" clearable placeholder="系统自动生成" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="审批部门" prop="approve_dept">
                            <el-select v-model="formData.approve_dept" placeholder="请选择部门" class="flex-1">
                                <el-option :label="item.name" :value="item.id" v-for="item in deptList">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="费用类别" prop="cost_type">
                            <el-select v-model="formData.cost_type" placeholder="请选择费用类别" class="flex-1">
                                <el-option :label="item.name" :value="parseInt(item.value)"
                                    v-for="item in dictData.cost_type">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="支付方式" prop="pay_type">
                            <el-select v-model="formData.pay_type" placeholder="请选择支付方式" class="flex-1">
                                <el-option :label="item.name" :value="parseInt(item.value)"
                                    v-for="item in dictData.financial_pay_type">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="付款原因" prop="pay_reason">
                            <el-input v-model="formData.pay_reason" clearable placeholder="请输入付款原因" type="textarea" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="支出合同">
                            <el-input v-model="formData.contract_name" clearable placeholder="点击选择合同"
                                @click="showDialog = true" readonly />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="已支付金额">
                            <el-input v-model="formData.has_pay_amount" clearable placeholder="请输入已支付金额" type="number" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="本次支付金额">
                            <el-input v-model="formData.this_pay_amount" clearable placeholder="请输入本次支付金额" type="number" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="付往单位" prop="accept_company">
                            <el-input v-model="formData.accept_company" clearable placeholder="请输入付往单位" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="收款账号" prop="accept_acount">
                            <el-input v-model="formData.accept_acount" clearable placeholder="请输入收款账号" type="number" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="开户省份" prop="province">
                            <el-select v-model="formData.province" clearable placeholder="请选择开户省份" @change="province_change"
                                class="flex-1">
                                <el-option v-for="(item, index) in datas.provinceOptions" :key="index"
                                    :label="item.province_name" :value="(item.province_code)" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="开户城市" prop="city">
                            <el-select v-model="formData.city" clearable placeholder="请选择开户城市" class="flex-1">
                                <el-option v-for="(item, index) in datas.cityOptions" :key="index" :label="item.city_name"
                                    :value="(item.city_code)" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="收款银行" prop="accept_bank">
                            <el-input v-model="formData.accept_bank" clearable placeholder="请输入收款银行" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="收款开户行" prop="accept_deposit">
                            <el-input v-model="formData.accept_deposit" clearable placeholder="请输入收款开户行" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="附单据张数">
                            <el-input v-model="formData.bill_num" clearable placeholder="请输入附单据张数" type="number" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="事由" prop="content">
                            <el-input v-model="formData.content" clearable placeholder="请输入事由" type="textarea" />
                        </el-form-item>
                    </el-col>
                    <createUserLable :formData="formData" name="申请" flag></createUserLable>

                </el-row>
                <FormTable :form-data="formData.detail" :config="tableConfig" @getSummaries="getSummaries"
                    :dict-data="dictData">
                    <el-table-column label="部门">
                        <template #default="{ row }">
                            <el-form-item label-width="0">
                                <el-select v-model="row.dept_id" placeholder="请选择部门">
                                    <el-option :label="item.name" :value="item.id" v-for="item in deptList">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </template>
                    </el-table-column>
                </FormTable>

            </el-form>
            <el-dialog v-model="showDialog" title="选择合同" width="70%">
                <dialogTable :config="cost_approved_projects" @customEvent="customEvent" :query="{ status: 1 }">
                </dialogTable>
            </el-dialog>
        </popup>
    </div>
</template>

<script lang="ts" setup name="financialUsingFundsEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiFinancialUsingFundsAdd, apiFinancialUsingFundsEdit, apiFinancialUsingFundsDetail, apiFinancialUsingFundsDetailDelete, apiFinancialUsingFundsDetailLists } from '@/api/financial_using_funds'
import { timeFormat } from '@/utils/util'
import type { PropType } from 'vue'
import { deptLists } from "@/api/org/department"
import { cost_approved_projects } from "@/components/dialogTable/dialogTableConfig";
import { apiCityList, apiProvinceList } from "@/api/common";


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 datas = reactive({
    provinceOptions: [],
    cityOptions: [],
});


const getProvinceList = async () => {
    const data = await apiProvinceList({});
    datas["provinceOptions"] = data;
};
const getCityList = async () => {
    const data = await apiCityList({ province_code: formData.province });
    datas["cityOptions"] = data;
};

//获取省份
function province_change(value: string) {
    getCityList();
}
getProvinceList();


// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑财务管理--用款申请单' : '新增财务管理--用款申请单'
})

// 表单数据
const formData = reactive({
    id: '',
    code: '',
    approve_dept: '',
    cost_type: '',
    pay_type: '',
    pay_reason: '',
    contract_id: '',
    contract_name: "",
    has_pay_amount: '',
    this_pay_amount: '',
    accept_company: '',
    accept_acount: '',
    province: '',
    city: '',
    accept_bank: '',
    accept_deposit: '',
    bill_num: '',
    content: '',
    create_user: '',
    create_time: '',
    annex: [],
    "detail": [
    ]
})

const tableConfig = reactive(
    {
        title: "用款申请明细",
        tableConfig: [
            {
                label: "发生日期",
                value: 'date',
                date: true

            },
            {
                label: "科目名称",
                value: 'subject_name',
                select: 'subject_category'
            },
            {
                label: "金额 ",
                value: 'amount',
                type: 'number'

            },
            {
                label: "摘要",
                value: 'abstract',

            },
            {
                label: "关联发票",
                value: 'invoice',
                type: 'number'

            },

        ],
        deleteApi: apiFinancialUsingFundsDetailDelete,
    }
)

const customEvent = (e) => {
    formData.contract_id = e.id
    formData.contract_name = e.contract_name
    // formData.contract_type = e.contract_type
    // formData.part_a = e.part_a
    // formData.part_b = e.part_b
    // formData.sign_money = e.money
    // formData.sign_time = e.sign_date
    // formData.total_invoice_amount = e.total_invoice_amount
    // formData.total_refund_amount = e.total_refund_amount
    showDialog.value = false
}



// 表单验证
const formRules = reactive<any>({
    code: [{
        required: true,
        message: '请输入单据编号',
        trigger: ['blur']
    }],
    approve_dept: [{
        required: true,
        message: '请输入审批部门',
        trigger: ['blur']
    }],
    cost_type: [{
        required: true,
        message: '请输入费用类别',
        trigger: ['blur']
    }],
    pay_type: [{
        required: true,
        message: '请输入支付方式',
        trigger: ['blur']
    }],
    pay_reason: [{
        required: true,
        message: '请输入付款原因',
        trigger: ['blur']
    }],
    contract_id: [{
        required: true,
        message: '请输入支出合同',
        trigger: ['blur']
    }],
    has_pay_amount: [{
        required: true,
        message: '请输入已支付金额',
        trigger: ['blur']
    }],
    this_pay_amount: [{
        required: true,
        message: '请输入本次支付金额',
        trigger: ['blur']
    }],
    accept_company: [{
        required: true,
        message: '请输入付往单位',
        trigger: ['blur']
    }],
    accept_acount: [{
        required: true,
        message: '请输入收款账号',
        trigger: ['blur']
    }],
    province: [{
        required: true,
        message: '请输入开户省份',
        trigger: ['blur']
    }],
    city: [{
        required: true,
        message: '请输入开户城市',
        trigger: ['blur']
    }],
    accept_bank: [{
        required: true,
        message: '请输入收款银行',
        trigger: ['blur']
    }],
    accept_deposit: [{
        required: true,
        message: '请输入收款开户行',
        trigger: ['blur']
    }],
    bill_num: [{
        required: true,
        message: '请输入附单据张数',
        trigger: ['blur']
    }],
    content: [{
        required: true,
        message: '请输入事由',
        trigger: ['blur']
    }],
    create_user: [{
        required: true,
        message: '请输入申请人',
        trigger: ['blur']
    }],
    create_time: [{
        required: true,
        message: '请输入申请日期',
        trigger: ['blur']
    }]
})


// 获取详情
const setFormData = async (data: Record<any, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
    let res = await apiFinancialUsingFundsDetailLists({ using_funds_id: data.id })
    formData.detail = res.lists
    getCityList()

}

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


// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate()
    const data = { ...formData, }
    mode.value == 'edit'
        ? await apiFinancialUsingFundsEdit(data)
        : await apiFinancialUsingFundsAdd(data)
    popupRef.value?.close()
    emit('success')
}

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

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

const deptList = ref([])
const getDeptList = async () => {
    let res = await deptLists()
    deptList.value = res.lists
}


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