﻿<template>
    <div class="row justify-content-center">
        <div class="col-12 col-md-10 col-lg-10">
            <div class="card shadow">
                <div class="card-header bg-primary text-white text-center">
                    <h4 class="mb-0">收款收據開立作業</h4>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="mb-3 col-12 col-md-6">
                            <label for="source" class="form-label">來源 <span class="text-danger">*</span></label>
                            <select class="form-select" id="source" v-model="formData.source" required :disabled="mode=='view'||mode=='edit'">
                                <option value="">請選擇</option>
                                <option v-for="(desc, value) in sources" :key="value" :value="value">
                                    {{desc}}
                                </option>
                            </select>
                        </div>
                        <div class="mb-3 col-12 col-md-6">
                            <!--source=1 就要有-->
                            <label for="order_no" class="form-label">報名單號 <span class="text-danger" v-show="order_no_need">*</span></label>
                            <div class="input-group mb-3"
                                 @click.prevent="showPickOrder" :disabled="mode=='view'||mode=='edit'">
                                <input class="form-control search-text" type="text" readonly
                                       id="order_no" runat="server" placeholder="報名單號" v-model="formData.order_no">
                                <button class="btn btn-outline-secondary" type="button">
                                    <i class="mdi mdi-view-list-outline"></i>
                                </button>
                            </div>
                        </div>
                        <!--<div class="mb-3 col-12 col-md-6">
                            <label for="" class="form-label">開立日期 <span class="text-danger">*</span></label>
                            <v-menu ref="menu"
                                    v-model="menu"
                                    :close-on-content-click="false"
                                    :return-value.sync="formData.receipt_date"
                                    transition="scale-transition"
                                    offset-y
                                    min-width="auto"
                                    :disabled="mode=='view'||mode=='edit'">
                                <template v-slot:activator="{ on, attrs }">
                                    <v-text-field v-model="formData.receipt_date"
                                                  prepend-icon="mdi-calendar"
                                                  readonly
                                                  v-bind="attrs"
                                                  v-on="on"></v-text-field>
                                </template>
                                <v-date-picker v-model="formData.receipt_date"
                                               :active-picker.sync="activePicker"
                                               :max="(new Date(Date.now() - (new Date()).getTimezoneOffset() * 60000)).toISOString().substring(0, 10)"
                                               min="1950-01-01">

                                    <v-spacer></v-spacer>
                                    <v-btn text
                                           color="primary"
                                           @click.prevent="menu = false">
                                        Cancel
                                    </v-btn>
                                    <v-btn text
                                           color="primary"
                                           @click.prevent="$refs.menu.save(formData.receipt_date)">
                                        OK
                                    </v-btn>
                                </v-date-picker>
                            </v-menu>
                        </div>-->
                        <div class="mb-3 col-12 col-md-6">
                            <label for="receiptStyle" class="form-label">收據格式 <span class="text-danger">*</span></label>
                            <select class="form-select" id="receiptStyle" v-model="formData.style_num" required
                                    :disabled="mode=='view'||mode=='edit'">
                                <option value="">請選擇</option>
                                <option v-for="r in receiptStyles" :key="r.num" :value="r.num">
                                    {{r.name}}
                                </option>
                            </select>
                        </div>
                        <div class="mb-3 col-12 col-md-6">
                            <label  for="total_amt" class="form-label" >應收總金額</label>
                            <v-text-field v-model="formData.total_amt"  id="total_amt"
                                          :disabled="mode=='view'||mode=='edit'||formData.source=='1'"></v-text-field><!--從報名來的不能改總金額-->
                        </div>
                        <div class="mb-3 col-12 col-md-6">
                            <label for="alreadyAmt" class="form-label">已收總金額</label>
                            <v-text-field v-model="alreadyAmt" id="alreadyAmt"
                                          :disabled="mode=='view'||mode=='edit'||formData.source=='1'"></v-text-field>
                        </div>
                        </div>
                    </div>
            </div>
            <div class="card">
                <div class="card-title bg-primary text-white">
                    <h4>收據明細</h4>
                </div>
                <div class="card-body">
                    <div class="row" v-show="mode!='view'">
                        <div class="col-12 col-md-2">
                            <label for="" class="form-label">抬頭 <span class="text-danger">*</span></label>
                            <v-text-field v-model="newDetail.title"></v-text-field>
                        </div>
                        <div class="col-12 col-md-2">
                            <label for="" class="form-label">金額 <span class="text-danger">*</span></label>
                            <v-text-field v-model="newDetail.amt"></v-text-field>
                        </div>
                        <div class="col-12 col-md-2">
                            <label for="" class="form-label">開立日期 <span class="text-danger">*</span></label>
                            <v-menu ref="menu"
                                    v-model="menu"
                                    :close-on-content-click="false"
                                    :return-value.sync="newDetail.receipt_date"
                                    transition="scale-transition"
                                    offset-y
                                    min-width="auto"
                                    :disabled="mode=='view'">
                                <template v-slot:activator="{ on, attrs }">
                                    <v-text-field v-model="newDetail.receipt_date"
                                                  prepend-icon="mdi-calendar"
                                                  readonly
                                                  v-bind="attrs"
                                                  v-on="on"></v-text-field>
                                </template>
                                <v-date-picker v-model="newDetail.receipt_date"
                                               :active-picker.sync="activePicker"
                                               :max="(new Date(Date.now() - (new Date()).getTimezoneOffset() * 60000)).toISOString().substring(0, 10)"
                                               min="1950-01-01">

                                    <v-spacer></v-spacer>
                                    <v-btn text
                                           color="primary"
                                           @click.prevent="menu = false">
                                        Cancel
                                    </v-btn>
                                    <v-btn text
                                           color="primary"
                                           @click.prevent="$refs.menu.save(newDetail.receipt_date)">
                                        OK
                                    </v-btn>
                                </v-date-picker>
                            </v-menu>
                        </div>
                        <div class="col-12 col-md-6">
                            <label for="" class="form-label">功德項目</label>
                            <v-text-field v-model="newDetail.receipt_item"> </v-text-field>
                        </div>
                    <!--</div>
                    <div class="row" v-show="mode!='view'">-->
                        <div class="col-12 col-md-8">
                            <label for="" class="form-label">地址</label>
                            <v-text-field v-model="newDetail.addr" ></v-text-field>
                        </div>
                        <div class="col-12 col-md-2">
                            <label for="" class="form-label">經手人 <span class="text-danger">*</span></label>
                            <v-text-field v-model="newDetail.caseofficer" ></v-text-field>
                        </div>
                        <div class="col-12 col-md-2">
                            <button class="btn btn-info" @click.prevent="addDetail">新增</button>
                        </div>
                    </div>
                        <div class="row" v-for="d in formDetail">
                            <div class="row">
                                <div class="col-12 col-md-2">
                                    <v-text-field v-model="d.title" label="抬頭" :disabled="mode=='view'"></v-text-field>
                                </div>
                                <div class="col-12 col-md-2">
                                    <v-text-field v-model="d.amt" label="金額" :disabled="mode=='view'"></v-text-field>
                                </div>
                                <div class="col-12 col-md-2">
                                   <!-- <v-text-field v-model="d.receipt_date" label="開立日期" :disabled="mode=='view'"></v-text-field>-->
                                    <v-menu ref="menu"
                                            v-model="menu"
                                            :close-on-content-click="false"
                                            :return-value.sync="d.receipt_date"
                                            transition="scale-transition"
                                            offset-y
                                            min-width="auto"
                                            :disabled="mode=='view'">
                                        <template v-slot:activator="{ on, attrs }">
                                            <v-text-field v-model="d.receipt_date"
                                                          prepend-icon="mdi-calendar"
                                                          readonly
                                                          label="開立日期"
                                                          v-bind="attrs"
                                                          v-on="on"></v-text-field>
                                        </template>
                                        <v-date-picker v-model="d.receipt_date"
                                                       :active-picker.sync="activePicker"
                                                       :max="(new Date(Date.now() - (new Date()).getTimezoneOffset() * 60000)).toISOString().substring(0, 10)"
                                                       min="1950-01-01">

                                            <v-spacer></v-spacer>
                                            <v-btn text
                                                   color="primary"
                                                   @click.prevent="menu = false">
                                                Cancel
                                            </v-btn>
                                            <v-btn text
                                                   color="primary"
                                                   @click.prevent="$refs.menu.save(d.receipt_date)">
                                                OK
                                            </v-btn>
                                        </v-date-picker>
                                    </v-menu>

                                </div>
                                <div class="col-12 col-md-6">
                                    <v-text-field v-model="d.receipt_item" label="功德項目" :disabled="mode=='view'"></v-text-field>
                                </div>
                                <div class="col-12 col-md-8">
                                    <v-text-field v-model="d.addr" label="地址" :disabled="mode=='view'"></v-text-field>
                                </div>
                                <div class="col-12 col-md-2">
                                    <v-text-field v-model="d.caseofficer" label="經手人" :disabled="mode=='view'"></v-text-field>
                                </div>
                                <div class="col-12 col-md-2">
                                    <v-text-field v-model="d.receipt_no" label="收據編號" v-show="mode=='view'" :disabled="mode=='view'||mode=='edit'"></v-text-field>
                                </div>
                            </div>

                        </div>
                        <div class="row">
                            <div class="col-12 col-md-2">
                                收據已開立總金額 {{ countReceiptTotal() }}
                            </div>
                        </div>
                    </div>

                </div>
            <div class="card">
                <div class="card-footer">
                    <button class="btn btn-primary" @click.prevent="saveReceipt" v-show="mode!='view'">存檔</button>
                    <button class="btn btn-primary" @click.prevent="printReceipt" v-show="mode=='view'">列印</button>
                    <button class="btn btn-primary" @click.prevent="closeWindow('')">取消</button>
                </div>
            </div>
        </div>


        <v-dialog v-model="order_dialog.show" max-width="800px">
            <v-card>
                <v-card-title class="grey lighten-2">
                    選擇報名表
                    <v-spacer></v-spacer>
                    <v-btn icon @click.prevent="order_dialog.show = false">
                        <v-icon>mdi-close</v-icon>
                    </v-btn>
                </v-card-title>

                <v-card-text class="pt-4">
                    <v-row>
                        <v-col cols="12">
                            <v-text-field v-model="order_dialog.search"
                                          label="依法會名稱搜尋報名表 (按 Enter 搜尋)"
                                          prepend-icon="mdi-magnify"
                                          @keydown.enter.prevent="searchOrders"
                                          clearable></v-text-field>
                        </v-col>
                    </v-row>

                    <v-data-table :headers="order_dialog.headers"
                                  :items="order_dialog.list"
                                  :loading="order_dialog.loading"
                                  item-key="num"
                                  :server-items-length="order_dialog.count"
                                  :page.sync="order_dialog.page"
                                  :items-per-page.sync="order_dialog.pageSize"
                                  :options.sync="options"
                                  class="elevation-1"
                                  @click:row="selectOrder">
                        <template v-slot:item.actions="{ item }">
                            <v-btn small color="primary" @click.stop="selectOrder(item)">
                                選擇
                            </v-btn>
                        </template>
                    </v-data-table>
                </v-card-text>
            </v-card>
        </v-dialog>

        <v-snackbar v-model="snackbar.show" :timeout="3000" top color="error">
            {{ snackbar.text }}
            <template v-slot:action="{ attrs }">
                <v-btn dark text v-bind="attrs" @click="snackbar.show = false">關閉</v-btn>
            </template>
        </v-snackbar>
    </div>

