<template>
    <div class="site-setting-wrap min-flex-right">
        <div class="pagePadding main-wrap">
            <p class="pageTitle bold">新增套餐</p>
            <div class="siteMessage flex-common" id="siteMessage2">
                <p class="littleTitle mb32">套餐信息</p>
                <el-form :model="siteForm" :rules="siteFormrules" ref="siteForm1">
                    <div class="flex-wrap">
                        <div class="flex-left">
                            <GuipFormItem column="column" class="mb24" label="套餐名称" :required="true">
                                <GuipInput slot="formDom" ref="GuipInput" column="column" v-model="siteForm.name"
                                    prop="name" placeholder="输入" />
                            </GuipFormItem>
                        </div>
                        <div class="flex-line"></div>
                        <div class="flex-right">
                            <GuipFormItem column="column" class="mb24" label="套餐价格" :required="true">
                                <GuipInput slot="formDom" ref="GuipInput" column="column" v-model="siteForm.price"
                                    prop="price" placeholder="输入" unit="元" />
                            </GuipFormItem>
                        </div>
                    </div>
                </el-form>
            </div>
            <div class="siteMessage flex-common" id="siteMessage2">
                <p class="littleTitle mb32">套餐项目</p>
                <el-form>
                    <div class="flex">
                        <div class="checkboxAll">
                            <el-checkbox @change="handleSelectAllChange1" v-model="selectAll"
                                :indeterminate="isIndeterminate">全选</el-checkbox>
                        </div>
                        <span class="totalCount">共{{ projectList.length }}条，已选{{ selectedCount }}条</span>
                    </div>

                    <div class="flex-between mb32 mt32">
                        <div class="tabProject flex">
                            <div :class="['tab-item ', projectSearchId == item.id ? 'active' : '']"
                                v-for="item in Object.values(projectTagData)" :key="item.name">{{ item.name }}</div>
                        </div>
                        <div class="right flex">
                            <GuipFormItem label="搜索项目">
                                <GuipInput slot="formDom" ref="GuipInput" width="280px" v-model="projectSearchName"
                                    placeholder="请输入" @blur="inputBlur">
                                    <img src="@/assets/input_search_ic.svg" slot="suffix" @click="handleClear" />
                                </GuipInput>
                            </GuipFormItem>
                        </div>
                    </div>
                    <GuipTable :tableData="sortedProjectList" style="width: 100%" ref="multipleTable" max-height="600px"
                        @selection-change="handleSelectionChange" :loading="loading">
                        <el-table-column type="selection" label="选择" width="150"></el-table-column>
                        <el-table-column prop="name" label="项目名称" min-width="150"></el-table-column>
                        <el-table-column label="次数" min-width="150px" prop="num">
                            <template slot-scope="scope">
                                <GuipInput width="90%" v-if="package_id && scope.row.num" v-model="scope.row.num"
                                    @change="changeNums(scope.row)" />
                                <GuipInput width="90%" v-else v-model="scope.row.unit_num"
                                    @change="changeNums(scope.row)" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="price" label="项目价格" min-width="150">
                            <template slot-scope="scope">
                                <GuipInput width="90%" v-model="scope.row.price" @change="changePrice(scope.row)" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="classify_id" label="分类" min-width="150">
                            <template slot-scope="scope">
                                <GuipSelect width="90%" v-model="scope.row.classify_id"
                                    @change="changeClassify(scope.row)" prop="classify_id" :options="projectTagData"
                                    valueKey="id" labelKey="name" />
                            </template>
                        </el-table-column>
                    </GuipTable>
                    <!-- <el-pagination background @size-change='handleSizeChange' @current-change='handleCurrentChange'
                        :current-page="currentPage" :page-size=pageSize layout="prev, pager, next,jumper"
                        :total="treatMentList.length">
                    </el-pagination> -->
                </el-form>
            </div>
        </div>
        <div class="register-btns">
            <GuipButton type="system" :btnstyle="{ width: '144px', height: '46px' }" @click="cancelClick">取消
            </GuipButton>
            <GuipButton type="primary" :btnstyle="{ width: '144px', height: '46px' }" @click="confirmClick">保存套餐
            </GuipButton>
        </div>
        <GuipDialog :dialogVisible="dialogVisible" :title="'新增套餐确认'" :show-close-button="true" width="599px"
            :show-cancel-button="true" @confirm="handleConfirm" @cancel="handleCancel" @close="handleClose"
            confirmText="确定新增">
            <div class="flex content">
                <span>套餐名称：</span>
                <span>{{ siteForm.name }}套餐</span>
            </div>
            <div class="flex content">
                <span>套餐价格：</span>
                <span>{{ siteForm.price }}元</span>
            </div>
            <div class="flex content">
                <span>套餐项目：</span>
                <div class="column">
                    <span v-for="item in selectedRows" :key="item.id">{{ item.name }} {{ item.nums }}次</span>
                </div>
            </div>
        </GuipDialog>
    </div>
