<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" inline>
                <el-steps :active="2" align-center style="margin-bottom: 30px;">
                    <el-step title="销售发起" />
                    <el-step title="商务部技术部" />
                    <el-step title="财务部" />
                    <el-step title="事业部总工" />
                    <el-step title="事业部总经理审批" />
                    <el-step title="销售副总" />
                </el-steps>
                <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="buy_bidding_document_id" @click="showDialog = true" :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="bid_document_no" clearable readonly placeholder="请选择标书编号" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="购买人员" prop="buy_bidding_document_id">
                            <el-input v-model="buyer" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="客户名称" prop="buy_bidding_document_id" :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="bid_document_no" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="项目名称" prop="buy_bidding_document_id" :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="project_name" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="招标公司名称" prop="buy_bidding_document_id">
                            <el-input v-model="invite_tenders_company_name" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="投标公司名称" prop="buy_bidding_document_id">
                            <el-input v-model="bid_company_name" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="购买标书金额" prop="buy_bidding_document_id">
                            <el-input v-model="amount" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">

                        <el-form-item label="招标项目资金来源" prop="buy_bidding_document_id">
                            <!-- <el-select v-model="project_fund_source" clearable disabled placeholder="系统自动填写">
                                <el-option v-for="(item, index) in dictData.construction_funds_sources" :key="index" :label="item.name" :value="parseInt(item.value)" />
                            </el-select> -->
                            <el-input v-model="bidding_project_fund_source" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="投标时间" prop="buy_bidding_document_id">
                            <el-input v-model="bid_date" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="购买标书时间" prop="buy_bidding_document_id">
                            <el-input v-model="buy_date" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="招标方式" prop="buy_bidding_document_id">
                            <!-- <el-select v-model="invite_tenders_type" clearable disabled placeholder="系统自动填写">
                                <el-option v-for="(item, index) in dictData.bidding_method" :key="index" :label="item.name" :value="parseInt(item.value)" />
                            </el-select> -->
                            <el-input v-model="invite_tenders_type" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="投标地址" prop="buy_bidding_document_id">
                            <el-input v-model="bid_address" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>


                    <el-col :span="8">
                        <el-form-item label="是否需要保证金" prop="is_margin">
                            <el-input v-model="is_margin" clearable disabled placeholder="系统自动填写" />
                            <!-- <el-radio-group v-model="is_margin" placeholder="请选择是否需要保证金">
                                <el-radio v-for="(item, index) in dictData.whether_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="bid_opening_date">
                             <el-date-picker class="flex-1 !flex" v-model="formData.bid_opening_date" clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择开标日期">
                            </el-date-picker> 
                            <el-input v-model="bid_opening_date" clearable disabled placeholder="系统自动填写" />
                        </el-form-item></el-col> <el-col :span="8"> -->

                    <!--       <el-col :span="8"><el-form-item label="保证金退还时间" prop="deposit_refund_time">
                             <el-date-picker class="flex-1 !flex" v-model="formData.deposit_refund_time" clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择保证金退还时间">
                            </el-date-picker> 
                            <el-input v-model="deposit_refund_time" clearable disabled placeholder="系统自动填写" />
                        </el-form-item> 
                    </el-col>-->


                    <!-- <el-col :span="8">
                        <el-form-item label="招标项目概况" prop="bidding_project_overview">
                            <el-input v-model="bidding_project_overview" clearable disabled placeholder="系统自动填写" />
                            <el-input v-model="formData.bidding_project_overview" clearable placeholder="请输入招标项目概况" />
                        </el-form-item></el-col> <el-col :span="8">
                        <el-form-item label="项目简介" prop="project_introduction">
                            <el-input v-model="project_introduction" clearable disabled placeholder="系统自动填写" />
                            <el-input v-model="formData.project_introduction" clearable placeholder="请输入项目简介" />
                        </el-form-item>
                    </el-col> -->
                </el-row>
                <div class="tit">技术审查</div>
                <el-row>

                    <el-col :span="8">
                        <el-form-item label="技术协议偏差" prop="technical_protocol_deviation">
                            <el-input v-model="formData.technical_protocol_deviation" clearable placeholder="请输入技术协议偏差" />
                        </el-form-item></el-col> <el-col :span="8">
                        <el-form-item label="协议偏差处理方案" prop="protocol_deviation_handling_plan">
                            <el-input v-model="formData.protocol_deviation_handling_plan" clearable placeholder="请输入协议偏差处理方案" />
                        </el-form-item></el-col>
                    <el-col :span="24">
                        <el-form-item label="技术审查附件" prop="technical_review_annex">

                            <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_four1" ref="upload">
                                <el-button type="primary">
                                    上传
                                </el-button>
                            </el-upload>

                            <div>
                                <div v-for="(item, index) in formDataannex1" 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="delFileFn1(index)">x</span>
                                </div>
                            </div>

                        </el-form-item>
                    </el-col>


                </el-row>
                <div class="tit">商务审查</div>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="总金额" prop="business_review_total_amount">
                            <el-input v-model="formData.business_review_total_amount" clearable placeholder="请输入总金额" />
                        </el-form-item></el-col> <el-col :span="8">
                        <el-form-item label="税率" prop="tax_rate">
                            <el-select class="flex-1" v-model="formData.tax_rate" clearable placeholder="请选择税率">
                                <el-option v-for="(item, index) in dictData.tax_rate" :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="pay_type">
                            <el-select class="flex-1" v-model="formData.pay_type" clearable placeholder="请选择付款方式">
                                <el-option v-for="(item, index) in dictData.pay_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="pay_rate">
                            <el-input v-model="formData.pay_rate" clearable placeholder="请输入付款比例" />
                        </el-form-item></el-col> <el-col :span="8">
                        <el-form-item label="商务合同偏差" prop="business_contract_deviation">
                            <el-input v-model="formData.business_contract_deviation" clearable placeholder="请输入商务合同偏差" />
                        </el-form-item></el-col> <el-col :span="8">
                        <el-form-item label="偏差处理方案" prop="business_contract_deviation_handling_plan">
                            <el-input v-model="formData.business_contract_deviation_handling_plan" clearable placeholder="请输入偏差处理方案" />
                        </el-form-item></el-col> <el-col :span="24">
                        <el-form-item label="商务审查附件" prop="business_contract_deviation_annex">

                            <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_four2" ref="upload">
                                <el-button type="primary">
                                    上传
                                </el-button>
                            </el-upload>

                            <div>
                                <div v-for="(item, index) in formDataannex2" 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="delFileFn2(index)">x</span>
                                </div>
                            </div>



                        </el-form-item></el-col>
                </el-row>
                <div class="tit">审查明细</div>
                <div style="margin-bottom: 30px;">
                    <el-table :data="tableData">
                        <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="name">
                            <template #default="{ row, $index }">
                                <el-input v-model="row.name" readonly @click="productDiag(row, $index)" placeholder="请选择产品">
                                    <template #suffix>
                                        <icon name="el-icon-Search" />
                                    </template>
                                </el-input>
                            </template>
                        </el-table-column>
                        <el-table-column label="型号规格" prop="specs">
                            <template #default="{ row }">
                                <el-input v-model="row.specs" />
                            </template></el-table-column>
                        <el-table-column label="单位" prop="unit">
                            <template #default="{ row }">
                                <el-input v-model="row.unit" /> </template>
                        </el-table-column>
                        <el-table-column label="数量" prop="num">
                            <template #default="{ row, $index }">
                                <el-input v-model="row.num" type="number" @input="jiprice1(row, $index)" /> </template>
                        </el-table-column>

                        <el-table-column label="成本单价" prop="cost_price">
                            <template #default="{ row, $index }">
                                <el-input v-model="row.cost_price" type="number" @input="jiprice2(row, $index)" /> </template>
                        </el-table-column>

                        <el-table-column label="金额" prop="cost_amount">
                            <template #default="{ row }">
                                <el-input v-model="row.cost_amount" type="number" disabled placeholder="系统自动计算" /> </template>
                        </el-table-column>
                        <el-table-column label="点数" prop="points">
                            <template #default="{ row }">
                                <el-input v-model="row.points" type="number" /> </template>
                        </el-table-column>
                        <el-table-column label="报价单价" prop="sale_price">
                            <template #default="{ row, $index }">
                                <el-input v-model="row.sale_price" type="number" @input="jiprice3(row, $index)" /> </template>
                        </el-table-column>
                        <el-table-column label="报价金额" prop="total_amount">
                            <template #default="{ row }">
                                <el-input v-model="row.sale_amount" type="number" disabled placeholder="系统自动计算" />
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </el-form>
        </popup>
        <el-dialog v-model="showDialog" title="选择标书" width="70%">
            <biddocumentTable @customEvent="customEvent"></biddocumentTable>
        </el-dialog>
        <el-dialog v-model="showDialog1" title="选择产品" width="70%">
            <customDialog1 @customEvent="customEvent1"></customDialog1>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup name="bidDocumentExaminationEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import customDialog1 from '@/components/product/index.vue'
