<template>
    <div class="demo-wrap min-flex-right">
        <div class="flex-between">
            <h2>{{ pageTitle }}</h2>
            <el-button type="primary" @click="openDialog">新增</el-button>

            <GuipDialog :dialogVisible="dialogVisible" :title="dialogTitle" :show-close-button="false"
                :show-cancel-button="showCancelButton" @confirm="handleConfirm" @cancel="handleCancel"
                @close="handleClose" @dialogVisibleChange="dialogVisibleChange">
                <el-form :model="form" class="el-row demo-ruleForm" ref="formRef">
                    <!-- 组件已经封装了  el-form-item  没有特殊需求，直接在组件上传prop label 就可以实现效果-->
                    <GuipSelect v-model="form.type" prop="type" label="检测类型" :options="type2nameOptions" />
                    <el-form-item label="采购单价" label-width="73px">
                        <div style="display: flex; align-items: center; gap: 8px; width: 100%;">
                            <GuipInput v-model="form.unit_price" prop="unit_price" />
                            <span>元 /</span>
                            <GuipInput v-model="form.unit_num" prop="unit_num" style="flex: 1;" />
                            <span>字（篇/页）</span>
                        </div>
                    </el-form-item>

                    <template v-if="type != 'purchase'">
<!--                        <el-form-item label="阶段成本" prop="cost" label-width="73px">-->
<!--                            <div style="display: flex; align-items: center; gap: 8px; width: 100%;">-->
<!--                                <GuipInput v-model="form.cost" style="flex: 1;" />-->
<!--                                <span>元</span>-->
<!--                            </div>-->
<!--                        </el-form-item>-->
                        <el-form-item label="起止日期" prop="date" label-width="73px">
                            <el-date-picker v-model="form.date" type="daterange" value-format="yyyy-MM-dd" range-separator="至"
                             start-placeholder="开始时间" end-placeholder="结束时间" @input="testClick" style="width: 100%;"></el-date-picker>
                        </el-form-item>
                    </template>
                </el-form>
            </GuipDialog>
        </div>
        <div class=" flex-common" v-if="type2filterOptions.length > 0">
            <el-form>
                <el-table :data="tableData" style="width: 100%">
                    <template v-if="type == 'purchase'">
                        <el-table-column prop="type">
                            <template slot="header">
                                <GuipSelect class="custom-select" v-model="chktype" :options="type2filterOptions"
                                    defaultValue="全部检测类型" @change="changeSelectType" />
                            </template>

                            <template slot-scope="scope">
                                {{ type2name[scope.row.type] }}
                            </template>
                        </el-table-column>

                        <el-table-column label="采购单价">
                            <template slot-scope="scope">
                                {{ scope.row.unit_price }} 元 / {{
                                    scope.row.unit_num == 1 ? '篇' : scope.row.unit_num + '字' }}
                            </template>
                        </el-table-column>

                        <el-table-column label="操作" width="200">
                            <template slot-scope="scope">
                                <a @click="editPurchase(scope.row)" style="color: #006aff;cursor: pointer;">编辑</a>
                            </template>
                        </el-table-column>
                    </template>

                    <template v-else>
                        <el-table-column prop="type">
                            <template slot="header">
                                <GuipSelect class="custom-select" v-model="chktype" :options="type2filterOptions"
                                    defaultValue="全部检测类型" @change="changeSelectType" />
                            </template>

                            <template slot-scope="scope">
                                {{ type2name[scope.row.type] }}
                            </template>
                        </el-table-column>

                        <el-table-column label="采购价">
                            <template slot-scope="scope">
<!--                                <template v-if="scope.row.unit_price > 0">-->
                                    单价：{{ scope.row.unit_price }} 元 / {{
                                        scope.row.unit_num == 1 ? '篇' : scope.row.unit_num + '字' }}
