<template>
    <div class="agent_page adffc">
        <div class="ap_title">{{ title }}</div>
        <el-form :model="queryParams" ref="queryRef" label-width="98px" style="margin-top: 20px;">
          <el-row>
            <el-col :span="6" style="padding-right: 20px;">
                <el-form-item label="商品类型">
                    <el-select style="width: 100%" v-model="queryParams.type" placeholder="请选择商品类型" filterable clearable>
                        <el-option label="基础版" :value="1"/>
                        <el-option label="专业版" :value="2"/>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="6" style="padding-right: 20px;">
                <el-form-item label="商品状态">
                    <el-select style="width: 100%" v-model="queryParams.status" placeholder="请选择商品状态" filterable clearable>
                        <el-option label="未上架" :value="0"/>
                        <el-option label="已上架" :value="1"/>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item style="display: flex;">
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                <el-button type="primary" @click="getList">查询</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="ap_line"></div>
        <div class="add adf">
            <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增商品</el-button>
        </div>
        <el-table :data="dataList" border cell-class-name="vertical-top-cell" v-loading="loading" empty-text="暂无商品" max-height="578px" style="margin-top: 12px;">
            <el-table-column label="序号" width="50">
                <template #default="scope">
                    {{ scope.$index + 1 }}
                </template>
            </el-table-column>
            <el-table-column label="商品ID" prop="id"></el-table-column>
            <el-table-column label="商品类型" prop="xx">
                <template #default="{ row }">{{ typeCfg[row.type] }}</template>
            </el-table-column>
            <el-table-column label="问卷次数" prop="frequency">
                <template #default="{ row }">{{ row.frequency==11?'10次以上':(row.frequency+'次') }}</template>
            </el-table-column>
            <el-table-column label="价格(元)" prop="price">
                <template #default="{ row }">{{ row.frequency==11?(row.price+'/次'):row.price }}</template>
            </el-table-column>
            <el-table-column label="有效期" prop="valid">
                <template #default="{ row }">{{ row.valid }}年</template>
            </el-table-column>
            <el-table-column label="创建时间" prop="createDate"></el-table-column>
            <el-table-column label="销量" prop="sales"></el-table-column>
            <el-table-column label="上架状态" prop="status">
                <template #default="{ row }">
                    <el-switch v-model="row.status" active-color="#33A7A7" inactive-color="#B9C0C8" @change="e=>statusChange(e,row)"></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
                <template #default="scope">
                    <el-button link type="text" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button link type="text" size="mini" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-row style="display: flex;justify-content: center;">
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryParams.page"
                :page-sizes="[5, 10, 20, 50]"
                :page-size="10"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                v-show="total > 0">
            </el-pagination>
        </el-row>
        <el-dialog width="40%" :visible.sync="show" :title="dialogTitle" @close="cancel">
            <el-form ref="goodRef" :model="goodForm" :rules="goodRules" label-width="100px" style="width: 90%;margin: 0 auto;">
                <el-form-item label="商品类型" prop="" class="red">
                    <div class="gtype adfac">
                        <div class="gtype-pre" :class="{'active':tidx===1}" @click="changeType(1)">
                            基础版
                            <img src="@/assets/images/agent/good_type_selected.png" v-if="tidx===1">
                        </div>
                        <div class="gtype-pre" :class="{'active':tidx===2}" @click="changeType(2)">
                            专业版
                            <img src="@/assets/images/agent/good_type_selected.png" v-if="tidx===2">
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="问卷次数" prop="frequency">
                    <el-select v-model="goodForm.frequency" placeholder="请选择问卷次数" style="width:100%">
                        <el-option label="1次" value="1"></el-option>
                        <el-option label="5次" value="5"></el-option>
                        <el-option label="10次" value="10"></el-option>
                        <el-option label="10次以上" value="11"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="价格" prop="price">
                    <el-input type="number" v-model="goodForm.price" placeholder="请输入次数价格"></el-input>
                </el-form-item>
                <el-form-item label="有效期" prop="valid">
                    <el-select v-model="goodForm.valid" placeholder="请选择有效期" style="width:100%">
                        <el-option label="购买成功后，1年内有效" value="1"></el-option>
                        <el-option label="购买成功后，2年内有效" value="2"></el-option>
                        <el-option label="购买成功后，3年内有效" value="3"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商品状态" prop="status">
                    <el-radio-group v-model="goodForm.status">
                        <el-radio :label="1">上架</el-radio>
                        <el-radio :label="0">下架</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <div class="demo-drawer__footer" style="display: flex;justify-content: end;">
                <el-button :loading="buttonLoading" type="primary" @click="submitForm">保 存</el-button>
                <el-button @click="cancel" style="margin-right: 5%;">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script setup name="">
    import { ref, getCurrentInstance, onMounted } from 'vue'
    import { 
        getCommodityList,
        addCommodity,
        updateCommodity,
        getCommodityInfo,
        deleteCommodity 
    } from '@/api/agent/indexTwo.js'
    const { proxy } = getCurrentInstance();
    const title = proxy.$route.meta.title;
    const queryParams = ref({
        page: 1,
        limit: 10,
        type: '',
        status: ''
    })
    const typeCfg = ref({
        1:'基础版',
        2:'专业版',
        3:'专家版'
    })
    const queryRef = ref(null)
    const dataList = ref([])
    const total = ref(0)
    const loading = ref(false)
    const buttonLoading = ref(false)
    const show = ref(false)
    const tidx = ref(1)
    const dialogTitle = ref('新增商品')
    const goodForm = ref({
        id:'',
        type:1,
        frequency:'',
        price:'',
        valid:'',
        status:1
    })
    const goodRef = ref(null)
    const goodRules = ref({
        frequency: [
            { required: true, message: '请选择问卷次数', trigger: 'change' },
        ],
        price: [
            { required: true, message: '请输入价格', trigger: 'blur' },
        ],
        valid: [
            { required: true, message: '请选择有效期', trigger: 'change' },
        ],
        status: [
            { required: true, message: '请选择商品状态', trigger: 'change' },
        ],
    })

    const resetQuery = () => {
        proxy.$refs.queryRef.resetFields();
        queryParams.value = {
            type: '',
            status: ''
        }
        getList();
    }

    const changeType = (idx) => {
        tidx.value = idx;
        goodForm.value.type = idx;
    }

    const getList = async () => {
        let query = {...queryParams.value};
        loading.value = true;
        const res = await getCommodityList(query);
        dataList.value = res.data.list;
        dataList.value.forEach(item=>{
            item.status = item.status==1?true:false;
        })
        total.value = res.data.total;
        loading.value = false;
    }
    const handleSizeChange = (e)=>{
        queryParams.value.limit = e;
        getList();
    }
    const handleCurrentChange = (e)=>{
        queryParams.value.page = e;
        getList();
    }

    const reset = () => {
        goodForm.value = {
            id:'',
            type:1,
            frequency:'',
            price:'',
            valid:'',
            status:1
        };
        proxy.resetForm("goodRef");
    }
    const handleAdd = () => {
        reset();
        dialogTitle.value = "新增商品";
        show.value = true;
    }
    const handleEdit = (row) => {
        reset();
        getCommodityInfo(row.id).then(response => {
            goodForm.value = response.data;
            goodForm.value.frequency+='';
            goodForm.value.valid+='';
            tidx.value = +goodForm.value.type??1;
            dialogTitle.value = "编辑商品";
            show.value = true;
        });
    }

    const submitForm = () => {
        proxy.$refs.goodRef.validate((valid) => {
            if (valid) {
                buttonLoading.value = true;
                if(goodForm.value.id){
                    updateCommodity(goodForm.value).then((res)=>{
                        if(res.code!==0) return proxy.$message.error(res.msg);
                        buttonLoading.value = false;
                        show.value = false;
                        getList();
                    })
                }else{
                    addCommodity(goodForm.value).then((res)=>{
                        if(res.code!==0) return proxy.$message.error(res.msg);
                        buttonLoading.value = false;
                        show.value = false;
                        getList();
                    })
                }
            } else {
                return false;
            }
        });
    }
    const cancel = () => {
        show.value = false;
        reset();
    }

    async function handleDelete(row) {
        await proxy?.$modal.confirm('确认删除该商品吗？').finally(() => loading.value = false);
        let res = await deleteCommodity([row.id]);
        if (res.code === 0) proxy?.$modal.msgSuccess("删除成功");
        else return proxy?.$modal.msgError(res.msg);
        await getList();
    }

    function statusChange(e,row) {
        let data = JSON.parse(JSON.stringify(row));
        data.status = data.status?1:0;
        updateCommodity(data).then((res)=>{
            if(res.code!==0) return proxy.$message.error(res.msg);
            getList();
        })
    }

    onMounted(()=>{
        getList();
    })
</script>

<style scoped lang="scss">
    .agent_page{
        padding: 24px 16px;

        .add{
            margin-top: 16px;
            justify-content: flex-end;
        }

        .gtype{
            &-pre{
                width: 124px;
                height: 36px;
                border-radius: 6px;
                border: 1px solid #E5E7EB;
                font-family: PingFangSC, PingFang SC;
                font-weight: 400;
                font-size: 14px;
                color: #002846;
                line-height: 36px;
                text-align: center;
                position: relative;
                cursor: pointer;
                &:last-child{
                    margin-left: 20px;
                }
                &.active{
                    border: 1px solid #33A7A7;
                    color: #33A7A7;
                }
                img{
                    width: 27px;
                    height: 23px;
                    position: absolute;
                    right: 0;
                    bottom: 0;
                }
            }
        }
    }
</style>