import biddocumentTable from "@/components/biddocument/index.vue"
import { apiBidDocumentExaminationAdd, apiBidDocumentExaminationEdit, apiBidDocumentExaminationDetail } from '@/api/bid_document_examination'
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 num = ref(0)
const bid_document_no = ref('')
const invite_tenders_company_name = ref('')
const bid_company_name = ref('')
const amount = ref('')
const buyer = ref('')
const project_name = ref('')
const project_fund_source = ref('')
const is_margin = ref('')
const bid_date = ref('')
const buy_date = ref('')
const bidding_project_fund_source = ref('')
const invite_tenders_type = ref('')
const bid_opening_date = ref('')
const deposit_refund_time = ref('')
const bidding_project_overview = ref('')
const project_introduction = ref('')
const bid_address = ref('')
const tableData = ref([{}])
const list1 = reactive([])
const list2 = reactive([])
import { deptAll } from '@/api/org/department'
import { getAll } from '@/api/org/organization'
import configs from "@/config"
const base_url = configs.baseUrl + configs.urlPrefix
import useUserStore from "@/stores/modules/user";
const userStore = useUserStore();
const formDataannex = reactive([])
const formDataannex1 = reactive([])
const formDataannex2 = reactive([])
// 上传文件
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 handleAvatarSuccess_four1 = (
    response,
    uploadFile
) => {
    if (response.code == 0) {
        ElMessage.error(response.msg);
        return;
    }
    formDataannex1.push(
        { uri: response.data.uri, name: response.data.name }

    );
};
// 删除上传的文件
const delFileFn1 = (index: number) => {
    formDataannex1.splice(index, 1)
}
//金额计算
const jiprice1 = (row: any, index: any) => {
    console.log(row)
    if (row.cost_price) {
        row.cost_amount = row.num * row.cost_price
    }
    if (row.sale_price) {
        row.cost_amount = row.num * row.sale_price
    }
}
const jiprice2 = (row: any, index: any) => {
    console.log(row)
    if (row.num) {
        row.cost_amount = row.num * row.cost_price
    }
}

