<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item prop="title">
                <el-input v-model="queryParams.title" placeholder="请输入优惠券类型名称" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item prop="discountWay">
                <el-select v-model="queryParams.discountWay" placeholder="请选择优惠券类型" clearable>
                    <el-option v-for="dict in dict.type.coupon_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item prop="couponTypeThirdPartyId" label-width="90px">
                <el-select v-model="queryParams.couponTypeThirdPartyId" placeholder="请选择三方品牌" clearable>
                    <el-option v-for="third in thirdPartyList" :key="third.id" :label="third.name" :value="third.id" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="有效期开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd" v-hasPermi="['coupon:type:add']">新增</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <Page uri="/mapi/coupon/type/list" :request-params="queryParams" ref="pagination">
            <el-table-column label="编号" align="center" prop="id" width="80" />
            <el-table-column label="名称" align="center" prop="title" />
            <el-table-column label="图片" align="center" prop="imgUrl" width="80">
                <template slot-scope="scope">
                    <image-preview :src="scope.row.imgUrl" :width="60" :height="60" />
                </template>
            </el-table-column>
            <el-table-column label="优惠券类型" align="center" prop="discountWay" width="120">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.coupon_type" :value="scope.row.discountWay" />
                </template>
            </el-table-column>
            <el-table-column label="券值" align="center" prop="deductAmount" width="150">
                <template slot-scope="scope">
                    <span v-if="scope.row.discountWay == 0">满{{ scope.row.minAmount }}元减{{ scope.row.deductAmount }}元</span>
                    <span v-if="scope.row.discountWay == 1">满{{ scope.row.minAmount }}件减{{ scope.row.deductAmount }}件</span>
                    <span v-if="scope.row.discountWay == 2">折扣比例：{{ scope.row.discountRate }}%</span>
                </template>
            </el-table-column>
            <el-table-column label="有效期" align="center" prop="startDate" width="210">
                <template slot-scope="scope"> {{ scope.row.startDate }} ~ {{ scope.row.endDate }} </template>
            </el-table-column>

            <!-- <el-table-column label="是否单件抵扣券" align="center" prop="isUnique" width="150">
                <template slot-scope="scope">
                    <div v-if="scope.row.discountWay != '2'">
                        <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isUnique" />
                    </div>
                    <div v-if="scope.row.discountWay == '2'"><span>- -</span></div>
                </template>
            </el-table-column> -->
            <el-table-column label="发放方式" align="center" prop="sendWay" width="180">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.coupon_send_way" :value="parseInt(scope.row.sendWay)" />
                </template>
            </el-table-column>
            <el-table-column label="适用范围" align="center" prop="useScope" width="180">
                <template slot-scope="scope">
                    <span v-if="scope.row.useScope == 1">全部衣服</span>
                    <span v-if="scope.row.useScope == 2">指定衣服</span>
                </template>
            </el-table-column>
            <el-table-column label="优惠券库存" align="center" prop="couponStock" width="120" />
            <el-table-column label="已发放数量" align="center" prop="couponSendNum" width="120" />
            <el-table-column label="已使用数量" align="center" prop="couponUseNum" width="120" />
            <el-table-column label="三方品牌" align="center" prop="couponTypeThirdPartyId" width="120">
                <template slot-scope="scope">
                    <div v-for="third in thirdPartyList" :key="third.id">
                        <span v-if="scope.row.couponTypeThirdPartyId == third.id">{{ third.name }}</span>
                    </div>
                    <span v-if="!scope.row.couponTypeThirdPartyId">--</span>
                </template>
            </el-table-column>
            <el-table-column label="状态" align="center" prop="status" width="120">
                <template slot-scope="scope">
                    <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
                <template slot-scope="scope">
                    <el-button type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['coupon:type:edit']">修改</el-button>
                    <el-button type="text" icon="el-icon-s-shop" @click="handleSetClothItems(scope.row)" v-if="scope.row.useScope == 2" v-hasPermi="['coupon:type:list']">指定衣物</el-button>
                    <el-button type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['coupon:type:remove']">删除</el-button>
                </template>
            </el-table-column>
        </Page>

        <!-- 添加或修改优惠券类型对话框 -->
        <el-dialog :title="title" :visible.sync="open" size="50%" append-to-body>
            <el-row :gutter="15">
                <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                    <el-col :span="12">
                        <el-form-item label="优惠券类型" prop="discountWay" label-width="100px">
                            <el-select v-model="form.discountWay" placeholder="请选择优惠券类型" clearable :disabled="disabled" style="width: 300px" @change="changeDiscountWay">
                                <el-option v-for="dict in dict.type.coupon_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="名称" prop="title">
                            <el-input v-model="form.title" placeholder="请输入优惠券类型名称" maxlength="100" show-word-limit style="width: 300px" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="图片" prop="imgUrl">
                            <image-upload v-model="form.imgUrl" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="有效期" prop="duringDate">
                            <el-date-picker v-model="form.duringDate" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <!--                      <el-form-item label="是否单件抵扣券" label-width="150px" prop="isUnique" v-if="form.discountWay != '2'">-->
                        <!--                        <el-radio-group v-model="form.isUnique">-->
                        <!--                          <el-radio-button v-for="dict in dict.type.sys_yes_no" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio-button>-->
                        <!--                        </el-radio-group>-->
                        <!--                      </el-form-item>-->
                    </el-col>
                    <el-col :span="24">
                        <template v-if="form.discountWay == 0">
                            <el-form-item label="抵扣金额" prop="deductAmount" label-width="100px">
                                <el-input-number v-model="form.deductAmount" placeholder="请输入抵扣金额" :precision="2" :min="0" :max="999999" />
                            </el-form-item>
                            <el-form-item label="限制金额" prop="minAmount" label-width="100px">
                                <el-input-number v-model="form.minAmount" placeholder="请输入最低限制金额 0无限制" :precision="2" :min="0" :max="999999" />
                            </el-form-item>
                        </template>
                        <template v-if="form.discountWay == 1">
                            <el-form-item label="最小件数" prop="minAmount" label-width="100px">
                                <el-input-number v-model="form.minAmount" placeholder="请输入最小件数" :min="form.deductAmount" :max="999999" />
                            </el-form-item>
                            <el-form-item label="可减件数" prop="deductAmount" label-width="100px">
                                <el-input-number v-model="form.deductAmount" placeholder="请输入可减件数" :min="0" :max="form.minAmount" />
                            </el-form-item>
                        </template>
                        <template v-if="form.discountWay == 2">
                            <el-form-item label="折扣率(%)" prop="discountRate" label-width="100px">
                                <el-input-number v-model="form.discountRate" placeholder="请输入折扣率%" :step="1" :min="1" :max="99" />
                            </el-form-item>
                            <el-form-item label="最大折扣金额" prop="deductAmount" label-width="100px">
                                <el-input-number v-model="form.deductAmount" placeholder="请输入最大折扣金额" :step="0.01" :min="0" />
                            </el-form-item>
                        </template>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="库存" prop="couponStock" label-width="100px">
                            <el-input-number v-model="form.couponStock" placeholder="请输入最大折扣金额" :step="1" :min="0" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="三方品牌" prop="couponTypeThirdPartyId" label-width="100px">
                            <el-select v-model="form.couponTypeThirdPartyId" placeholder="请选择三方品牌" clearable style="width: 300px">
                                <el-option v-for="third in thirdPartyList" :key="third.id" :label="third.name" :value="third.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="描述" prop="description" label-width="100px">
                            <el-input type="textarea" v-model="form.description" placeholder="请输入优惠券类型描述" maxlength="200" show-word-limit style="width: 300px" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="发放方式" prop="sendWay">
                            <el-radio-group v-model="form.sendWay">
                                <el-radio v-for="dict in dict.type.coupon_send_way" :key="parseInt(dict.value)" :label="parseInt(dict.value)">{{ dict.label }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="适用衣服范围" prop="useScope">
                            <el-radio-group v-model="form.useScope">
                                <el-radio key="1" :label="1">全部衣服</el-radio>
                                <el-radio key="2" :label="2">指定衣服</el-radio>
                            </el-radio-group>
                            <span style="color: #aaa; display: block">若指定衣服，请在操作里面添加衣服</span>
                        </el-form-item>
                    </el-col>
                    <!--                    <el-col :span="24">-->
                    <!--                        <el-form-item label="适用工厂" prop="selectFactoryIds">-->
                    <!--                            <el-transfer v-model="form.selectFactoryIds" :data="form.factoryVOS" :filterable="true" :titles="['待选择的工厂', '已选择的工厂']"></el-transfer>-->
                    <!--                        </el-form-item>-->
                    <!--                    </el-col>-->
                    <el-col :span="24">
                        <el-form-item label="适用门店" prop="selectStoreIds">
                            <el-transfer v-model="form.selectStoreIds" :data="form.storeVOS" :filterable="true" :titles="['待选择的门店', '已选择的门店']"></el-transfer>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="状态" prop="status">
                            <el-radio-group v-model="form.status">
                                <el-radio-button v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio-button>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-form>
            </el-row>

            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm" style="margin-left: 5%">提交</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listType, getType, delType, addType, updateType, updateTypeStatus } from '@/api/coupon/type'
import { listThirdParty } from '@/api/coupon/thirdParty'

export default {
    name: 'Type',
    dicts: ['sys_normal_disable', 'coupon_send_way', 'sys_yes_no', 'coupon_type'],
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 优惠券类型表格数据
            typeList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                title: null,
                startDate: null,
                endDate: null
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                discountWay: [{ required: true, message: '优惠券类型不能为空', trigger: 'blur' }],
                title: [{ required: true, message: '优惠券类型名称不能为空', trigger: 'blur' }],
                description: [{ required: true, message: '优惠券类型描述不能为空', trigger: 'blur' }],
                imgUrl: [{ required: true, message: '优惠券类型图片不能为空', trigger: 'blur' }],
                duringDate: [{ required: true, message: '有效期不能为空', trigger: 'blur' }],
                startDate: [{ required: true, message: '有效期开始日期不能为空', trigger: 'blur' }],
                endDate: [{ required: true, message: '有效期结束日期不能为空', trigger: 'blur' }],
                status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
                isUnique: [{ required: true, message: '是否单件抵扣券不能为空', trigger: 'blur' }],
                sendWay: [{ required: true, message: '发放方式不能为空', trigger: 'blur' }],
                deductAmount: [{ required: true, message: '抵用金额不能为空', trigger: 'blur' }],
                canDeductRecharge: [{ required: true, message: '是否可抵用充值不能为空', trigger: 'blur' }],
                deductRechargeAmount: [{ required: true, message: '抵用充值金额不能为空', trigger: 'blur' }],
                minAmount: [{ required: true, message: '满减最小件数不能为空', trigger: 'blur' }]
            },
            // 日期范围
            dateRange: [],
            disabled: false,
            thirdPartyList: []
        }
    },
    created() {
        this.getThirdPartyList()
        this.getList()
    },
    methods: {
        getThirdPartyList() {
            listThirdParty({ pageSize: 99999, pageNum: 1, status: '0' }).then((response) => {
                this.thirdPartyList = response.rows
            })
        },
        /** 查询优惠券类型列表 */
        getList() {
            this.loading = true
            if (null != this.dateRange && '' != this.dateRange) {
                this.queryParams['startDate'] = this.dateRange[0]
                this.queryParams['endDate'] = this.dateRange[1]
            } else {
                delete this.queryParams.startDate
                delete this.queryParams.endDate
            }
            this.$nextTick(() => {
                this.$refs.pagination.handleSearch(true)
            })
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                title: null,
                description: null,
                imgUrl: null,
                startDate: null,
                endDate: null,
                status: '0',
                isUnique: 'Y',
                canManual: 'Y',
                canDeductRecharge: 'N',
                deductRechargeAmount: null,
                deductAmount: null,
                couponTypeThirdPartyId: null,
                delFlag: null,
                createById: null,
                createBy: null,
                createTime: null,
                updateById: null,
                updateBy: null,
                updateTime: null,
                remark: null
            }
            this.resetForm('form')
        },
        changeDiscountWay() {
            this.form.minAmount = 1
            if (this.form.discountWay == 2) {
                this.form.deductAmount = 0.01
            } else {
                this.form.deductAmount = 0
            }
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset()
            this.disabled = false
            getType().then((response) => {
                var duringDate = []
                response.data.duringDate = duringDate
                response.data.status = '0'
                response.data.isUnique = 'Y'
                response.data.canManual = 'Y'
                response.data.canDeductRecharge = 'N'
                this.form = response.data
                this.open = true
                this.title = '添加优惠券类型'
            })
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset()
            const id = row.id || this.ids
            getType(id).then((response) => {
                var duringDate = []
                duringDate.push(response.data.startDate)
                duringDate.push(response.data.endDate)
                response.data.duringDate = duringDate
                this.form = response.data
                console.log(this.form)
                this.open = true
                this.title = '修改优惠券类型'
                this.disabled = true
            })
        },
        /** 提交按钮 */
        submitForm() {
            if (null != this.form.duringDate && this.form.duringDate.length > 0) {
                this.form['startDate'] = this.form.duringDate[0]
                this.form['endDate'] = this.form.duringDate[1]
            } else {
                delete this.form.startDate
                delete this.form.endDate
            }
            if (this.form.discountWay == '2') {
                this.form.isUnique = null
            }
            // if (this.form.couponTypeThirdPartyId == null){
            //   this.form.couponTypeThirdPartyId = null;
            // }
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    if (this.form.id != null) {
                        updateType(this.form).then((response) => {
                            this.$modal.msgSuccess('修改成功')
                            this.open = false
                            this.getList()
                        })
                    } else {
                        addType(this.form).then((response) => {
                            this.$modal.msgSuccess('新增成功')
                            this.open = false
                            this.getList()
                        })
                    }
                }
            })
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids
            this.$modal
                .confirm('是否确认删除优惠券类型编号为"' + ids + '"的数据项？')
                .then(function () {
                    return delType(ids)
                })
                .then(() => {
                    this.getList()
                    this.$modal.msgSuccess('删除成功')
                })
                .catch(() => {})
        },
        /** 导出按钮操作 */
        handleExport() {
            if (null != this.dateRange && '' != this.dateRange) {
                this.queryParams['startDate'] = this.dateRange[0]
                this.queryParams['endDate'] = this.dateRange[1]
            } else {
                delete this.queryParams.startDate
                delete this.queryParams.endDate
            }
            this.download(
                'mapi/coupon/type/export',
                {
                    ...this.queryParams
                },
                `type_${new Date().getTime()}.xlsx`
            )
        },
        checkClose(done) {
            this.$confirm('是否关闭表单，关闭后数据将丢失？')
                .then(function () {
                    done()
                })
                .then(() => {})
                .catch(() => {})
        },
        handleStatusChange(row) {
            let text = row.status === '0' ? '启用' : '停用'
            this.$confirm('确认要' + text + ' ' + row.name + ' 吗？')
                .then(function () {
                    return updateTypeStatus(row.id, row.status)
                })
                .then(() => {
                    this.$modal.msgSuccess(text + '成功')
                })
                .catch(function () {
                    row.status = row.status === '0' ? '1' : '0'
                })
        },
        handleSetClothItems(row) {
            this.$tab.openPage(row.title + '的可使用衣物', '/coupon/typeApplyCloth/' + row.id)
        }
    }
}
</script>
