<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">
                <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="supplier_id" @click="showDialog1 = true"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-input v-model="supplier_name" readonly clearable placeholder="请选择供应商" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="供应商编码" prop="supplier_id"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-input v-model="supplier_code" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="项目名称" prop="project_id" @click="showDialog = true"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-input v-model="project_name" readonly clearable placeholder="请选择项目" />
                        </el-form-item> </el-col>
                    <el-col :span="8">
                        <el-form-item label="项目编码" prop="project_id"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-input v-model="project_code" readonly disabled placeholder="系统自动填写" />
                        </el-form-item> </el-col>
                    <el-col :span="8">
                        <el-form-item label="合同编号" prop="contract_no">
                            <el-input v-model="contract_no" clearable disabled placeholder="系统自动编号" />
                        </el-form-item> </el-col> <el-col :span="8">
                        <el-form-item label="合同名称" prop="supplier_id">
                            <el-input v-model="formData.contract_name" clearable placeholder="请输入合同名称" />
                        </el-form-item> </el-col> <el-col :span="24">
                        <el-form-item label="合同类型" prop="contract_type">
                            <el-radio-group v-model="formData.contract_type" placeholder="请选择合同类型"
                                :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                                <el-radio v-for="(item, index) in dictData.procurement_contract_type" :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="signing_date"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-date-picker class="flex-1 !flex" v-model="formData.signing_date" clearable
                                value-format="YYYY-MM-DD " placeholder="选择签约日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col> <el-col :span="24">
                        <el-form-item label="付款方式" prop="pay_type">
                            <el-radio-group v-model="formData.pay_type" placeholder="请选择付款方式">
                                <el-radio v-for="(item, index) in dictData.pay_type" :key="index"
                                    :label="parseInt(item.value)">
                                    {{ item.name }}
                                </el-radio>
                            </el-radio-group>
                        </el-form-item> </el-col> <el-col :span="24">
                        <el-form-item label="账期" prop="account_period">
                            <el-radio-group v-model="formData.account_period" placeholder="请选择账期">
                                <el-radio v-for="(item, index) in dictData.account_period" :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="amount">
                            <el-input v-model="amount" clearable disabled placeholder="系统自动计算" />
                        </el-form-item> </el-col> <el-col :span="8">
                        <el-form-item label="不含税金额" prop="amount_excluding_tax">
                            <el-input v-model="amount_excluding_tax" disabled clearable placeholder="系统自动计算" />
                        </el-form-item> </el-col> <el-col :span="8">
                        <el-form-item label="金额大写" prop="project_id"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="amount_daxie" clearable disabled placeholder="请输入金额大写" />
                        </el-form-item> </el-col> <el-col :span="8">
                        <el-form-item label="质保金比例" prop="retention_money_rate">
                            <el-input v-model="formData.retention_money_rate" clearable placeholder="请输入质保金比例" />
                        </el-form-item> </el-col>
                    <el-col :span="8">
                        <el-form-item label="质保金" prop="project_id"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="retention_money" disabled 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="8">
                        <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=" display: flex;justify-content: flex-end;margin-bottom: 30px;">
                    <el-button @click="showDialog2 = true" type="primary" :disabled="!formData.project_id"
                        plain>选择采购申请</el-button>
                </div>
                <el-row>
                    <el-col :span="24">
                        <div style="margin-bottom: 30px;">采购合同明细</div>
                        <div style="margin-bottom: 30px;">
                            <el-table :data="materialList">
                                <el-table-column label="序号">
                                    <template #default="{ row }">
                                        <!-- <el-button @click="handleAdd1(row)">+</el-button> -->
                                        <el-button @click="handleDelete1(row)">-</el-button>
                                    </template>
                                </el-table-column>
                                <el-table-column label="采购申请单号" prop="material_purchase_request_code">
                                    <template #default="{ row }">
                                        <el-input v-model="row.material_purchase_request_code" disabled />
                                    </template>
                                </el-table-column>
                                <el-table-column label="材料名称" prop="material_name">
                                    <template #default="{ row }"> <el-input v-model="row.material_name" disabled />
                                    </template></el-table-column>
                                <el-table-column label="材料编码" prop="material_code">
                                    <template #default="{ row }"> <el-input v-model="row.material_code" disabled />
                                    </template></el-table-column>

                                <el-table-column label="规格型号" prop="material_specs">
                                    <template #default="{ row }">
                                        <el-input v-model="row.material_specs" />
                                    </template>
                                </el-table-column>

                                <el-table-column label="品牌" prop="material_brand">
                                    <template #default="{ row }">
                                        <el-input v-model="row.material_brand" disabled />
                                    </template>
                                </el-table-column>
                                <el-table-column label="单位" prop="material_unit">
                                    <template #default="{ row }">
                                        <el-input v-model="row.material_unit" disabled />
                                    </template>
                                </el-table-column>
                                <el-table-column label="数量" prop="num">
                                    <template #default="{ row, $index }">
                                        <el-input v-model="row.num" />
                                    </template>
                                </el-table-column>
                                <el-table-column label="含税单价" prop="price">
                                    <template #default="{ row, $index }">
                                        <el-input v-model="row.price" />
                                    </template>
                                </el-table-column>

                                <el-table-column label="税率(%)" prop="tax_rate">
                                    <template #default="{ row, $index }">
                                        <el-select v-model="row.tax_rate" clearable placeholder="请选择税率" value-key="name">
                                            <el-option v-for="(item, index) in dictData.tax_rate" :key="index"
                                                :label="item.name" :value="item.value" />
                                        </el-select>
                                    </template>
                                </el-table-column>

                                <el-table-column label="不含税金额" prop="amount_excluding_tax">
                                    <template #default="{ row }">
                                        <el-input v-model="row.amount_excluding_tax" prop="num" disabled />
                                    </template>
                                </el-table-column>
                                <el-table-column label="含税金额" prop="amount_including_tax">
                                    <template #default="{ row }">
                                        <el-input v-model="row.amount_including_tax" prop="num" disabled />
                                    </template>
                                </el-table-column>

                            </el-table>
                        </div>

                        <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="pay_date">
                                    <template #default="{ row }">
                                        <el-date-picker v-model="row.pay_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-col>

                </el-row>
            </el-form>
        </popup>
        <el-dialog v-model="showDialog" title="选择项目" width="70%">
            <projectTable @customEvent="customEvent"></projectTable>
        </el-dialog>

        <el-dialog v-model="showDialog1" title="选择供应商" width="70%">
            <suppliertable @customEvent="customEvent1"></suppliertable>
        </el-dialog>
        <div v-if="showDialog2">
            <el-dialog v-model="showDialog2" title="选择产品" width="70%">
                <prodctTable @customEvent="customEvent2" :project_id="formData.project_id"></prodctTable>
            </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 projectTable from '@/components/project/index.vue'