const jiprice3 = (row: any, index: any) => {
    if (row.num) {
        row.sale_amount = row.num * row.sale_price
    }
    // console.log(row)
}

// 上传文件
const handleAvatarSuccess_four2 = (
    response,
    uploadFile
) => {
    if (response.code == 0) {
        ElMessage.error(response.msg);
        return;
    }
    formDataannex2.push(
        { uri: response.data.uri, name: response.data.name }

    );
};
// 删除上传的文件
const delFileFn2 = (index: number) => {
    formDataannex2.splice(index, 1)
}

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

const handleDelete = (row: any) => {
    // 删除 row
    const index = tableData.value.indexOf(row);
    tableData.value.splice(index, 1);
};

//打开产品弹窗
const productDiag = (row: any, index: number) => {
    num.value = index
    showDialog1.value = true
}
// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑标书审查' : '新增标书审查'
})

// 表单数据
const formData = reactive({
    id: '',
    dept_id: '',
    org_id: '',
    approve_id: 0,
    buy_bidding_document_id: '',

    bidding_project_overview: '',
    project_introduction: '',
    technical_protocol_deviation: '',
    protocol_deviation_handling_plan: '',
    technical_review_annex: '',
    business_review_total_amount: 0,
    tax_rate: '',
    pay_type: '',
    pay_rate: '',
    business_contract_deviation: '',
    business_contract_deviation_handling_plan: '',
    business_contract_deviation_annex: '',
    quotation_detail: ''
})

