<template>
    <div class="p-3">
        <div class="bg-fff flex1 ov-hd d-flex flex-cln">
            <div class="d-flex a-c pd-16 border-bottom">
                <div class="f-s-20 c-333 f-w-7 mr-10">新增套餐</div>
                <el-button @click="router.go(-1)" type="primary" text>
                    <el-icon>
                        <Back />
                    </el-icon>
                    返回上一级
                </el-button>
            </div>
            <div class="flex1 over-auto">
                <el-form ref="formRef" label-width="auto" label-position="top" :model="form" :rules="rules">
                    <div class="pd-16 border-bottom">
                        <el-form-item prop="items">
                            <div class="flex1 ov-hd">
                                <template v-if="!form.items.length">
                                    <add-btn @click="showSelectItems = true" content="选择检测项目"></add-btn>
                                </template>
                                <template v-else>
                                    <div class="d-flex mb-10">
                                        <div class="flex1 ov-hd f-s-16 c-333 f-w-5">已选择{{ form.items.length }}项检测项目，合计{{ totalCountPrice }}元</div>
                                        <div>
                                            <el-button @click="addItems" type="primary" text>
                                                <el-icon><Plus /></el-icon>
                                                继续添加
                                            </el-button>
                                            <el-button @click="clearItemsAdd" type="danger" text>
                                                <el-icon><DeleteFilled /></el-icon>
                                                清空重选
                                            </el-button>
                                        </div>
                                    </div>
                                    <vxe-table ref="tableRightRef" border :data="form.items" :column-config="{ resizable: true }">
                                        <vxe-column type="seq" width="60" title="序号" align="center" />
                                        <vxe-column title="检测项目" align="center" field="name" min-width="100" :formatter="colNoData" />
                                        <vxe-column title="单价（元、批次）" align="center" field="price" min-width="100" :formatter="colNoData" />
                                        <vxe-column title="备注" align="center" field="description" min-width="100" :formatter="colNoData" />
                                        <vxe-column title="操作" align="center">
                                            <template #default="{ $rowIndex }">
                                                <el-button type="danger" @click="deleteRow($rowIndex)" text>删除</el-button>
                                            </template>
                                        </vxe-column>
                                    </vxe-table>
                                </template>
                            </div>
                        </el-form-item>
                    </div>
                    <div class="pd-16 border-bottom ov-hd">
                        <div class="info-title mb-10">套餐基本信息</div>
                        <el-row :gutter="90">
                            <el-col :span="8">
                                <el-form-item label="套餐名称" prop="name">
                                    <el-input v-model="form.name" clearable placeholder="请输入套餐名称"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="套餐类型" prop="publicFlag">
                                    <el-select v-model="form.publicFlag" clearable placeholder="请选择套餐类型">
                                        <el-option v-for="item in dm_package_type" :key="item.value" :label="item.label" :value="item.value"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="制定规则" prop="permitType">
                                    <el-radio-group v-model="form.permitType" @change="changePermitType">
                                        <el-radio v-for="item in dm_permit_type" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
                            <template v-if="form.permitType === '1'">
                                <el-col :span="8">
                                    <el-form-item label="适用类型" prop="permit">
                                        <el-select v-model="form.permit" @change="changePermit" clearable multiple placeholder="请选择适用类型">
                                            <el-option v-for="item in vip_level" :key="item.value" :label="item.label" :value="item.value"></el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                            </template>
                            <template v-if="form.permitType === '2'">
                                <el-col :span="8">
                                    <el-form-item label="适用企业" prop="permitCpys">
                                        <SearchSelect v-model="form.permitCpys" :limit="1" :params="{ reviewStatus: '1' }" @changeItem="changeItemCpy"></SearchSelect>
                                    </el-form-item>
                                </el-col>
                            </template>
                            <el-col :span="8">
                                <el-form-item label="检测周期" prop="period">
                                    <el-input v-model.number="form.period" clearable placeholder="请输入检测周期">
                                        <template #suffix>个工作日</template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="上架数量" prop="totalCount">
                                    <el-input v-model.number="form.totalCount" clearable placeholder="请输入上架数量"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="检测类型" prop="testType">
                                    <el-select v-model="form.testType" clearable placeholder="请选择检测类型">
                                        <el-option v-for="item in dm_test_type" :key="item.value" :label="item.label" :value="item.value"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="执行标准" prop="standard">
                                    <el-input type="textarea" v-model="form.standard" placeholder="请输入执行标准" :rows="4" show-word-limit maxlength="100"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="送样信息" prop="description">
                                    <el-input type="textarea" v-model="form.description" placeholder="请输入送样信息" :rows="4" show-word-limit maxlength="100"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="购买须知" prop="purchaseNotes">
                                    <el-input type="textarea" v-model="form.purchaseNotes" placeholder="请输入购买须知" :rows="4" show-word-limit maxlength="100"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="失效日期" prop="validUntil">
                                    <el-date-picker v-model="form.validUntil" value-format="YYYY-MM-DD" type="date" clearable placeholder="请选择失效日期"></el-date-picker>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="标签" prop="tags">
                                    <el-input v-model="form.tags" maxlength="20" clearable placeholder="请输入标签"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="封面图" prop="coverImg">
                                    <imageUpload v-model="form.coverImg" :limit="1" isString :isShowTip="false"></imageUpload>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="产品图" prop="proImg">
                                    <imageUpload v-model="form.proImg" :limit="5" isString :isShowTip="false"></imageUpload>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </div>
                    <div v-if="form.permit?.length" class="pd-16">
                        <div class="info-title mb-10">套餐价格确认</div>
                        <vxe-table ref="tableRightRef" border :data="form.priceDetail" :column-config="{ resizable: true }">
                            <vxe-column type="seq" width="60" title="序号" align="center" />
                            <vxe-column v-if="form.permitType === '2'" title="企业名称" align="center" min-width="100" :formatter="colNoData">
                                <template #default="{ row, $rowIndex }">{{ row?.cpyName || form?.permitCpyNames[$rowIndex] || '-' }}</template>
                            </vxe-column>
                            <vxe-column title="适用类型" align="center" field="memberLevelName" min-width="100" :formatter="colNoData" />
                            <vxe-column title="折扣标准" align="center" min-width="100">
                                <template #default="{ row }">{{ NP.times(row?.memberDiscount, 10) }}折</template>
                            </vxe-column>
                            <vxe-column title="折扣后售价" align="center" field="name" min-width="100">
                                <template #default="{ row }">{{ NP.times(row?.originalPrice, row?.memberDiscount) }}元</template>
                            </vxe-column>
                            <vxe-column title="最终售价" align="center" min-width="100">
                                <template #default="{ row }">
                                    <el-input v-model="row.price" clearable placeholder="请输入最终售价">
                                        <template #suffix>元</template>
                                    </el-input>
                                </template>
                            </vxe-column>
                        </vxe-table>
                    </div>
                </el-form>
            </div>
            <div class="d-flex a-c j-c pd-16">
                <el-button @click="router.go(-1)">取消</el-button>
                <el-button @click="save" color="#0079fe">保存</el-button>
                <el-button @click="submitGround" type="warning">立即上架</el-button>
            </div>
        </div>
    </div>
    <TransferItems v-if="showSelectItems" ref="TransferItemsRef" v-model:show="showSelectItems" @change="changeItems" :items="form.items"></TransferItems>
