<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>
                <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"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-input v-model="customer_name" clearable placeholder="点击选择客户" readonly
                                @click="showDialog = true" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="联系人" prop="custom_master_name">
                            <el-input v-model="formData.custom_master_name" disabled clearable placeholder="请输入联系人" />
                        </el-form-item></el-col>
                    <el-col :span="8">
                        <el-form-item label="联系电话" prop="custom_master_phone"
                            :rules="[{ validator: isMobileNumber, trigger: 'blur' }]">
                            <el-input v-model="formData.custom_master_phone" disabled clearable placeholder="请输入联系电话"
                                :regex="/^ 1[3 - 9]\d{ 9}$ /" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="报价日期" prop="quotation_date">
                            <el-date-picker v-model="formData.quotation_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="create_user">
                            <el-input v-model="formData.create_user" clearable placeholder="请输入制单人" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="发票类型" prop="invoice_type">
                            <el-radio-group v-model="formData.invoice_type" placeholder="请选择发票类型">
                                <el-radio v-for="( item, index ) in  dictData.invoice_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="amount_including_tax"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-input v-model="formData.amount_including_tax" disabled clearable placeholder="请输入含税金额"
                                @input="amountinput" />
                        </el-form-item></el-col>
                    <el-col :span="8">
                        <el-form-item label="含税金额大写" prop="amount_including_tax"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-input v-model="amount_including_daxie" disabled clearable placeholder="请输入含税金额大写" />
                        </el-form-item></el-col>

                    <el-col :span="8">
                        <el-form-item label="运费" prop="freight"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="formData.freight" clearable placeholder="请输入运费" type="number" />
                        </el-form-item></el-col><el-col :span="8">
                        <el-form-item label="其他费用" prop="other_fee"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="formData.other_fee" clearable type="number" placeholder="请输入其他费用" />
                        </el-form-item></el-col>

                    <el-col :span="8">
                        <el-form-item label="合计金额" prop="total_amount">
                            <el-input v-model="formData.total_amount" disabled clearable placeholder="请输入合计金额"
                                @input="amountinput1" />
                            <div v-show="false">{{ totalPrice }}</div>
                        </el-form-item></el-col>
                    <el-col :span="8">
                        <el-form-item label="合计金额大写" prop="total_amount">
                            <el-input v-model="total_amount_daxie" clearable disabled placeholder="请输入合计金额大写" />
                        </el-form-item></el-col>
                    <el-col :span="8">
                        <el-form-item label="客户需求" prop="customer_require"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="formData.customer_require" 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="showDialog1 = true">选择产品</el-button></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 }">
                                <el-input v-model="row.name" disabled placeholder="系统自动填写" />
                            </template>
                        </el-table-column>
                        <el-table-column label="产品编码" prop="code">
                            <template #default="{ row }"> <el-input v-model="row.code" disabled placeholder="系统自动填写" />
                            </template></el-table-column>
                        <el-table-column label="规格型号" prop="specs">
                            <template #default="{ row }"> <el-input v-model="row.specs" disabled placeholder="系统自动填写" />
                            </template></el-table-column>

                        <el-table-column label="品牌" prop="brand">
                            <template #default="{ row }">
                                <el-input v-model="row.brand" disabled placeholder="系统自动填写" />
                            </template>
                        </el-table-column>

                        <el-table-column label="参数说明" prop="parameter_description">
                            <template #default="{ row }"> <el-input v-model="row.parameter_description" disabled />
                            </template></el-table-column>
                        <el-table-column label="单位" prop="unit">
                            <template #default="{ row }"> <el-input v-model="row.unit" disabled />
                            </template></el-table-column>
                        <el-table-column label="数量" prop="product_num">
                            <template #default="{ row }">
                                <el-input v-model="row.product_num" />
                            </template>
                        </el-table-column>
                        <el-table-column label="税率(%)" prop="tax_rate">
                            <template #default="{ row }">

                                <el-select class="flex-1" v-model="row.tax_rate" clearable placeholder="请选择税率">
                                    <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="price">
                            <template #default="{ row }">
                                <el-input v-model="row.price" />
                            </template>
                        </el-table-column>
                        <el-table-column label="含税金额" prop="amount">
                            <template #default="{ row }">
                                <el-input v-model="row.amount" disabled />
                            </template>
                        </el-table-column>
                        <el-table-column label="不含税金额" prop="amount_including">
                            <template #default="{ row }">
                                <el-input v-model="row.amount_including" disabled />
                            </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>
                <!-- <div>
                    <reviewprocess></reviewprocess>
                </div> -->


            </el-form>
        </popup>

        <el-dialog v-model="showDialog" title="选择客户" width="70%">

            <customDialog @customEvent="customEvent"></customDialog>
        </el-dialog>

        <el-dialog v-model="showDialog1" title="选择产品" width="70%">
            <customDialog1 @customEvent="customEvent1"></customDialog1>
        </el-dialog>

    </div>