import suppliertable from '@/components/supplier/index.vue'
import prodctTable from '@/components/Materialprocurement_details/index.vue'
const list1 = reactive([])
const list2 = reactive([])
import { deptAll } from '@/api/org/department'
import { getAll } from '@/api/org/organization'
import { paymentplanLists } from '@/api/paymentplan'
import { apiProcurementContractDetailLists } from '@/api/procurement_contract_detail'
import { apiProcurementContractAdd, apiProcurementContractEdit, apiProcurementContractDetail } from '@/api/procurement_contract'
import { timeFormat } from '@/utils/util'
import type { PropType } from 'vue'
let props = defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    },

})
import { toChinesNum } from "@/utils/util";
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 showDialog2 = ref(false)
const project_name = ref('')
const project_code = ref('')
const supplier_name = ref('')
const supplier_code = ref('')
const contract_no = ref('')
const amount = ref('')
const amount_excluding_tax = ref('')
const amount_daxie = ref('')
const materialList = reactive([])
const paymentList = reactive([
    {
        id: "",
        period: "",
        pay_date: "",
        amount: "",
        remark: "",
    }


])
const formDataannex = reactive([])
import feedback from '@/utils/feedback'
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) {
        feedback.msgError(response.msg);
        return;
    }
    formDataannex.push(
        { uri: response.data.uri, name: response.data.name }

    );
};
// 删除上传的文件
const delFileFn = (index: number) => {
    formDataannex.splice(index, 1)
}
const handleAdd = (row: any) => {
    // 在 row 后面插入一行数据
    const index = paymentList.indexOf(row);
    paymentList.splice(index + 1, 0, {});
};

const handleDelete = (row: any) => {
    if (paymentList.length <= 1) return
    // 删除 row
    const index = paymentList.indexOf(row);
    paymentList.splice(index, 1);
};
const handleAdd1 = (row: any) => {
    // 在 row 后面插入一行数据
    const index = materialList.indexOf(row);
    materialList.splice(index + 1, 0, {});
};

const handleDelete1 = (row: any) => {
    // 删除 row
    const index = materialList.indexOf(row);
    materialList.splice(index, 1);
};
// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑采购合同' : '新增采购合同'
})