</template>

<script>
    module.exports = {
        name:"receipt_component",
        props: {
            num: {
                type: Number // num
            },
            mode: {
                type: String,
                default:''
            }
        },
        data() {
            return {
                snackbar: {
                    show: false,
                    text: ''
                },
                options: { multiSort: false },
                formData: {
                    source: '',
                    order_no: '',
                    receipt_date: null,
                    receipt_style: "",
                    total_amt: 0,
                    style_num: 0,
                    num:0
                },
                alreadyAmt:0,
                order_no_need:false,
                newDetail: {
                    num:0,
                    receipt_no: "",
                    title: "",
                    addr: "",
                    amt: 0,
                    caseofficer: "",
                    receipt_date: "",
                    receipt_item:"",
                },
                formDetail: [
                ],
                sources: {
                    '1': '活動/法會',
                    '2':'其他'
                },
                orders: [],
                receiptStyles:[],
                activePicker: null,
                date: null,
                menu: false,
                order_dialog: {
                    show: false,
                    search: '',
                    headers: [
                        { text: '活動/法會', value: 'subject' },
                        { text: '單號', value: 'order_no' },
                        { text: '姓名', value: 'u_name' },
                    ],
                    loading: false,
                    items: [],
                    list: [],
                    count: 0,
                    page: 1,
                    pageSize: 10,
                    options: { multiSort: false },
                }
            }
        },
        watch: {
            options: {
                handler() {
                    this.searchOrders()
                },
                deep: true,
            },
            formData: {
                handler(newVal) {
                    if (newVal.source === "1") {
                        this.order_no_need = true;
                    } else {
                        this.order_no_need = false;
                    }
                },
                deep:true,
            },
            num: {
                handler(newVal) {
                    console.log("........", newVal)
                    this.formData = {
                        source: '',
                        order_no: '',
                        receipt_date: null,
                        receipt_style: "",
                        total_amt: 0,
                        style_num: 0,
                        num: 0
                    }
                    if ((this.mode == "view"||this.mode=="edit")&&newVal!=0) {
                        this.getReceipt();
                    }
                },
                deep: true,
                immediate: true 
            }
        },
        methods: {
            showPickOrder() {
                this.order_dialog.show = true;
            },
            selectOrder(item) {
                //console.log(item)
                this.formData.order_no = item.order_no
                this.formData.total_amt = item.amt
                this.order_dialog.show=false
            },
            searchOrders() {
                const { sortBy, sortDesc, page, itemsPerPage } = this.options
                //page = this.data_table.page;
                let self = this;
                const params = {
                    page: page == null ? 1 : page, pageSize: itemsPerPage == null ? 10 : itemsPerPage,
                    sortBy: sortBy[0], sortDesc: sortDesc[0],
                };
                this.order_dialog.loading = true
                let search = { subject: this.order_dialog.search }
                //sessionStorage.setItem('orderpage', clearpage ? '1' : page);
                axios
                    .post(HTTP_HOST + 'api/order/GetList', search, { params: params })
                    .then(response => {
                        console.log(response)
                        self.order_dialog.list = response.data.list
                        self.order_dialog.count = response.data.count;
                        self.order_dialog.loading = false

                        //sessionStorage.setItem("order_list_cache", dataToStore);
                    })
                    .catch(error => console.log(error))
            },
            getReceiptStyles() {
                axios
                    .post(HTTP_HOST + 'api/receipt/GetAllStyle')
                    .then(response => {
                        let data = response.data.list;
                        this.receiptStyles = data;
                    });
            },
            getOrders() {

            },
            getReceipt() {
                let search = { num: this.num }
                axios
                    .post(HTTP_HOST + 'api/receipt/GetData', search)
                    .then(response => {
                        let data = response.data.data;
                        this.formData = {
                            source: data.source,
                            order_no: data.order_no,
                            receipt_date: data.receipt_date,
                            style_num: data.style_num,
                            total_amt: data.total_amt,
                            num: data.num
                        }
                        data.orderdetails.forEach(x => {
                            x.records.forEach(y => {
                                this.alreadyAmt = Number(this.alreadyAmt) + (isNaN(y.price) ? 0 : Number(y.price))
                            })
                        })
                   
                        this.formDetail=[...data.receipt_detail]
                    })
                    .catch(error => console.log(error))
            },
            addDetail() {
                if (this.newDetail.title === "") {
                    this.showSnack("抬頭必須填寫")
                    return
                }
                if (this.newDetail.amt ===0 ) {
                    this.showSnack("金額不可為0")
                    return
                }
                if (this.newDetail.receipt_date === "") {
                    this.showSnack("開立日期必須填寫")
                    return
                }
                if (this.newDetail.caseofficer === "") {
                    this.showSnack("經手人必須填寫")
                    return
                }
                this.formDetail.push({ ...this.newDetail })
                this.newDetail = {
                    receipt_no: "",
                    title: "",
                    addr: "",
                    amt: 0,
                    caseofficer: "",
                    num: 0,
                    receipt_num: 0,
                    receipt_date: "",
                    receipt_item:""
                  
                }
            },
            showSnack(message) {
                this.snackbar.text = message;
                this.snackbar.show = true;
               
            },
            saveReceipt() {
                if (this.formDetail.length === 0) {
                    this.showSnack("沒有明細資料");
                    return false;
                }
                if (this.formData.source == "") {
                    this.showSnack("請選擇來源");
                    return false;
                }
                if (this.formData.source === "1" && this.formData.order_no== "") {
                    this.showSnack("請選擇活動/法會");
                    return false;
                }
                //if (this.formData.receipt_date == "") {
                //    this.showSnack("請選擇開立日期");
                //    return false;
                //}
                if (this.formData.style_num==0) {
                    this.showSnack("請選擇收據格式");
                    return false;
                }
                if (this.formData.total_amt == 0) {
                    this.showSnack("總金額不可為0");
                    return false;
                }
                let total=0
                let detail = []
                this.formDetail.forEach(x => {
                    detail.push({ ...x })
                    total=total+Number(x.amt)
                })
                if (total > this.formData.total_amt) {
                    this.showSnack("收據總金額超過應收總金額!!!");
                    return false
                }
                let master = {
                    ...this.formData, list: detail
                }
                let targetUrl = "SaveReceiptWithDetail";
                if (this.mode === "edit")
                    targetUrl = "UpdateReceiptWithDetail";
                axios
                    .post(HTTP_HOST + `api/receipt/${targetUrl}`, master)
                    .then(response => {
                        this.snackbar.text = response.data.message;
                        this.snackbar.show = true;
                        if (response.data.result == "Y") {
                            this.closeWindow('reload');
                        }
                    })
                    .catch(error => console.log(error))
            },
            closeWindow(param) {
                //this.num=0
                this.formDetail.length = 0
                this.formData = {
                    source: '',
                    order_no: '',
                    receipt_date: null,
                    receipt_style: "",
                    total_amt: 0,
                    style_num: 0,
                    num: 0
                }
                this.$emit('close-dialog', param);
            },
            printReceipt() {
                try {
                    let searchData = {num:this.formData.num}
                    axios
                        .post(HTTP_HOST + 'api/receipt/PrintReceipt', searchData, { responseType: 'blob' })
                        .then(response => {
                            // 1. Create a dynamic URL object from the binary blob
                            const blob = new Blob([response.data], {
                                type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
                            });
                            const fileUrl = window.URL.createObjectURL(blob);

                            // 2. Create a temporary 'a' element to trigger download
                            const link = document.createElement('a');
                            link.href = fileUrl;

                            // 3. Set desired file name
                            link.setAttribute('download', `${searchData.activity_num}_${searchData.mode}.docx`);

                            // 4. Append, click and cleanup
                            document.body.appendChild(link);
                            link.click();

                            document.body.removeChild(link);
                            window.URL.revokeObjectURL(fileUrl); // Free up memory allocation
                        })

                } catch (error) {
                    console.error('Error downloading the file:', error);
                    //alert('Failed to download file.');
                    this.showSnack('Failed to download file.');
                } finally {
                    this.loading = false;
                }
            },
            countReceiptTotal() {
                let total=0
                this.formDetail.forEach(x => {
                    total=Number(total)+Number(x.amt)
                })
                return total
            }
        },
        deactivated() {
            this.formData = {
                source: '',
                order_no: '',
                receipt_date: null,
                receipt_style: "",
                total_amt: 0,
                style_num: 0,
                num: 0
            }
            this.formDetail.length = 0;
            this.alreadyAmt = 0;
            console.log("deactivated");
        },
        activated() {
            this.getReceiptStyles();
            this.formData = {
                source: '',
                order_no: '',
                receipt_date: null,
                receipt_style: "",
                total_amt: 0,
                style_num: 0,
                num: 0
            }
            this.formDetail.length = 0;
            this.alreadyAmt = 0;
        },
        beforeUnmount() {
            console.log("beforeUnmount");
            this.formData = {
                source: '',
                order_no: '',
                receipt_date: null,
                receipt_style: "",
                total_amt: 0,
                style_num: 0,
                num: 0
            }
            this.formDetail.length = 0;
            this.alreadyAmt = 0;
        },
        mounted() {
            this.getReceiptStyles();
            this.formData = {
                source: '',
                order_no: '',
                receipt_date: null,
                receipt_style: "",
                total_amt: 0,
                style_num: 0,
                num: 0
            }
            this.formDetail.length = 0;
            this.alreadyAmt = 0;
            
        },
        computed: {
            pageCount() {
                return Math.ceil(this.order_dialog.count / (this.options.itemsPerPage??10))
            },
        }
    }
  </script>