<template>
    <div class="app-container">

        <!-- 查询和其他操作 -->
        <div class="filter-container">
            <el-select v-model="listQuery.channel" style="width: 160px" class="filter-item" placeholder="请选择渠道"
                 clearable  filterable >
        <el-option v-for="item in channels" :key="item.id" :label="item.name" :value="item.id"/>
      </el-select>
            <el-input v-model="listQuery.name" clearable class="filter-item" style="width: 200px;" placeholder="请输入优惠券标题" />

            <el-select v-model="listQuery.discountType" clearable style="width: 200px" class="filter-item"
                placeholder="请选择抵用类型">
                <el-option v-for="type in discountTypeData" :key="type.value" :label="type.label" :value="type.value" />
            </el-select>

            <el-select v-model="listQuery.status" clearable style="width: 200px" class="filter-item" placeholder="请选择优惠券状态">
                <el-option v-for="type in statusOptions" :key="type.value" :label="type.label" :value="type.value" />
            </el-select>

            <el-button v-permission="['GET /admin/dyCoupon/list']" class="filter-item" type="primary" icon="el-icon-search"
                @click="handleFilter">查找</el-button>
            <el-button v-permission="['POST /admin/dyCoupon/create']" class="filter-item" type="primary" icon="el-icon-edit"
                @click="handleCreate">添加</el-button>
            <!-- <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button> -->
        </div>

        <!-- 查询结果 -->
        <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>

            <el-table-column align="center" label="抖音侧ID" prop="couponMetaId">
                <template slot-scope="scope">
                    <div v-if="scope.row.discountType != 4">{{ scope.row.couponMetaId }}</div>
                    <div v-else><el-tag>无需同步抖音</el-tag></div>
                </template>
            </el-table-column>
            <el-table-column align="center" label="渠道" min-width="90" prop="channel">
            <template slot-scope="scope">
                <el-tag type="success">
                    {{ channelsFilter(scope.row.channel) }}
                </el-tag>
            </template>
            </el-table-column>
            <el-table-column align="center" label="优惠券名称" prop="name">
                <template slot-scope="scope">
                    <span v-if="scope.row.discountType != 4">{{ scope.row.name }}</span>
                    <span v-else style="color:red">{{ scope.row.name }}</span>
                </template>
            </el-table-column>

            <el-table-column align="center" label="券场景描述" prop="sceneDesc" />

            <!-- <el-table-column align="center" label="领取须知" prop="receiveDesc" /> -->
            <el-table-column align="center" label="可领取时间" prop="receiveBeginTime" width="180px">
                <template slot-scope="scope">
                    {{ scope.row.receiveBeginTime }}<br />{{ scope.row.receiveEndTime }}
                </template>
            </el-table-column>

            <el-table-column align="center" label="有效期类型" prop="validType">
                <template slot-scope="scope">{{ scope.row.validType == 1 ? "固定时间过期" : "领取后多久过期" }}</template>
            </el-table-column>

            <el-table-column align="center" label="有效期" prop="validBeginTime" width="180px">
                <template slot-scope="scope">
                    <span v-if="scope.row.validType == 1">
                        {{ scope.row.validBeginTime }}<br />{{ scope.row.validEndTime }}
                    </span>
                    <span v-else>领后{{ scope.row.validDuration }}天</span>
                </template>
            </el-table-column>

            <el-table-column align="center" label="最低消费" prop="minPayAmount">
                <template slot-scope="scope">
                    <span v-if="scope.row.discountType != 4">满{{ scope.row.minPayAmount }}元可用</span>
                    <span v-else style="color:red">可代金额 随订单商品</span>
                </template>
            </el-table-column>

            <el-table-column align="center" label="减免金额" prop="discountAmount">
                <template slot-scope="scope">
                    <span v-if="scope.row.discountType == 1">立减{{ scope.row.discountAmount }}元</span>
                    <span v-if="scope.row.discountType == 2">满减{{ scope.row.discountAmount }}元</span>
                    <span v-if="scope.row.discountType == 4" style="color:red">满减随订单商品售价</span>
                </template>
            </el-table-column>

            <!-- <el-table-column align="center" label="每人限领" prop="limit">
                <template slot-scope="scope">{{ scope.row.limit != 0 ? scope.row.limit : "不限" }}</template>
            </el-table-column> 

            <el-table-column align="center" label="优惠券类型" prop="type">
                <template slot-scope="scope">{{ scope.row.type | formatType }}</template>
            </el-table-column>-->

            <el-table-column align="center" label="商品使用范围" prop="goodsType">
                <template slot-scope="scope">{{ scope.row.goodsType | formatGoodsType }}</template>
            </el-table-column>


            <el-table-column align="center" label="优惠券数量" prop="stockNumber">
                <template slot-scope="scope">共{{ scope.row.stockNumber }} <br />余{{ scope.row.remainingNumber }} </template>
            </el-table-column>

            <el-table-column align="center" label="状态" prop="status">
                <template slot-scope="scope">
                    <el-tag :type="scope.row.status == 2 ? 'danger' : ''">{{ scope.row.status | formatStatus
                    }}</el-tag></template>
            </el-table-column>

            <el-table-column align="center" label="操作" width="300" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button v-permission="['GET /admin/coupon/read']" type="primary" size="mini"
                        @click="handleDetail(scope.row)">详情</el-button>
                    <el-button v-if="scope.row.status == 1 && scope.row.discountType != 4"
                        v-permission="['GET /admin/dyCoupon/increase']" type="success" size="mini"
                        @click="handleIncrease(scope.row)">追加库存</el-button>
                    <el-button v-if="scope.row.status == 1 && scope.row.discountType != 4"
                        v-permission="['POST /admin/dyCoupon/allocation']" type="info" size="mini"
                        @click="handleAllocate(scope.row)">授权达人</el-button>
                    <!-- <el-button v-permission="['POST /admin/dyCoupon/delete']" type="danger" size="mini"
                        @click="handleDelete(scope.row)">下架</el-button> -->
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
            @pagination="getList" />

        <!-- 添加或修改对话框 -->
        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width='800px'>
            <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="100px"
                style="margin-left:20px;">

            <el-form-item label="渠道" prop="channel">
                <el-select v-model="dataForm.channel" style="width: 160px" class="filter-item" placeholder="请选择渠道"
                 clearable >
                    <el-option v-for="item in channels" :key="item.id" :label="item.name" :value="item.id"/>
                 </el-select>
            </el-form-item>

                <el-form-item label="优惠券名称" prop="name">
                    <el-input v-model="dataForm.name" oninput="if(value.length>20) value=value.slice(0,20)"
                        placeholder="优惠券显示名称" />
                </el-form-item>
                <el-form-item label="券场景描述" prop="sceneDesc">
                    <el-input v-model="dataForm.sceneDesc" oninput="if(value.length>20) value=value.slice(0,20)"
                        placeholder="券场景描述--如立减100" />
                </el-form-item>
                <el-form-item label="领取须知" prop="receiveDesc">
                    <el-input v-model="dataForm.receiveDesc" oninput="if(value.length>20) value=value.slice(0,20)"
                        placeholder="领取须知，长度20以内，用于展示当前优惠券的领取规则说明" />
                </el-form-item>
                <el-form-item label="发放须知" prop="sendDesc">
                    <el-input v-model="dataForm.sendDesc" oninput="if(value.length>20) value=value.slice(0,20)"
                        placeholder="优惠券发放时候的描述文案，对主播、短视频制作人等展示" />
                </el-form-item>
                <el-form-item label="使用须知" prop="consumeDesc">
                    <el-input v-model="dataForm.consumeDesc" oninput="if(value.length>20) value=value.slice(0,20)"
                        placeholder="20字以内 优惠券发放时候的描述文案，仅对主播、短视频制作人等展示，用户不可见，比如可向主播传递当前优惠券的稀有程度或口播建议" />
                </el-form-item>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="优惠类型" prop="discountType">
                            <el-select v-model="dataForm.discountType" style="width:100%">
                                <el-option v-for="type in discountTypeData" :key="type.value" :label="type.label"
                                    :value="type.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item :label="dataForm.discountType == 1 ? '立减券' : '满减券'" prop="discountAmount">
                            <el-input v-model="dataForm.discountAmount">
                                <template slot="append">元</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="最低消费" prop="minPayAmount" placeholder="如果选择满减，请输入最低消费金额">
                            <el-input v-model="dataForm.minPayAmount">
                                <template slot="append">元</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="优惠券数量" prop="stockNumber">
                            <el-input v-model="dataForm.stockNumber">
                                <template slot="append">张</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="生效时间" required>
                    <el-col :span="11">
                        <el-date-picker v-model="dataForm.receiveBeginTime" type="datetime" placeholder="选择生效开始日期"
                            value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%;" />
                    </el-col>
                    <el-col :span="2" class="line">至</el-col>
                    <el-col :span="11">
                        <el-date-picker v-model="dataForm.receiveEndTime" type="datetime" placeholder="选择生效结束日期"
                            value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%;" />
                    </el-col>
                    <div style="font-size: 11px;line-height: 13px;color:red">
                        券模板生效时间（即可领取开始时间），和当前时间最大时间差为30天，小于当前时间，立即生效<br />
                        券模板过期时间（即可领取结束时间），必须大于生效开始时间，大于当前时间，和当前时间最大时间差为60天</div>
                </el-form-item>


                <el-form-item label="有效时间" required>
                    <el-radio-group v-model="dataForm.validType">
                        <el-radio-button :label="1">券有效起止时间</el-radio-button>
                        <el-radio-button :label="2">领券后有效时长</el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item v-show="dataForm.validType === 2">
                    <el-input v-model="dataForm.validDuration" placeholder="领取后，多久过期，最大日期为30天">
                        <template slot="append">天</template>
                    </el-input>
                </el-form-item>
                <el-form-item v-show="dataForm.validType === 1">
                    <el-col :span="11">
                        <el-date-picker v-model="dataForm.validBeginTime" type="datetime" placeholder="选择日期"
                            value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%;" />
                    </el-col>
                    <el-col :span="2" class="line">至</el-col>
                    <el-col :span="11">
                        <el-date-picker v-model="dataForm.validEndTime" type="datetime" placeholder="选择日期"
                            value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%;" />
                    </el-col>
                </el-form-item>
                <el-form-item label="商品限制范围">
                    <el-radio-group v-model="dataForm.goodsType">
                        <el-radio-button :label="0">全场通用</el-radio-button>
                        <el-radio-button :label="2">指定商品</el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item v-show="dataForm.goodsType === 1">
                    <el-cascader :options="categoryList" expand-trigger="hover" style="width:100%" clearable
                        @change="handleTypeChange" />
                </el-form-item>
                <el-form-item v-show="dataForm.goodsType === 2">
                    <el-cascader v-model="dataForm.goodsId" :options="goodsList" expand-trigger="hover"
                        :props="{ expandTrigger: 'hover', value: 'value', label: 'label', multiple: true }"
                        style="width:100%" clearable @change="handleTypeChange" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button v-if="dialogStatus == 'create'" type="primary" @click="createData">确定</el-button>
                <!--<el-button v-else type="primary" @click="updateData">修改</el-button>-->
            </div>
        </el-dialog>

        <!-- 追加优惠券库存 -->
        <el-dialog title="追加优惠券库存" :visible.sync="increaseFormVisible" width='600px'>
            <el-form ref="increaseForm" :rules="rules" :model="increaseForm" status-icon label-position="left"
                label-width="150px" style="margin-left:20px;">
                <el-form-item label="追加优惠券数量" prop="increase">
                    <el-input v-model="increaseForm.increase" type="number" placeholder="请输入追加的优惠券数量" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="increaseFormVisible = false">取消</el-button>
                <el-button type="primary" @click="increaseCoupon">确定</el-button>
            </div>
        </el-dialog>

        <!-- 优惠券分配 -->
        <el-dialog title="优惠券分配" :visible.sync="allocationFormVisible" width='860px'>
            <div style="display: flex;padding:5px 0;align-items: center;">
                <div style="line-height: 36px;width:100px">达人信息</div>
                <!-- <el-cascader style="width:100%" placeholder="请选择达人信息" v-model="allocationForm.talentIdList"
                    :options="providers" :props="{
                        expandTrigger: 'hover',
                        value: 'id',
                        label: 'name',
                        multiple: true,
                    }" expand-trigger="hover" clearable />
                <el-button type="primary" style="margin-left: 5px;" @click="btnAllcationConfirm">确定选中</el-button> -->
                <el-input :readonly="true" @click.native="handleSelectTalent" v-model="allocationForm.talentIdList"
                    style="width:100%;" />
            </div>

            <div style="margin: 5px 0 2px 0;color:red">
                1.分配只是给与达人发券能力及上限，并不对库存进行预扣减<br />
                2.每个达人的库存是独立的，总库存被客户领完后即止，哪怕还有剩余可用数量<br />
                3.如果达人已分配过此优惠券，再次分配会在原有数量上追加可发送上限
            </div>
            <el-table :data="talentAllocationList" border highlight-current-row height="400px">
                <el-table-column label="达运" prop="provider"  width="90px" />
                <el-table-column label="达人id" prop="talentId" width="120px" />
                <el-table-column label="达人昵称" prop="talentNick" />
                <el-table-column label="发券权限" prop="status" width="80px">
                    <template slot-scope="scope">
                        <el-tag :type="scope.row.status == 1 ? '' : 'danger'">{{ scope.row.status == 1 ? '上架' : '下架'
                        }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="优惠券数量" prop="couponNumber">
                    <template slot-scope="scope">
                        优惠券数量:{{ scope.row.couponNumber }} <br />剩余可分配数:{{ scope.row.couponRemaining }}
                    </template>
                </el-table-column>
                <el-table-column label="分配数量" prop="allocationNumber">
                    <template slot-scope="scope">
                        <el-input type="number" :disabled="scope.row.status == 2" v-model="scope.row.allocationNumber"
                            clearable />
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="80px">
                    <template slot-scope="scope">
                        <el-button type="text" icon="el-icon-remove" size="mini" @click="deltempListRow(scope.$index)">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div slot="footer" class="dialog-footer">
                <el-button @click="allocationFormVisible = false">取消</el-button>
                <el-button type="primary" @click="allocationCoupon">确定</el-button>
            </div>
        </el-dialog>


        <!-- 选择达人 -->
        <selectTalentRef ref="selectTalentRef" />

    </div>
</template>
  
  
<script>
import { listCoupon, createCoupon, increaseCoupon, deleteCoupon, talentAllocationInfo, allocationCoupon } from "@/api/dyCoupon";
import { talentList, selectProvider } from "@/api/dyApp";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination
import { listGoods3 } from "@/api/goods";
import { defaultCouponTypeOptions, ArrayToObject } from "@/api/enumUtils"
import selectTalentRef from "@/views/dy/compent/selectTalentRef.vue";
import {allChannel} from "@/api/channel";

const discountTypeData = [
    {
        label: "立减券",
        value: 1,
    },
    {
        label: "满减券",
        value: 2,
    },
    //  {
    //     label: "权益券",
    //     value: 3,
    // },
    // {
    //     label: "中介代金券",
    //     value: 4,
    // },
];


const defaultStatusOptions = [
    {
        label: "审核中",
        value: 0,
    },
    {
        label: "正常",
        value: 1,
    },
    {
        label: "过期",
        value: 2,
    }, {
        label: "已下架",
        value: 3,
    }, {
        label: "审核失败",
        value: 4,
    },
];

export default {
    name: "dyCoupon",
    components: { Pagination, selectTalentRef },
    filters: {
        formatType(type) {
            for (let i = 0; i < defaultCouponTypeOptions.length; i++) {
                if (type === defaultCouponTypeOptions[i].value) {
                    return defaultCouponTypeOptions[i].label
                }
            }
            return ''
        },
        formatGoodsType(goodsType) {
            if (goodsType === 0) {
                return "全场通用";
            } else if (goodsType === 1) {
                return "指定分类";
            } else if (goodsType === 2) {
                return "指定商品";
            }
        },
        formatStatus(status) {
            if (status === 0) {
                return "审核中";
            } else if (status === 1) {
                return "正常";
            } else if (status === 2) {
                return "过期";
            } else if (status === 3) {
                return "已下架";
            } else {
                return "审核失败";
            }
        },
    },
    data() {
        var validDate = (rule, value, callback) => {
            if (this.dataForm.validType != 1) {
                callback();
            } else {
                if (this.dataForm.validBeginTime == null || this.dataForm.validEndTime == null)
                    callback(new Error("请选择券有效期"));
            }
        };
        var validDuration = (rule, value, callback) => {
            if (this.dataForm.validType == 2 && (this.dataForm.validDuration == null || this.dataForm.validDuration == '' || this.dataForm.validDuration < 1 || this.dataForm.validDuration > 30)) {
                callback(new Error("请选择有效的券期限"));
            } else {
                callback();
            }
        };
        var stockNumberValidate = (rule, value, callback) => {
            if (this.dataForm.stockNumber == '' || this.dataForm.stockNumber < 1) {
                callback(new Error("请输入整数库存"));
            } else {
                callback();
            }
        };
        var discountValidate = (rule, value, callback) => {
            if (this.dataForm.discountAmount == '' || this.dataForm.discountAmount < 1) {
                callback(new Error("请输入整数优惠金额"));
            } else {
                callback();
            }
        };
        var minPayAmountValidate = (rule, value, callback) => {
            if (this.dataForm.discountType == 2 && (this.dataForm.minPayAmount == '' || this.dataForm.minPayAmount < 1 || this.dataForm.minPayAmount < this.dataForm.discountAmount)) {
                callback(new Error("请输入正确的满减金额"));
            } else {
                callback();
            }
        };


        return {
            channels:[],
            discountTypeData: discountTypeData,
            statusOptions: Object.assign({}, defaultStatusOptions),
            defaultTypeOptions: ArrayToObject(defaultCouponTypeOptions),
            list: [],
            goodsList: [], // 三级商品
            categoryList: [], // 商品分类
            total: 0,
            listLoading: true,
            listQuery: {
                page: 1,
                limit: 20,
                channel:null,
                name: undefined,
                status: undefined,
                discountType: undefined,
                sort: "update_time",
                order: "desc",
            },
            dataForm: {
                id: undefined,
                name: undefined,
                sceneDesc: undefined,
                receiveDesc: undefined,
                stockNumber: 0,
                discountType: 1, //1：立减券；2：满减券 
                discountAmount: 0,
                minPayAmount: 0,
                limit: 1,
                goodsType: 0,
                goodsValue: [],
                validType: 2,
                validDuration: 0,
                validBeginTime: null,
                validEndTime: null,
                goodsId: null, // 指定商品控件 绑定值
                goodsCate: null, // 指定分类
                channel:null,
                consumePath: "pages/ucenter/coupon/couponGoods?id="
            },
            dialogFormVisible: false,
            dialogStatus: "",
            textMap: {
                update: "编辑",
                create: "创建",
            },
            increaseForm: {
                couponId: '',
                increase: ''
            },
            increaseFormVisible: false,
            allocationFormVisible: false,
            allocationForm: {
                talentIdList: [],
                couponId: ''
            },
            providers: [],//供应商+达人 
            talentAllocationList: [],//分配情况
            rules: {
                merchantMetaNo: [
                    { required: true, message: "优惠券模板号不能为空", trigger: "blur" },
                ],
                name: [
                    { required: true, message: "优惠券标题不能为空", trigger: "blur" },
                ],
                minPayAmount: [{ validator: minPayAmountValidate, required: true, message: "最低消费不能为空", trigger: "blur" }],
                validDuration: [
                    { validator: validDuration, required: true, message: "请输入领券后有效期限", trigger: "blur" },
                ],
                discountAmount: [
                    { validator: discountValidate, required: true, message: "折扣或立减不能为空", trigger: "blur" },
                ],
                discountType: [
                    { required: true, message: "优惠券类型不能为空", trigger: "blur" },
                ],
                stockNumber: [
                    { validator: stockNumberValidate, required: true, message: "优惠券数量不能为空", trigger: "blur" },
                ],
                validBeginTime: [
                    { validator: validDate, required: true, message: "优惠券数量不能为空", trigger: "blur" },
                ],
                increase: [
                    { required: true, message: "优惠券数量不能为空", trigger: "blur" },
                ],
                receiveBeginTime: [
                    { required: true, message: "生效开始时间不能为空", trigger: "blur" },
                ],
                receiveEndTime: [
                    { required: true, message: "生效结束时间不能为空", trigger: "blur" },
                ],
                consumeDesc: [
                    { required: true, message: "使用须知不能为空", trigger: "blur" },
                ],
                channel:[
                    { required: true, message: "渠道不能为空", trigger: "blur" },
                ]
            },
            downloadLoading: false, 
        };
    },
    created() {
        this.getList();
        this.handleListGoods();
        this.getchannels();
    },
    methods: { 
        channelsFilter(value) {
            if(value==null||value==undefined){
                return null;
            }
            const rs = this.channels.filter((item) => {
                return item.id === value;
            });
            if (rs != null && rs.length > 0) {
                return rs[0].name;
            }
        },
        getchannels(){
            allChannel().then((res) => {
                let temp =[];
             res.data.data.forEach(e=>{
                if(e.name.indexOf('抖音')!=-1 && e.name.indexOf('原生') ==-1){
                    temp.push(e);
                }
             })
              this.channels=temp;
            });
        },
        handleSelectTalent() {
            //console.info(this.dxForm)
            this.$refs.selectTalentRef.load(0);
        },
        confirmSelectTalent(talents) {
            this.allocationForm.talentIdList = talents;
            console.info(talents)
            this.btnAllcationConfirm();
            // this.selectedTalent = "选中" + this.dxForm.douyinIdList.length + "个达人";
        },
        getList() {
            this.listLoading = true;
            listCoupon(this.listQuery)
                .then((response) => {
                    this.list = response.data.data.list;
                    this.total = response.data.data.total;
                    this.listLoading = false;
                })
                .catch(() => {
                    this.list = [];
                    this.total = 0;
                    this.listLoading = false;
                });
        },
        handleIncrease(row) {
            this.increaseForm.increase = '';
            this.increaseForm.couponId = row.id;
            this.increaseFormVisible = true;
        },
        increaseCoupon() {
            this.$refs["increaseForm"].validate((valid) => {
                if (valid) {
                    increaseCoupon(this.increaseForm).then(res => {
                        this.increaseFormVisible = false;
                        this.$notify.success({
                            title: "成功",
                            message: "追加优惠券成功",
                        });
                        this.getList();
                    })
                }
            });
        },
        // 三级商品分类
        handleListGoods() {
            listGoods3({ channelId: 26 })
                .then((res) => {
                    this.goodsList = res.data.data.goodsList;
                    this.categoryList = res.data.data.categoryList;
                })
                .catch(() => { });
        },
        handleTypeChange(value) {
            this.dataForm.goodsValue = []; //只允许一个
            if (value.length > 0) {
                if (this.dataForm.goodsType == "1") {
                    this.dataForm.goodsId = [];
                    this.dataForm.goodsValue.push(value[value.length - 1]);
                }
                else {
                    this.dataForm.goodsId.forEach((item) => {
                        this.dataForm.goodsValue.push(item[2]);
                    });
                }
            }

            console.log(this.dataForm.goodsValue);
        },
        handleFilter() {
            this.listQuery.page = 1;
            this.getList();
        },
        handleCreate() {
            this.resetForm();
            this.dialogStatus = "create";
            this.dialogFormVisible = true;
            this.$nextTick(() => {
                this.$refs["dataForm"].clearValidate();
            });
        },
        createData() {
            this.$refs["dataForm"].validate((valid) => {
                if (valid) {
                    createCoupon(this.dataForm)
                        .then((response) => {
                            this.list.unshift(response.data.data);
                            this.dialogFormVisible = false;
                            this.$notify.success({
                                title: "成功",
                                message: "创建优惠券成功",
                            });
                        })
                        .catch((response) => {
                            this.$notify.error({
                                title: "失败",
                                message: response.data.errmsg,
                            });
                        });
                }
            });
        },
        handleDelete(row) {
            this.$confirm("下架将导致所有未试用优惠券失效，确定下架吗?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                deleteCoupon(row)
                    .then((response) => {
                        this.$notify.success({
                            title: "成功",
                            message: "下架优惠券成功",
                        });
                        const index = this.list.indexOf(row);
                        this.list.splice(index, 1);
                    })
                    .catch((response) => {
                        this.$notify.error({
                            title: "失败",
                            message: response.data.errmsg,
                        });
                    });
            });
        },
        handleDetail(row) {
            this.$router.push({
                path: "dyCouponDetail",
                query: { id: row.id },
            });
        },
        handleAllocate(row) {
            this.allocationForm = {
                talentIdList: [],
                couponId: row.id,
                stockNumber: row.stockNumber
            }
            this.allocationFormVisible = true;
            this.talentAllocationList = [];
            if (this.providers.length == 0)
                this.getProviderList();
        },
        allocationCoupon() {
            //分配给主播的券库存的发放上限，不得超过券模板最大库存
            if (this.talentAllocationList.length == 0) {
                this.$notify.warning({
                    title: "失败",
                    message: "请选择达人",
                });
                return;
            }

            for (var i = 0; i < this.talentAllocationList.length; i++) {
                let item = this.talentAllocationList[i];
                console.info(item)
                if (item.allocationNumber == null || item.allocationNumber < 1) {
                    this.$notify.warning({
                        title: "失败",
                        message: "达人【" + item.talentNick + "】的分配数量为空或负值。",
                    });
                    return;
                }
                //console.info(item.allocationNumber + item.couponNumber)
                //达人可以分配总数 是否大于优惠券的总数
                if ((parseInt(item.allocationNumber) + parseInt(item.couponNumber)) > this.allocationForm.stockNumber) {
                    this.$notify.warning({
                        title: "失败",
                        message: "达人【" + item.talentNick + "】的总分配数量不能大于优惠券总数。",
                    });
                    return;
                }
            }
            this.$confirm("请仔细核对分配数据，确定逻辑分配吗?", "提示", {
                confirmButtonText: "分配",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                allocationCoupon(this.talentAllocationList).then(res => {
                    this.$notify.success({
                        title: "成功",
                        message: "分配成功",
                    });
                    this.allocationFormVisible = false;
                }).catch(res => {
                    this.$notify.success({
                        title: "错误",
                        message: res.data.errmsg,
                    });
                })
            });
        },
        btnAllcationConfirm() {
            if (this.allocationForm.talentIdList.length == 0) {
                this.$notify.error({
                    title: "失败",
                    message: "请选择达人",
                });
                return;
            }
            talentAllocationInfo(this.allocationForm).then(res => {
                this.talentAllocationList = res.data.data;
            })
        },
        deltempListRow(index) {
            console.log(index);
            this.talentAllocationList.splice(index, 1);
        },
        getProviderList() {
            console.info('getProviderList')
            selectProvider().then(res => {
                this.providers = res.data.data;
            })
        },
        resetForm() {
            this.dataForm = {
                id: undefined,
                name: undefined,
                merchantMetaNo: '',
                sceneDesc: undefined,
                receiveDesc: undefined,
                stockNumber: 0,
                discountType: 1, //1：立减券；2：满减券 
                discountAmount: 0,
                minPayAmount: 0,
                limit: 1,
                goodsType: 0,
                goodsValue: [],
                validType: 2,
                validDuration: '',
                validBeginTime: null,
                validEndTime: null,
                goodsId: null, // 指定商品控件 绑定值
                goodsCate: null, // 指定分类
                consumePath: "pages/ucenter/coupon/couponGoods?id="
            };
        },
    },
};
</script> 
  
  
<style>
.fixed-width .el-button--mini {
    width: auto;
    min-width: 60px;
}

.el-button+.el-button {
    margin-left: 0px;
}

.line {
    text-align: center;
}</style>