//获取采购明细
const procurementList = (id) => {
    apiProcurementContractDetailLists({ 'page_no': 1, 'page_size': 5000, 'contract_id': id }).then((res) => {
        const data = res.lists.map((item: any) => ({
            'id': item.id,
            'material_purchase_request_detail_id': item.material_purchase_request_detail_id,
            'material_name': item.material_name,
            'material_code': item.material_code,
            'material_unit': item.material_unit,
            'material_brand': item.material_brand,
            'material_purchase_request_code': item.material_purchase_request_code,
            'material_specs': item.material_specs,
            'num': item.num,
            'price': item.price,
            'tax_rate': props.dictData.tax_rate.find((item) => item.name == item.tax_rate)
        }))

        materialList.splice(0, materialList.length, ...data);
    })
}

//获取付款计划
const paymentplanList = (id: any) => {
    console.log("获取付款计划")
    paymentplanLists({ 'page_no': 1, 'page_size': 5000, 'contract_type': 1, 'contract_id': id }).then((res) => {
        const data = res.lists.map((item: any) => ({
            'period': item.period,
            'pay_date': item.pay_date,
            'amount': item.amount,
            'remark': item.remark,

        }))
        paymentList.splice(0, paymentList.length, ...data);
    })
}



//获取所有组织
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 formData = reactive({
    id: '',
    dept_id: '',
    org_id: '',
    supplier_id: '',
    project_id: '',
    contract_name: '',
    contract_type: '',
    signing_date: '',
    pay_type: '',
    account_period: '',
    retention_money_rate: '',
    remark: '',
    annex: '',
    material: [],
    payment_plan: []
})
const customEvent = (e: any) => {
    project_name.value = e.name
    formData.project_id = e.id
    project_code.value = e.project_code
    showDialog.value = false;
    materialList.splice(0, 9999)



};
const customEvent1 = (e: any) => {

    formData.supplier_id = e.id;
    supplier_code.value = e.supplier_code
    supplier_name.value = e.supplier_name
    showDialog1.value = false;
};
const customEvent2 = (e: any) => {
    materialList.push({
        'material_purchase_request_detail_id': e.id,
        'material_name': e.material_name,
        'material_code': e.material_code,
        'material_unit': e.material_unit,
        'material_brand': e.material_brand,
        'material_purchase_request_code': e.material_purchase_request_code,
        'material_specs': e.material_specs,
    });
    showDialog2.value = false;
}


//获取税率Name
const getTaxValue = (value) => {
    let i = props.dictData.tax_rate.findIndex((item) => item.value == value)
    return (1 - props.dictData.tax_rate[i]?.name / 100) || 0
}

//金额计算
watch(
    materialList,
    () => {
        amount.value = 0
        amount_excluding_tax.value = 0
        materialList.forEach(item => {
            item.amount_including_tax = item.num * item.price || 0 //单个含税金额
            item.amount_excluding_tax = item.amount_including_tax * getTaxValue(item.tax_rate) || 0 //单个不含税金额
            amount.value += item.amount_including_tax || 0 //计算合同金额
            amount_excluding_tax.value += item.amount_excluding_tax || 0//计算总不含税金额
            amount_daxie.value = toChinesNum(amount.value)
        });
    }
)
// 计算质保金
const retention_money = computed(() => {
    return amount.value * (formData.retention_money_rate / 100)
})



// 表单验证
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]
        }
    }
    procurementList(data.id)
    paymentplanList(data.id)
    project_name.value = data.project_name
    project_code.value = data.project_code
    contract_no.value = data.contract_no
    supplier_name.value = data.supplier_name
    supplier_code.value = data.supplier_code

}

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


// 提交按钮
const handleSubmit = async () => {
    if (materialList.length > 0) {

        formData.procurement_contract_detail = materialList.map((item) => ({
            'id': item.id,
            'material_purchase_request_detail_id': item.material_purchase_request_detail_id,
            'num': item.num,
            'price': item.price,
            'tax_rate': item.tax_rate,
        }))
    }

    if (paymentList.length > 0) {
        formData.payment_plan = paymentList.map((item) => ({
            'id': item.id,
            'period': item.period,
            'remark': item.remark,
            'amount': item.amount,
            'pay_date': item.pay_date,
        }))
    }
    await formRef.value?.validate()
    const data = { ...formData, }
    mode.value == 'edit'
        ? await apiProcurementContractEdit(data)
        : await apiProcurementContractAdd(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>