</template>

<script lang="ts" setup name="quotationEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiQuotationAdd, apiQuotationEdit, apiQuotationDetail } from '@/api/quotation'
import { timeFormat, convertToChinese } from '@/utils/util'
import { toChinesNum } from "@/utils/util";
import customDialog1 from '@/components/product/index.vue'
import reviewprocess from '@/components/reviewprocess/index.vue'
const list1 = reactive([])
const list2 = reactive([])
import { deptAll } from '@/api/org/department'
import { getAll } from '@/api/org/organization'
import type { PropType } from 'vue'
import { computed, watch } from "vue"

const props = 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 customer_name = ref('')
const amount_including_daxie = ref('')
const total_amount_daxie = ref('')
const tableData = ref([])
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 popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑报价单' : '新增报价单'
})
//获取所有组织
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 amountinput = (e) => {
    // console.log(e)
    if (e && e > 0) {
        amount_including_daxie.value = toChinesNum(e)
    }
}
const amountinput1 = (e) => {
    // console.log(e)
    if (e && e > 0) {
        total_amount_daxie.value = toChinesNum(e)
    }
}

//获取部门
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: '',
    approve_id: 1,
    custom_id: '',
    quotation_date: '',
    custom_master_name: '',
    custom_master_phone: '',
    create_user: '',
    invoice_type: '',
    amount_including_tax: '',
    freight: '',
    other_fee: '',
    total_amount: '',
    customer_require: '',
    remark: '',
    annex: [],
    quotation_detail: [],

})

const customEvent = (e: any) => {
    formData.custom_id = e.id;
    customer_name.value = e.name;
    formData.custom_master_name = e.master_name
    formData.custom_master_phone = e.master_phone
    showDialog.value = false;

};
const customEvent1 = (e: any) => {
    tableData.value.push({
        product_id: e.id,
        name: e.name,
        code: e.code,
        unit: e.unit,
        specs: e.specs,
        brand: e.brand,
        parameter_description: e.parameter_description,
        product_num: 1,
        tax_rate: '',
        price: e.sales_price,
        remark: '',
        amount: e.sales_price,
        amount_including: e.sales_price
    })
    console.log(e)
    // formData.customer_id = e.id;
    // customer_name.value = e.name;
    showDialog1.value = false;

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

})

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 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)
    }
    if (data.total_amount && data.total_amount > 0) {
        amountinput1(data.total_amount)
    }
    if (data.amount_including_tax && data.amount_including_tax > 0) {
        amountinput(data.amount_including_tax)
    }
    customer_name.value = data.custom_name
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }


}

const getDetail = async (row: Record<string, any>) => {

    const data = await apiQuotationDetail({
        id: row.id
    })
    console.log(data)



    setFormData(data)
}
const isMobileNumber = (rule: any, value: string | number | any[], callback: (arg0: Error | undefined) => void) => {

    if (value && !/^1[3|4|5|7|8][0-9]{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号码'));
    } else {
        callback()
    }
};

// 提交按钮
const handleSubmit = async () => {
    if (formDataannex.length > 0) {
        formData.annex = formDataannex.map((item) => item.uri)
    }
    if (tableData.value.length > 0) {
        formData.quotation_detail = tableData.value.map(item => ({

            tax_inclusive_price: item.price,
            product_id: item.product_id,
            num: item.product_num,
            tax_rate: item.tax_rate,
            remark: item.remark
        }));


    }
    await formRef.value?.validate()
    const data = { ...formData, }
    mode.value == 'edit'
        ? await apiQuotationEdit(data)
        : await apiQuotationAdd(data)
    popupRef.value?.close()
    emit('success')
}

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

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

// 计算价格
const totalPrice = computed(() => {
    formData.total_amount = Number(formData.amount_including_tax) + Number(formData.freight || 0) + Number(formData.other_fee || 0)
    total_amount_daxie.value = convertToChinese(formData.total_amount)
    return Number(formData.amount_including_tax) + Number(formData.freight || 0) + Number(formData.other_fee || 0)
})

watch(tableData.value, (newVal, oldVal) => {
    let num = 0;
    tableData.value.forEach(item => {
        item.amount = item.price * item.product_num
        let name;
        props.dictData.tax_rate.forEach(items => {
            if (items.value == item.tax_rate) {
                name = items.name
            }
        })
        item.amount_including = item.amount * (1 - (Number(name) / 100)) || 0
        num += item.amount

    })
    formData.amount_including_tax = num
    amount_including_daxie.value = convertToChinese(num)
})

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