</template>
<script>
import store from '../store';
import { mapState } from 'vuex';
import GuipFormItem from '@/components/GuipFormItem.vue';
import GuipTable from '@/components/GuipTable.vue';
import GuipDialog from '@/components/GuipDialog.vue';
import GuipInput from '@/components/GuipInput.vue';
import GuipButton from '@/components/GuipButton.vue';
import GuipSelect from '@/components/GuipSelect.vue';
export default {
    // 站点设置
    name: '',
    props: [''],
    components: {
        GuipFormItem,
        GuipInput,
        GuipDialog,
        GuipButton,
        GuipSelect,
        GuipTable

    },
    data() {
        return {
            dialogVisible: false,
            selectAll: false,
            selectedCount: 0,
            currentPage: 1,
            pageSize: 10,
            isIndeterminate: false,
            projectSearchName: '',
            projectSearchId: '0',
            loading: false,
            treatMentList: [],//疗程套餐项目
            projectList: [],//项目列表
            // {
            //     27:{
            //         classify_name:"针类",
            //         create_time:"2025-05-29 17:09:43",
            //         id:"1",
            //         name:"针刺",
            //         num:"2",
            //         pid:"1",
            //         price:"200.00",
            //         project_id:"27",
            //         sort:"1",
            //         status:"1",
            //     }
            // },
            selectedRows: [],
            siteForm: {
                create_time: "2025-05-29 17:08:29",
                depart_id: "1",
                doctor_id: "1",
                id: "1",
                name: "调理套餐",
                price: "1500.00",
                status: "1"
            },
            siteFormrules: {
                name: [
                    { required: true, message: '请输入套餐名称', trigger: 'blur' }
                ],
                price: [
                    { required: true, message: '请输入套餐价格', trigger: 'blur' }
                ],
            },
            projectTagData: [],
            package_id: '',
            doctor_id: '',
            depart_id: '',
        }
    },
   
    computed: {
        ...mapState(['pageTitle']),
        sortedProjectList() {
            return [...this.projectList].sort((a, b) => {
                // 有sort属性的排在前面
                if (a.sort && !b.sort) return -1;
                if (!a.sort && b.sort) return 1;
                // 如果都有sort属性，按sort值排序
                if (a.sort && b.sort) return a.sort - b.sort;
                // 都没有sort属性，保持原顺序
                return 0;
            });
        }
    },
    mounted() {
        const { package_id, doctor_id, depart_id } = this.$route.query; // 获取 doctorId 参数
        this.package_id = package_id;
        this.depart_id = depart_id;
        this.doctor_id = doctor_id;
        store.commit('SET_PAGETITLE', '基本设置');
        // 编辑
        if (package_id) {
            this.getInitData()
            return
        }
        this.fetchProjectData();
    },
    methods: {
      
        // 
        getInitData() {
            this.$http('POST', '/api/admin/get_project_package_info', {
                depart_id: this.depart_id,
                doctor_id: this.doctor_id,
                package_id: this.package_id
            }).then(response => {
                if (response.code == 0) {
                    this.siteForm = { ...response.data }
                    if (response.data?.project_list) {
                        this.treatMentList = Object.values(response.data.project_list)
                        this.fetchProjectData()
                    }
                }
            }).catch(error => {
                console.error(error, 'error')
            })
        },
        fetchProjectData() {
            this.$http('POST', '/api/admin/get_project_list', {
                depart_id: this.depart_id,
                doctor_id: this.doctor_id
            }).then(response => {
                if (response.code == 0) {
                    this.projectTagData = response.data.classify;//项目分类
                    this.projectList = Object.values(response.data.list).map(item => {
                        return {
                            ...item,
                            checked: false
                        }
                    });//项目列表

                    if (this.package_id) {//编辑状态
                        this.treatMentList.forEach(item => {
                            this.projectList.forEach(item1 => {
                                if (item.project_id == item1.id) {
                                    item1.checked = true;
                                    item1.num = item.num;
                                    item1.sort = item.sort;
                                    // 编辑的时候初始默认选中
                                    this.$nextTick(() => {
                                        this.$refs.multipleTable.$refs.guiptable.toggleRowSelection(item1, true);
                                        this.selectedRows.push(item1)
                                        this.updateSelectionState();
                                    });


                                }
                            })
                        })
                        // this.$nextTick(() => {
                        //     if (this.projectList.length >= 2) {
                        //         const defaultSelected = this.projectList.filter(item => item.checked === true);
                        //         defaultSelected.forEach(row => {
                        //             this.$refs.multipleTable.$refs.guiptable.toggleRowSelection(row, true);
                        //         });
                        //         this.selectedRows = defaultSelected;
                        //         this.updateSelectionState();
                        //     }
                        // });
                    }


                }
            }).catch(error => {
                console.error(error, 'error')
            })
        },
        changeChecked() {

        },
        inputBlur(val) {
            // 搜索项目
            this.$http('POST', '/supernew/ajax_get_type_batch_list', {
                projectSearchId: this.projectSearchId,
                search: this.projectSearchName
            }).then(response => {
                if (response.code == 0) {
                    this.dialogVisible = false;
                }

            }).catch(error => {
                console.error(error, 'error')
            })
            console.log(val, '----搜索');
        },
        updateSelectionState() {
            const allSelected = this.selectedRows.length === this.projectList.length;
            const noneSelected = this.selectedRows.length === 0;
            this.selectAll = allSelected;
            this.isIndeterminate = !noneSelected && !allSelected;
            this.selectedCount = this.selectedRows.length;
        },

        // 处理选择变化
        handleSelectionChange(rows) {
            this.selectedRows = rows;
            this.updateSelectionState();
        },
        handleSelectAllChange1(val) {
            if (val) {
                // 只选中未选中的行
                const unselectedRows = this.projectList.filter(
                    row => !this.selectedRows1.includes(row)
                );
                unselectedRows.forEach(row => {
                    this.$refs.multipleTable1.$refs.guiptable.toggleRowSelection(row, true);
                });
            } else {
                // 只取消已选中的行
                this.selectedRows.forEach(row => {
                    this.$refs.multipleTable1.$refs.guiptable.toggleRowSelection(row, false);
                });
            }
        },
        // 只有在原本套餐内的直接修改有效/ 否则无效；
        //  选中项目，进行保存套餐的时候，修改的项目信息才会有效；
        //  修改某一项就将此项默认成为选中
        // 修改次数
        changeNums(row) {
            if (row.sort) {
                this.editorProjectInfo({ num: row.num, project_id: row.id })
            } else {
                this.changeSelectStatus(row)
            }
        },
        // 修改分类
        changeClassify(row) {
            if (row.sort) {
                this.editorProjectInfo({ classify_id: row.classify_id, project_id: row.id })
            } else {
                this.changeSelectStatus(row)

            }
        },
        // 修改价格
        changePrice(row) {
            if (row.sort) {
                this.editorProjectInfo({ price: row.price, project_id: row.id })
            } else {
                this.changeSelectStatus(row)

            }
        },
        changeSelectStatus(row) {
            this.$refs.multipleTable.$refs.guiptable.toggleRowSelection(row, true);
            row.checked = true
            // 确保行被添加到 selectedRows 中
            if (!this.selectedRows.includes(row)) {
                this.selectedRows.push(row);
            }
            // 更新选择状态
            this.updateSelectionState();
        },
        // 修改项目信息
        editorProjectInfo(props) {
            // 
            this.$http('POST', '/api/admin/edit_project', {
                ...props,
                depart_id: this.depart_id,
                doctor_id: this.doctor_id,
            }).then(response => {
                if (response.code == 0) {
                    this.$Message.success('修改成功')
                    this.getInitData()
                }
            }).catch(error => {
                console.error(error, 'error')
            })
        },
        handleClose() {
            this.handleCancel()
        },
        handleCancel() {
            this.dialogVisible = false;
        },
        handleConfirm() {
            // 确认增加套餐接口
            this.$http('POST', '/supernew/ajax_get_type_batch_list', {

            }).then(response => {
                if (response.code == 0) {
                    this.dialogVisible = false;
                }

            }).catch(error => {
                console.error(error, 'error')
            })
        },
        handleClear(value) {
            // this.handleInput('')
            console.log(value, 'value===qinghcu');
        },
        handleSelectAllChange(val) {
            console.log(this.$refs.multipleTable, 'multipleTable-');
            if (val) {
                // 只选中未选中的行
                const unselectedRows = this.projectList.filter(
                    row => !this.selectedRows.includes(row)
                );
                unselectedRows.forEach(row => {
                    this.$refs.multipleTable.$refs.guiptable.toggleRowSelection(row, true);
                });
            } else {
                // 只取消已选中的行
                this.selectedRows.forEach(row => {
                    this.$refs.multipleTable.$refs.guiptable.toggleRowSelection(row, false);
                });
            }
        },

        // // 处理选择变化
        // handleSelectionChange(rows) {
        //     this.selectedRows = rows;

        //     // 更新全选按钮状态
        //     const allSelected = rows.length === this.treatMentList.length;
        //     const noneSelected = rows.length === 0;

        //     this.selectAll = allSelected;
        //     this.isIndeterminate = !noneSelected && !allSelected;
        // },
        handleSizeChange(val) {
            this.pageSize = val
            this.getData()
        },
        handleCurrentChange(val) {
            this.currentPage = val
            this.getData()
        },
        changeSelect(value) {
            console.log(value, '--');
        },
        btnClick() {
        },
        handleRemove(file, fileList) {
            console.log(file, fileList);
        },
        handlePreview(file) {
            console.log(file);
        },
        // 上传图片
        handleAvatarSuccess(res, file) {
            this.imageUrl1 = URL.createObjectURL(file.raw);
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        changeNormalWeixin() {

        },
        changeSelectWeixin(item, flag) {
            if (flag) {
                this.select_placeholder_weixin = this.options_weixin_null.desc;
                return
            }
            this.selectedItem = { ...item };
            console.log(this.selectedItem, 'this.selectedItem====');
        },
        //  销售渠道
        domain_radioChange(type) {
            console.log(type, '--');
        },
        onSwitchChange(data) {
            console.log(data, '---');
        },
        submitForm(form) {
            this.$refs[form].validate((valid) => {
                console.log(this[form], '======formxinxi');
                if (valid) {
                    alert('提交成功!');
                } else {
                    return false;
                }
            });
        },
        cancelClick() {
            this.$router.push({
                name: '医院信息',
                query: { doctor_id: this.doctor_id,depart_id:this.depart_id }
            })
        },
        confirmClick() {
            this.dialogVisible = true;
        }

    }
}
</script>
<style lang="scss" scoped>
.siteMessage {
    border-radius: 4px;
    transition: all .5s;
    border: 1px solid transparent;
}

.content {
    margin-top: 16px;
    color: #626573;
    letter-spacing: 0.08em;
    align-items: flex-start;
}

.register-btns {
    display: flex;
    flex-direction: row;
    justify-content: center;
    background: #FFFFFF;
    padding: 16px 0px;
    /* 蓝色阴影_常规 */
    box-shadow: 0px 4px 16px 0px rgba(17, 55, 143, 0.12);

    button:nth-child(1) {
        margin-right: 56px;
    }
}

.totalCount {
    font-size: 12px;
    font-weight: normal;
    line-height: 13px;
    letter-spacing: 0.08em;
    color: #8A9099;
    margin-left: 12px;
}

.tabProject {
    gap: 12px;

    .tab-item {
        height: 28px;
        min-width: 74px;
        display: flex;
        justify-content: center;
        align-items: center;
        box-sizing: border-box;
        padding: 4px 12px;
        gap: 4px;
        align-self: stretch;
        border-radius: 14px;
        background: #FFFFFF;
        box-sizing: border-box;
        border: 1px solid #DFE2E6;
        text-align: justify;
        letter-spacing: 0.08em;
        /* text/text_4 */
        color: #8A9099;
    }

    .active {
        color: #006AFF;
        border: none;
        background: #F2F3F5;
    }
}


.addStore {
    margin-top: 12px;
}

.qqCode-wrap {
    margin-bottom: 14px;

    .labelImg {
        opacity: .7;
        margin-left: 8px;
    }

    .avatar-uploader {
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        justify-content: flex-start;
        margin: 12px 0 8px;
    }

    .avatar-desc {
        text-align: left;
    }
}


.site-setting-wrap {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;

    .main-wrap {
        flex: 1;
    }
}

#siteMessage2 {
    margin: 12px 0;
}

.domain-wrap {
    .domain-item {
        margin-bottom: 10px;
    }


    .domain-item p:last-child {
        padding-left: 23px;
        color: #8A9099;
    }

    p {
        text-align: left;
        line-height: 18px;
        margin-bottom: 8px;
    }

    .domain-box {
        display: flex;
        flex-direction: column;
        justify-content: flex-start;
    }
}
</style>