<template>
    <div>
        <el-dialog v-model="dialogVisible" :close-on-click-modal="false" draggable width="1200px" height="500px">
            <el-card :body-style="cardBodyStyle">
                <el-form inline :model="query">
                    <el-form-item label="计划号" style="margin-bottom: 5px;">
                        <el-input v-model="query.planNo" placeholder="请输入" style="width: 200px; margin-right: 10px;" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="计划名称" style="margin-bottom: 5px;">
                        <el-input v-model="query.planNo" placeholder="请输入" style="width: 200px; margin-right: 10px;" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="需求日期" style="margin-bottom: 5px;">
                        <el-date-picker v-model="query.demandDt" type="date" value-format="YYYY-MM-DD" style="width: 200px; margin-right: 10px;" clearable/>
                    </el-form-item>
                    <!-- <el-form-item label="供应商名称" style="margin-bottom: 5px;">
                        <el-input v-model="query.tradePartnerName" placeholder="请输入" style="width: 200px; margin-right: 10px;" clearable></el-input>
                    </el-form-item> -->
                </el-form>
            </el-card>

            <el-card :body-style="cardBodyStyle">
                <el-button plain type="primary" @click="search">查询</el-button>
                <el-button plain type="success" @click="handleSelect">选择</el-button>
            </el-card>
            
            <el-card :body-style="cardBodyStyle">
                <el-table :data="tableData" border highlight-current-row @selection-change="handleSelectionChange">
                    <el-table-column type="selection" fixed></el-table-column>
                    <el-table-column type="index" label="序号" align="center" width="60" fixed="left">
                        <template #default="scope">
                            <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column v-for="(item, index) in column" :key="index" :prop="item.prop" :label="item.label"
                        header-align="center" align="center" show-overflow-tooltip :width="item.width"
                        :formatter="formatter">
                    </el-table-column>
                </el-table>
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="pageSizes"
                    :total="totalRows" background="background" layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange">
                </el-pagination>
            </el-card>
        </el-dialog>
    </div>
</template>

<script setup>

import {
    ref,
    onMounted,
    watch,
    getCurrentInstance
} from 'vue'

const {
    proxy
} = getCurrentInstance()

import tools from '@/tools'

const cardBodyStyle = ref(tools.style.card)

const dialogVisible = ref(false)
const open = () => {
    dialogVisible.value = true
}
const close = () => {
    dialogVisible.value = false
}

const props = defineProps({
    column: { // form查询项
        type: Array,
        default: () => [
            {
                prop: 'itemCd',
                label: '物料编码',
                width: 150,
            },
            {
                prop: 'itemNm',
                label: '物料名称',
                width: 150,
            },
            {
                prop: 'specType',
                label: '规格',
                width: 100,
            },
            {
                prop: 'qty',
                label: '数量',
                width: 100,
            },
            {
                prop: 'uom',
                label: '单位',
                width: 100,
            },
            {
                prop: 'taxPrice',
                label: '含税单价',
                width: 100,
            },
            {
                prop: 'totalAmount',
                label: '含税金额',
                width: 100,
            },
            {
                prop: 'price',
                label: '单价',
                width: 100,
            },
            {
                prop: 'amount',
                label: '金额',
                width: 100,
            },
            {
                prop: 'taxAmount',
                label: '税额',
                width: 100,
            },
            {
                prop: 'taxRate',
                label: '税率',
                width: 100,
            },
            {
                prop: 'tradePartnerCode',
                label: '供应商编码',
                width: 180,
            },
            {
                prop: 'tradePartnerName',
                label: '供应商名称',
                width: 180,
            },
            {
                prop: 'planNo',
                label: '计划号',
                width: 200,
            },
            {
                prop: 'planLn',
                label: '计划行号',
                width: 100,
            },
            {
                prop: 'planNm',
                label: '计划名称',
                width: 200,
            },
            {
                prop: 'addDeptName',
                label: '单位',
                width: 100,
            },
            {
                prop: 'addName',
                label: '计划员',
                width: 100,
            },
            {
                prop: 'demandDt',
                label: '需求日期',
                width: 200,
            },
            {
                prop: 'remark',
                label: '备注',
                width: 160,
            },
            {
                prop: 'cotFlag',
                label: '是否转为合同明细',
                width: 150,
            },
        ]
    },
    url: { // form查询数据
        type: String,
        default: 'pur/OrdLine/queryPopup'
    },
    params: {
		type: Object,
		default: () => {
		}
	},
})