<!--                                </template>-->
<!--                                <template v-else>-->
<!--                                    成本：{{ scope.row.cost }} 元-->
<!--                                </template>-->
                            </template>
                        </el-table-column>

                        <el-table-column label="起止日期">
                            <template slot-scope="scope">
                                {{ scope.row.start_date.substring(0, 10) }} - {{ scope.row.end_date.substring(0, 10) }}
                            </template>
                        </el-table-column>

                        <el-table-column label="操作" width="200">
                            <template slot-scope="scope">
                                <a @click="editStagePurchase(scope.row)" style="color: #006aff;cursor: pointer;">编辑</a>
                                <a v-if="scope.row.is_sync == 0" @click="syncStagePurchase(scope.row)"
                                    style="color: #006aff;margin-left: 20px;cursor: pointer;">同步</a>
                            </template>
                        </el-table-column>
                    </template>
                </el-table>

                <el-pagination background @size-change='handleSizeChange' @current-change='handleCurrentChange'
                    :current-page="currentPage" :page-size=pageSize layout="prev, pager, next,jumper" :total="total">
                </el-pagination>
            </el-form>
        </div>
    </div>
</template>
<script>

import GuipDialog from "@/components/GuipDialog.vue";
import GuipSelect from "@/components/GuipSelect.vue";
import GuipInput from "@/components/GuipInput.vue";