//获取值
const customEvent = (e: any) => {
    formData.buy_bidding_document_id = e.id;
    is_margin.value = e.is_margin
    bid_document_no.value = e.bid_document_no
    invite_tenders_company_name.value = e.invite_tenders_company_name
    bid_company_name.value = e.bid_company_name
    amount.value = e.amount
    buyer.value = e.buyer
    project_name.value = e.project_name
    bid_date.value = e.bidding_time
    buy_date.value = e.buy_date
    invite_tenders_type.value = e.bid_type
    bid_address.value = e.bid_address
    bidding_project_fund_source.value = e.bidding_project_fund_source
    bid_opening_date.value = e.bid_opening_date
    // deposit_refund_time.value = e.margin_amount_return_date
    bidding_project_overview.value = e.bid_project_overview
    project_introduction.value = e.project_desc
    showDialog.value = false

};
const customEvent1 = (e: any) => {
    tableData.value[num.value].product_id = e.id
    tableData.value[num.value].name = e.name
    tableData.value[num.value].specs = e.specs
    tableData.value[num.value].unit = e.unit


    // formData.customer_id = e.id;
    // customer_name.value = e.name;
    showDialog1.value = false;

    console.log(tableData.value)
};
// 表单验证
const formRules = reactive<any>({

})

//获取所有组织
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 setFormData = async (data: Record<any, any>) => {

    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
    if (data.dept_id) {
        getlist1(data.org_id)
    }


    if (data.technical_review_annex && data.technical_review_annex.length > 0) {
        const arry1 = data.technical_review_annex.map((item: any, index: any) => {
            return {
                name: `文件${index + 1}`,
                uri: item
            };
        });
        Object.assign(formDataannex1, arry1)
    }
    if (data.business_contract_deviation_annex && data.business_contract_deviation_annex.length > 0) {

        const arry1 = data.business_contract_deviation_annex.map((item: any, index: any) => {
            return {
                name: `文件${index + 1}`,
                uri: item
            };
        });
        Object.assign(formDataannex2, arry1)

    }


    bid_document_no.value = data.bid_document_no
    invite_tenders_company_name.value = data.invite_tenders_company_name
    bid_company_name.value = data.bid_company_name
    amount.value = data.bid_document_amount

    buyer.value = data.buyer
    bid_date.value = data.bidding_time
    buy_date.value = data.buy_date
    //project_fund_source.value = data.project_fund_source
    bid_date.value = data.bidding_time
    invite_tenders_type.value = data.bid_type
    bid_address.value = data.bid_address
    bidding_project_fund_source.value = data.bidding_project_fund_source
    bid_opening_date.value = data.bid_opening_date
    deposit_refund_time.value = data.margin_amount_return_date
    bidding_project_overview.value = data.bid_project_overview
    project_introduction.value = data.project_desc

    // //@ts-ignore
    // formData.bid_opening_date = timeFormat(formData.bid_opening_date, 'yyyy-mm-dd hh:MM:ss')
    // //@ts-ignore
    // formData.deposit_refund_time = timeFormat(formData.deposit_refund_time, 'yyyy-mm-dd hh:MM:ss')
}

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


// 提交按钮
const handleSubmit = async () => {
    if (formDataannex1.length > 0) {
        formData.technical_review_annex = JSON.stringify(formDataannex1.map(item => item.uri))
    }
    if (formDataannex2.length > 0) {
        formData.business_contract_deviation_annex = JSON.stringify(formDataannex2.map(item => item.uri))
    }
    if (tableData.value.length > 0) {
        let data1 = tableData.value.map((item) => ({
            product_id: item.product_id,
            num: item.num,
            points: item.points,
            cost_price: item.cost_price,
            sale_price: item.sale_price
        }))
        formData.quotation_detail = JSON.stringify(data1)
    }



    await formRef.value?.validate()
    const data = { ...formData, }
    mode.value == 'edit'
        ? await apiBidDocumentExaminationEdit(data)
        : await apiBidDocumentExaminationAdd(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>