</template>

<script setup name="Menus-form" lang="ts">
import { AddBtn, SearchSelect } from '@/views/models';
import { TransferItems } from '../../models';
import NP from 'number-precision';
import { colNoData } from '@/utils/noData';
import { vipDiscountList } from '@/api/cdt/discount';
import { debounce } from 'lodash';
import { addTestPackage, editTestPackage, getTestPackage, getTestPackageItems, testPackageSale } from '@/api/cdt/menus';
const { query }: any = useRoute();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { dm_package_type, dm_permit_type, vip_level, dm_test_type } = toRefs<any>(proxy?.useDict('dm_package_type', 'dm_permit_type', 'vip_level', 'dm_test_type'));
// 字典
const TransferItemsRef = ref<any>();
const router = useRouter();
const showSelectItems = ref(false);
const form = ref<any>({
   items: [],
   priceDetail: [],
   permitCpys: []
});
const rules = reactive<any>({
    items: [
        { required: true,  type: 'array', message: '请选择检测项目', trigger: 'change' },
    ],
    name: [
        { required: true, message: '请输入套餐名称', trigger: 'blur' }
    ],
    publicFlag: [
        { required: true, message: '请选择套餐类型', trigger: 'change' }
    ],
    permitType: [
        { required: true, message: '请选择制定规则', trigger: 'change' }
    ],
    permit: [
        { required: true, message: '请选择适用类型', trigger: 'change' }
    ],
    permitCpys: [
        {type: 'array', required: true, message: '请选择适用企业', trigger: 'change' }
    ],
    period: [
        { required: true, message: '请输入检测周期', trigger: 'blur' }
    ],
    totalCount: [
        { required: true, message: '请输入上架数量', trigger: 'blur' }
    ],
    testType: [
        { required: true, message: '请选择检测类型', trigger: 'change' }
    ],
    standard: [
        { required: true, message: '请输入执行标准', trigger: 'blur' }
    ],
    description: [
        { required: true, message: '请输入送样信息', trigger: 'blur' }
    ],
    purchaseNotes: [
        { required: true, message: '请输入购买须知', trigger: 'blur' }
    ],
    validUntil: [
        { required: true, message: '请选择失效日期', trigger: 'change' }
    ],
    coverImg: [
        { required: true, message: '请上传封面图', trigger: 'blur' }
    ],
    proImg: [
        { required: true, message: '请上传产品图', trigger: 'blur' }
    ]
});
const formRef = ref<any>();
const save = debounce(() => {
   submitSever(0)
}, 500)
const submitGround = debounce(async () => {
   await formRef.value.validate()
   submitSever(1)
}, 500)
const submitSever = async (type) => {
   proxy.$modal.loading('提交中...');
   const params = {
        ...form.value,
        testItemIds: form.value.items.map((item: any) => item.id),
        priceDetail: form.value.priceDetail.map((item: any) => {
            return {
                memberLevel: item.memberLevel,
                memberDiscount: item.memberDiscount,
                originalPrice: item.originalPrice,
                memberLevelName: item.memberLevelName,
                price: item.price
            }
        })
   }
   delete params.items;
   let res = null;
   if (form.value.id) {
       res = await editTestPackage(params).finally(() => {
           proxy.$modal.closeLoading();
       });
   } else {
       res = await addTestPackage(params).finally(() => {
           proxy.$modal.closeLoading();
       });
   }
   if (!res || res.code !== 200) return;
   if (type) {
    await testPackageSale(res.data?.id || form.value?.id);
   }
    proxy.$modal.msgSuccess('提交成功!')
    router.go(-1);
};
// 合计价格
const totalCountPrice = computed(() => {
    return form.value.items.reduce((total: number, item: any) => {
        return NP.plus(total, item.price);
    }, 0);
});
const changeItems = (val: any) => {
    form.value.items = val;
    const standards = val.map((item: any) => item.standardForPackage).join(',').split(',');
    // 去重
    form.value.standard = Array.from(new Set(standards)).join(',');
    changePermitType();
};
const changeItemCpy = (val: any[]) => {
   const permits = val.map((item: any) => item.vipLevel || '0');
    form.value.permit = [...permits];
    changePermitCpys(val);
};
// 继续添加方法
const addItems = () => {
    // 保留之前选中
    console.log(form.value.items);
    
    showSelectItems.value = true;
};
// 清空重选方法
const clearItemsAdd = () => {
    form.value.items = [];
    TransferItemsRef.value?.clearAll();
    showSelectItems.value = true;
};
// 删除行
const deleteRow = (index: number) => {
    form.value.items.splice(index, 1);
    // changePermit()
    if (form.value.permitType === '1') {
        changePermit(form.value.permit);
    } else if (form.value.permitType === '2') {
        changePermitCpys(form.value.permitCpys);
    }
};
const discounts = ref<any>([]);
const getDiscount = async () => {
    // 获取折扣
    const res = await vipDiscountList({ pageSize: 1000, pageNum: 1 });
    if (!res || res.code !== 200) return;
    discounts.value = res.rows;
};
const changePermit = (val: string[]) => {
    form.value.priceDetail = discounts.value.filter(({ level }) => val.includes(level + '')).map(item => {
        return {
            ...item,
            memberLevel: item.level,
            memberDiscount: item.discount,
            memberLevelName: item.name,
            originalPrice: totalCountPrice.value,
            price: NP.times(item.discount, totalCountPrice.value) || undefined
        };
    });
};
const changePermitCpys = (vals: any[]) => {
    form.value.priceDetail = vals.map(item => {
        const discountItem = getDiscountItem(item.vipLevel || '0');
        return {
            cpyName: item.cpyName,
            memberLevelName: discountItem?.name,
            memberLevel: discountItem?.level,
            memberDiscount: discountItem?.discount,
            originalPrice: totalCountPrice.value,
            price: NP.times(discountItem?.discount, totalCountPrice.value) || undefined
        };
    });
};
// 获取discountsItem
const getDiscountItem = (val: string) => {
    return discounts.value.find(item => +item.level === +val);
};
const changePermitType = () => {
    form.value.permit = [];
    form.value.permitCpys = [];
    form.value.priceDetail = [];
};
const getDetail = async () => {
    proxy?.$modal.loading('加载中...');
    const res = await getTestPackage(query?.id).finally(() => {
        proxy?.$modal.closeLoading();
    });
    if (!res || res.code !== 200) return;
    form.value = {
        ...res.data,
        items: [],
    };
    getItems();
};
const getItems = async () => {
    const res = await getTestPackageItems({
        pageNum: 1,
        pageSize: 1000,
        packageId: query?.id
    });
    if (!res || res.code !== 200) return;
    form.value.items = res.rows;
};
onMounted(() => {
    getDiscount();
    if (query?.id) {
        getDetail();
    }
});
</script>