export default {
    name: 'purchase',
    props: {
        pageTitle: {
            type: String,
            default: ''
        },
        type: {
            type: String,
            default: ''
        },
        showDateSelect: {
            type: Boolean,
            default: true
        }
    },
    components: {
        GuipInput,
        GuipSelect,
        GuipDialog
    },
    data() {
        return {
            test: '00000',
            id: 0,
            chktype: '0',
            currentPage: 1,    //当前页
            pageSize: 20,   //每页的容量
            total: 0,   //列表总数
            tableData: [],
            type2name: [],
            dialogTitle: '新增',//弹框标题
            dialogVisible: false,//是否展示弹框
            showCancelButton: true, // 控制是否显示取消按钮
            showCloseButton: true, // 控制是否显示关闭按钮
            form: {
                id: '',
                type: '',
                unit_price: '',
                unit_num: '',
                cost: '',
                date: [],
                start_date: '',
                end_date: '',
            },
        }
    },
    mounted() {
        document.title = this.pageTitle

        this.currentPage = 1
        this.getData()
    },
    computed: {
        type2nameOptions() {
            if (this.type2name.length == 0) return true

            return Object.entries(this.type2name).map(([value, label]) => ({
                label,
                value: String(value)  // 如果你需要 value 是数字
            }));
        },
        type2filterOptions() {
            if (this.type2name.length == 0) return true

            let options = Object.entries(this.type2name).map(([value, label]) => ({
                label,
                value: String(value)  // 如果你需要 value 是数字
            }));

            return [{ label: '全部检测类型', value: '0' }, ...options];
        }
    },
    watch: {
        '$route'() {
            document.title = this.pageTitle
            this.currentPage = 1
            this.getData()
        },
    },
    methods: {
        testClick(e) {
            this.$nextTick(() => {
                if (Array.isArray(e) && e.length === 2) {
                    this.$set(this.form, "start_date", e[0]);
                    this.$set(this.form, "end_date",  e[1]);
                } else {
                    this.$set(this.form, "start_date", '');
                    this.$set(this.form, "end_date",  '');
                }
            });
        },
        getData(){
            if (this.type == 'purchase') {
                this.getPurchase()
            } else {
                this.getStagePurchase()
            }
        },
        changeSelectType() {
            this.currentPage = 1
            this.getData()
        },
        getPurchase() {
            const that = this
            that.tableData = []
            this.$http('POST', '/supernew/ajax_get_purchase_list', {
                type: that.chktype,
                cur_page: that.currentPage,
                page_size: that.pageSize,
            }).then(response => {
                this.$nextTick(() => {
                    that.tableData = response.data.list
                    that.type2name = response.data.type2name
                    that.total = response.data.total
                })
            }).catch(error => {
                console.error(error, 'error')
            })
        },
        getStagePurchase() {
            const that = this
            that.tableData = []
            this.$http('POST', '/supernew/ajax_get_stage_purchase', {
                type: that.chktype,
                cur_page: that.currentPage,
                page_size: that.pageSize,
            }).then(response => {
                this.$nextTick(() => {
                    that.tableData = response.data.list
                    that.type2name = response.data.type2name
                    that.total = response.data.total
                })
            }).catch(error => {
                console.error(error, 'error')
            })
        },
        handleSizeChange(val) {
            this.pageSize = val
            this.getData()
        },
        handleCurrentChange(val) {
            this.currentPage = val
            this.getData()
        },
        openDialog() {
            this.dialogVisible = true;
            // 重置数据
            this.$nextTick(() => {
                this.$refs.formRef.resetFields();
            });
        },  // 确认按钮事件
        handleConfirm() {
            const that = this
            // 避免打开弹框，重置数据时，新添加的数据被清空，重新拷贝一份  或者 添加数据后，拉取新数据
            let form = JSON.parse(JSON.stringify(that.form))
            if (!form.type) {
                this.$message.warning('请选择检测类型');
                return
            }
            if (that.type == 'purchase') {
                if (!form.unit_price || !form.unit_num) {
                    this.$message.warning('请输入采购单价');
                    return
                }

                this.$http('POST', '/supernew/ajax_save_purchase', {
                    id: form.id,
                    type: form.type,
                    unit_price: form.unit_price,
                    unit_num: form.unit_num,
                }).then(response => {
                    this.$nextTick(() => {
                        if (!response.status) {
                            this.$message.warning(response.info);
                        } else {
                            if (form.id > 0) {
                                that.$set(this.tableData, this.tableData.findIndex(item => item.id === form.id), { ...form });
                            } else {
                                form.id = response.data
                                that.tableData.unshift(form);
                            }
                        }
                        this.dialogVisible = false;
                    })
                }).catch(error => {
                    this.$message.warning(error);
                    this.dialogVisible = false;
                })
            } else {
                if ((!form.unit_price || !form.unit_num) && !form.cost) {
                    this.$message.warning('请输入采购单价');
                    return
                }

                if (!form.start_date || !form.end_date) {
                    this.$message.warning('请选择起止日期');
                    return
                }

                this.$http('POST', '/supernew/ajax_save_stage_purchase', {
                    id: form.id,
                    type: form.type,
                    unit_price: form.unit_price,
                    unit_num: form.unit_num,
                    // cost: form.cost,
                    sdate: form.start_date,
                    edate: form.end_date,
                }).then(response => {
                    this.$nextTick(() => {
                        if (!response.status) {
                            this.$message.warning(response.info);
                        } else {
                            if (form.id > 0) {
                                that.$set(this.tableData, this.tableData.findIndex(item => item.id === form.id), { ...form });
                            } else {
                                form.id = response.data
                                form.is_sync = 0
                                that.tableData.unshift(form);
                            }
                        }
                        this.dialogVisible = false;
                    })
                }).catch(error => {
                    this.$message.warning(error);
                    this.dialogVisible = false;
                })
            }
        },
        // 取消按钮事件
        handleCancel() {
            // this.$message.warning('点击了取消按钮');
            this.dialogVisible = false;
        },
        // 关闭弹框事件
        handleClose() {
            // this.$message.info('弹框已关闭');
            this.dialogVisible = false;
        },
        dialogVisibleChange(data) {
            console.log(data, 'data098908090');
        },
        formatDateTime(date) {
            const pad = n => n.toString().padStart(2, '0');
            const Y = date.getFullYear();
            const M = pad(date.getMonth() + 1);
            const D = pad(date.getDate());
            return `${Y}-${M}-${D}`;
        },
        editPurchase(row) {
            this.dialogVisible = true;
            this.$nextTick(() => {
                this.form = { ...row };
                // 如果需要强制更新视图
                this.$forceUpdate();
            })
        },
        editStagePurchase(row) {
            this.dialogVisible = true;
            this.$nextTick(()=>{
                this.form = { ...row };
                this.$set(this.form,'date', [row.start_date, row.end_date])
                this.$forceUpdate();
            })
        },
        syncStagePurchase(row) {
            this.$http('POST', '/supernew/ajax_sync_order_cost', {
                id: row.id,
            }).then(response => {
                this.$nextTick(() => {
                    if (response.status) {
                        row.is_sync = 1;
                    }
                    this.$message.warning(response.info);
                })
            }).catch(error => {
                this.$message.warning(error);
            })
        },
    }
}
</script>
<style scoped lang="scss">
.custom-select {
    width: 200px;
}
</style>