const query = ref({
    planNo: '',
    planNm: '',
    demandDt: '',
    tradePartnerCode: ''
})


/**
 *  查询字典
 */
const dicList = ref({
    COM_PAY_MTH: [],
    PUR_PAY_TYPE: [],
    PROVINCE_CODE: [],
    PUR_PAY_STS: [],
})
const getDicList = () => {
    var url = 'framework/Common/querySelectorList'
    var param = {
        type: JSON.stringify(['MEASURING_UNIT', 'TAX_RATE',])
    }
    proxy.$axios.get(url, param).then(response => {
        if (response.data.code == '0') {
            dicList.value = response.data.data
        } else {
            ElMessage.error('操作失败！' + response.data.msg)
        }
    })
}

const formatter = (row, column, cellValue, index) => {
    if (!cellValue || cellValue == null || cellValue == '') {
        return cellValue
    }
    switch (column.property) {
        case 'uom':
            cellValue = dicList.value.MEASURING_UNIT.find(item => item.dicCode == cellValue).dicName
            break
        case 'taxRate':
            cellValue = dicList.value.TAX_RATE.find(item => item.dicCode == cellValue).dicName
            break
        case 'cotFlag':
            cellValue = cellValue === '0' ? '否' : '是'
            break
    }

    return cellValue
}
/**
 *  查询字典
 */


const multipleSelection = ref([])
const handleSelectionChange = (val) => {
    multipleSelection.value = val
}

const emit = defineEmits(['receiveFromChild'])
const handleSelect = () => {
    if (multipleSelection.value.length === 0) {
        ElMessage({
            type: 'warning',
            message: '请勾选要转换的需求计划明细'
        })
        return
    }

    // const first = multipleSelection.value[0]
    // const flag = multipleSelection.value.find(item => item.tradePartnerCode != first.tradePartnerCode)
    // if(flag) {
    //     ElMessage({
    //         type: 'warning',
    //         message: '请选择同一供应商下的采购计划明细'
    //     })
    //     return
    // }

    emit('receiveFromChild', multipleSelection.value)
    close()
}
const currentPage = ref(1)
const pageSize = ref(10)
const pageSizes = ref([10, 20, 30, 40])
const tableData = ref([])
const totalRows = ref()
const initTableData = () => { // 需求计划审批流程通过的 且 未转成合同明细的 cotFlag == '0'
    tableData.value = []
    query.value.tradePartnerCode = props.params.tradePartnerCode

    var url = props.url
    var param = {
        page: currentPage.value,
        rows: pageSize.value,
        params: JSON.stringify(query.value)
    }

    proxy.$axios.get(url, param).then(response => {
        if (response.data.code == '0') {
            tableData.value = response.data.data.records
            totalRows.value = response.data.data.total
            tableData.value = [{
                id: '1',
                planNo: 'PLAN001', // 与 tableData 中的生产计划关联
                planLn: '0001',
                planNm: '生产计划A',
                itemCd: '10101012351', // 物料编码
                itemNm: 'M2矿',   // 物料名称
                qty: 100,          // 数量
                uom: 'wet ton',         // 单位
                taxPrice: 1000.00,    // 含税单价
                totalAmount: 100000.00, // 含税金额 (数量 * 含税单价)
                price: 884.96,
                amount: 88496.00,
                taxRate: 13,     // 税率,
                tradePartnerCode: 'D01000008',
                tradePartnerName: '青岛陆洋兴达国际贸易有限公司',
                addDeptName: '生产部', // 单位（可以从 tableData 继承或单独设置）
                addName: '张三',    // 计划员（可以从 tableData 继承或单独设置）
                demandDt: '2024-10-01', // 需求日期（可以从 tableData 继承或单独设置）
                cancelFlag: '0',
                cotFlag: '0'
            },]
        } else {
            ElMessage.error('操作失败！' + response.data.msg)
        }
    })
}

const search = () => {
    initTableData()
}
const handleSizeChange = (val) => {
    pageSize.value = val
    initTableData()
}
const handleCurrentChange = (val) => {
    currentPage.value = val
    initTableData()
}

onMounted(() => {
    getDicList()
    initTableData()
})
watch(dialogVisible, (newValue, oldValue) => {
    if (newValue) {
        initTableData()
    } else {

    }
})
defineExpose({
    open,
    close
})
</script>

<style></style>